Change direct handle management to use an inode layer to make it consistent with...
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2007 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13
14 const char *yaffs_guts_c_version =
15     "$Id: yaffs_guts.c,v 1.105 2010-01-06 04:02:12 charles Exp $";
16
17 #include "yportenv.h"
18
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
23
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
27 #endif
28 #include "yaffs_nand.h"
29
30 #include "yaffs_checkptrw.h"
31
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
34
35
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
37
38 #include "yaffs_ecc.h"
39
40
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
44                 int erasedOk);
45 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
46                                 const __u8 *data,
47                                 const yaffs_ExtendedTags *tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
49                                 const yaffs_ExtendedTags *tags);
50
51 /* Other local prototypes */
52 static void yaffs_UpdateParent(yaffs_Object *obj);
53 static int yaffs_UnlinkObject(yaffs_Object *obj);
54 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
55
56 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
57
58 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
59                                         const __u8 *buffer,
60                                         yaffs_ExtendedTags *tags,
61                                         int useReserve);
62 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
63                                 int chunkInNAND, int inScan);
64
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66                                         yaffs_ObjectType type);
67 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
68                                 yaffs_Object *obj);
69 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
70                                 int force, int isShrink, int shadows);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
74                         int chunkOffset, int *limit);
75 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
76
77 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
78
79
80 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
81                                 int chunkInNAND);
82
83 static int yaffs_UnlinkWorker(yaffs_Object *obj);
84
85 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
86                         int chunkInObject);
87
88 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
89                                 yaffs_BlockInfo **blockUsedPtr);
90
91 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
92
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
94
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
96 #ifdef YAFFS_PARANOID
97 static int yaffs_CheckFileSanity(yaffs_Object *in);
98 #else
99 #define yaffs_CheckFileSanity(in)
100 #endif
101
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
104
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
106
107 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
108                                 yaffs_ExtendedTags *tags);
109
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
111                 unsigned pos);
112 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
113                                         yaffs_FileStructure *fStruct,
114                                         __u32 chunkId);
115
116 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
117 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
118                                         int chunkInNAND,
119                                         const __u8 *data,
120                                         yaffs_ExtendedTags *tags);
121
122 /* Function to calculate chunk and offset */
123
124 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
125                 __u32 *offsetOut)
126 {
127         int chunk;
128         __u32 offset;
129
130         chunk  = (__u32)(addr >> dev->chunkShift);
131
132         if (dev->chunkDiv == 1) {
133                 /* easy power of 2 case */
134                 offset = (__u32)(addr & dev->chunkMask);
135         } else {
136                 /* Non power-of-2 case */
137
138                 loff_t chunkBase;
139
140                 chunk /= dev->chunkDiv;
141
142                 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
143                 offset = (__u32)(addr - chunkBase);
144         }
145
146         *chunkOut = chunk;
147         *offsetOut = offset;
148 }
149
150 /* Function to return the number of shifts for a power of 2 greater than or
151  * equal to the given number
152  * Note we don't try to cater for all possible numbers and this does not have to
153  * be hellishly efficient.
154  */
155
156 static __u32 ShiftsGE(__u32 x)
157 {
158         int extraBits;
159         int nShifts;
160
161         nShifts = extraBits = 0;
162
163         while (x > 1) {
164                 if (x & 1)
165                         extraBits++;
166                 x >>= 1;
167                 nShifts++;
168         }
169
170         if (extraBits)
171                 nShifts++;
172
173         return nShifts;
174 }
175
176 /* Function to return the number of shifts to get a 1 in bit 0
177  */
178
179 static __u32 Shifts(__u32 x)
180 {
181         int nShifts;
182
183         nShifts =  0;
184
185         if (!x)
186                 return 0;
187
188         while (!(x&1)) {
189                 x >>= 1;
190                 nShifts++;
191         }
192
193         return nShifts;
194 }
195
196
197
198 /*
199  * Temporary buffer manipulations.
200  */
201
202 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
203 {
204         int i;
205         __u8 *buf = (__u8 *)1;
206
207         memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
208
209         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
210                 dev->tempBuffer[i].line = 0;    /* not in use */
211                 dev->tempBuffer[i].buffer = buf =
212                     YMALLOC_DMA(dev->totalBytesPerChunk);
213         }
214
215         return buf ? YAFFS_OK : YAFFS_FAIL;
216 }
217
218 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
219 {
220         int i, j;
221
222         dev->tempInUse++;
223         if (dev->tempInUse > dev->maxTemp)
224                 dev->maxTemp = dev->tempInUse;
225
226         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
227                 if (dev->tempBuffer[i].line == 0) {
228                         dev->tempBuffer[i].line = lineNo;
229                         if ((i + 1) > dev->maxTemp) {
230                                 dev->maxTemp = i + 1;
231                                 for (j = 0; j <= i; j++)
232                                         dev->tempBuffer[j].maxLine =
233                                             dev->tempBuffer[j].line;
234                         }
235
236                         return dev->tempBuffer[i].buffer;
237                 }
238         }
239
240         T(YAFFS_TRACE_BUFFERS,
241           (TSTR("Out of temp buffers at line %d, other held by lines:"),
242            lineNo));
243         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
244                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
245
246         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
247
248         /*
249          * If we got here then we have to allocate an unmanaged one
250          * This is not good.
251          */
252
253         dev->unmanagedTempAllocations++;
254         return YMALLOC(dev->nDataBytesPerChunk);
255
256 }
257
258 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
259                                     int lineNo)
260 {
261         int i;
262
263         dev->tempInUse--;
264
265         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
266                 if (dev->tempBuffer[i].buffer == buffer) {
267                         dev->tempBuffer[i].line = 0;
268                         return;
269                 }
270         }
271
272         if (buffer) {
273                 /* assume it is an unmanaged one. */
274                 T(YAFFS_TRACE_BUFFERS,
275                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
276                    lineNo));
277                 YFREE(buffer);
278                 dev->unmanagedTempDeallocations++;
279         }
280
281 }
282
283 /*
284  * Determine if we have a managed buffer.
285  */
286 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
287 {
288         int i;
289
290         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
291                 if (dev->tempBuffer[i].buffer == buffer)
292                         return 1;
293         }
294
295         for (i = 0; i < dev->nShortOpCaches; i++) {
296                 if (dev->srCache[i].data == buffer)
297                         return 1;
298         }
299
300         if (buffer == dev->checkpointBuffer)
301                 return 1;
302
303         T(YAFFS_TRACE_ALWAYS,
304                 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
305         return 0;
306 }
307
308
309
310 /*
311  * Chunk bitmap manipulations
312  */
313
314 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
315 {
316         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
317                 T(YAFFS_TRACE_ERROR,
318                         (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
319                         blk));
320                 YBUG();
321         }
322         return dev->chunkBits +
323                 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
324 }
325
326 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
327 {
328         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
329                         chunk < 0 || chunk >= dev->nChunksPerBlock) {
330                 T(YAFFS_TRACE_ERROR,
331                 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
332                         blk, chunk));
333                 YBUG();
334         }
335 }
336
337 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
338 {
339         __u8 *blkBits = yaffs_BlockBits(dev, blk);
340
341         memset(blkBits, 0, dev->chunkBitmapStride);
342 }
343
344 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
345 {
346         __u8 *blkBits = yaffs_BlockBits(dev, blk);
347
348         yaffs_VerifyChunkBitId(dev, blk, chunk);
349
350         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
351 }
352
353 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
354 {
355         __u8 *blkBits = yaffs_BlockBits(dev, blk);
356
357         yaffs_VerifyChunkBitId(dev, blk, chunk);
358
359         blkBits[chunk / 8] |= (1 << (chunk & 7));
360 }
361
362 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
363 {
364         __u8 *blkBits = yaffs_BlockBits(dev, blk);
365         yaffs_VerifyChunkBitId(dev, blk, chunk);
366
367         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
368 }
369
370 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
371 {
372         __u8 *blkBits = yaffs_BlockBits(dev, blk);
373         int i;
374         for (i = 0; i < dev->chunkBitmapStride; i++) {
375                 if (*blkBits)
376                         return 1;
377                 blkBits++;
378         }
379         return 0;
380 }
381
382 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
383 {
384         __u8 *blkBits = yaffs_BlockBits(dev, blk);
385         int i;
386         int n = 0;
387         for (i = 0; i < dev->chunkBitmapStride; i++) {
388                 __u8 x = *blkBits;
389                 while (x) {
390                         if (x & 1)
391                                 n++;
392                         x >>= 1;
393                 }
394
395                 blkBits++;
396         }
397         return n;
398 }
399
400 /*
401  * Verification code
402  */
403
404 static int yaffs_SkipVerification(yaffs_Device *dev)
405 {
406         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
407 }
408
409 static int yaffs_SkipFullVerification(yaffs_Device *dev)
410 {
411         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
412 }
413
414 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
415 {
416         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
417 }
418
419 static const char *blockStateName[] = {
420 "Unknown",
421 "Needs scanning",
422 "Scanning",
423 "Empty",
424 "Allocating",
425 "Full",
426 "Dirty",
427 "Checkpoint",
428 "Collecting",
429 "Dead"
430 };
431
432 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
433 {
434         int actuallyUsed;
435         int inUse;
436
437         if (yaffs_SkipVerification(dev))
438                 return;
439
440         /* Report illegal runtime states */
441         if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
442                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
443
444         switch (bi->blockState) {
445         case YAFFS_BLOCK_STATE_UNKNOWN:
446         case YAFFS_BLOCK_STATE_SCANNING:
447         case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
448                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
449                 n, blockStateName[bi->blockState]));
450         }
451
452         /* Check pages in use and soft deletions are legal */
453
454         actuallyUsed = bi->pagesInUse - bi->softDeletions;
455
456         if (bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
457            bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
458            actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
459                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
460                 n, bi->pagesInUse, bi->softDeletions));
461
462
463         /* Check chunk bitmap legal */
464         inUse = yaffs_CountChunkBits(dev, n);
465         if (inUse != bi->pagesInUse)
466                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
467                         n, bi->pagesInUse, inUse));
468
469         /* Check that the sequence number is valid.
470          * Ten million is legal, but is very unlikely
471          */
472         if (dev->isYaffs2 &&
473            (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
474            (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
475                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
476                 n, bi->sequenceNumber));
477 }
478
479 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
480                 int n)
481 {
482         yaffs_VerifyBlock(dev, bi, n);
483
484         /* After collection the block should be in the erased state */
485         /* This will need to change if we do partial gc */
486
487         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
488                         bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
489                 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
490                         n, bi->blockState));
491         }
492 }
493
494 static void yaffs_VerifyBlocks(yaffs_Device *dev)
495 {
496         int i;
497         int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
498         int nIllegalBlockStates = 0;
499
500         if (yaffs_SkipVerification(dev))
501                 return;
502
503         memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
504
505         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
506                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
507                 yaffs_VerifyBlock(dev, bi, i);
508
509                 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
510                         nBlocksPerState[bi->blockState]++;
511                 else
512                         nIllegalBlockStates++;
513         }
514
515         T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
516         T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
517
518         T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
519         if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
520                 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
521
522         for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
523                 T(YAFFS_TRACE_VERIFY,
524                   (TSTR("%s %d blocks"TENDSTR),
525                   blockStateName[i], nBlocksPerState[i]));
526
527         if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
528                 T(YAFFS_TRACE_VERIFY,
529                  (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
530                  dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
531
532         if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
533                 T(YAFFS_TRACE_VERIFY,
534                  (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
535                  dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
536
537         if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
538                 T(YAFFS_TRACE_VERIFY,
539                  (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
540                  nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
541
542         T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
543
544 }
545
546 /*
547  * Verify the object header. oh must be valid, but obj and tags may be NULL in which
548  * case those tests will not be performed.
549  */
550 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
551 {
552         if (obj && yaffs_SkipVerification(obj->myDev))
553                 return;
554
555         if (!(tags && obj && oh)) {
556                 T(YAFFS_TRACE_VERIFY,
557                                 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
558                                 tags, obj, oh));
559                 return;
560         }
561
562         if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
563                         oh->type > YAFFS_OBJECT_TYPE_MAX)
564                 T(YAFFS_TRACE_VERIFY,
565                         (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
566                         tags->objectId, oh->type));
567
568         if (tags->objectId != obj->objectId)
569                 T(YAFFS_TRACE_VERIFY,
570                         (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
571                         tags->objectId, obj->objectId));
572
573
574         /*
575          * Check that the object's parent ids match if parentCheck requested.
576          *
577          * Tests do not apply to the root object.
578          */
579
580         if (parentCheck && tags->objectId > 1 && !obj->parent)
581                 T(YAFFS_TRACE_VERIFY,
582                         (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
583                         tags->objectId, oh->parentObjectId));
584
585         if (parentCheck && obj->parent &&
586                         oh->parentObjectId != obj->parent->objectId &&
587                         (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
588                         obj->parent->objectId != YAFFS_OBJECTID_DELETED))
589                 T(YAFFS_TRACE_VERIFY,
590                         (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
591                         tags->objectId, oh->parentObjectId, obj->parent->objectId));
592
593         if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
594                 T(YAFFS_TRACE_VERIFY,
595                         (TSTR("Obj %d header name is NULL"TENDSTR),
596                         obj->objectId));
597
598         if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
599                 T(YAFFS_TRACE_VERIFY,
600                         (TSTR("Obj %d header name is 0xFF"TENDSTR),
601                         obj->objectId));
602 }
603
604
605
606 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
607                                         __u32 level, int chunkOffset)
608 {
609         int i;
610         yaffs_Device *dev = obj->myDev;
611         int ok = 1;
612
613         if (tn) {
614                 if (level > 0) {
615
616                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
617                                 if (tn->internal[i]) {
618                                         ok = yaffs_VerifyTnodeWorker(obj,
619                                                         tn->internal[i],
620                                                         level - 1,
621                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
622                                 }
623                         }
624                 } else if (level == 0) {
625                         yaffs_ExtendedTags tags;
626                         __u32 objectId = obj->objectId;
627
628                         chunkOffset <<=  YAFFS_TNODES_LEVEL0_BITS;
629
630                         for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
631                                 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
632
633                                 if (theChunk > 0) {
634                                         /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
635                                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
636                                         if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
637                                                 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
638                                                         objectId, chunkOffset, theChunk,
639                                                         tags.objectId, tags.chunkId));
640                                         }
641                                 }
642                                 chunkOffset++;
643                         }
644                 }
645         }
646
647         return ok;
648
649 }
650
651
652 static void yaffs_VerifyFile(yaffs_Object *obj)
653 {
654         int requiredTallness;
655         int actualTallness;
656         __u32 lastChunk;
657         __u32 x;
658         __u32 i;
659         yaffs_Device *dev;
660         yaffs_ExtendedTags tags;
661         yaffs_Tnode *tn;
662         __u32 objectId;
663
664         if (!obj)
665                 return;
666
667         if (yaffs_SkipVerification(obj->myDev))
668                 return;
669
670         dev = obj->myDev;
671         objectId = obj->objectId;
672
673         /* Check file size is consistent with tnode depth */
674         lastChunk =  obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
675         x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
676         requiredTallness = 0;
677         while (x > 0) {
678                 x >>= YAFFS_TNODES_INTERNAL_BITS;
679                 requiredTallness++;
680         }
681
682         actualTallness = obj->variant.fileVariant.topLevel;
683
684         if (requiredTallness > actualTallness)
685                 T(YAFFS_TRACE_VERIFY,
686                 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
687                  obj->objectId, actualTallness, requiredTallness));
688
689
690         /* Check that the chunks in the tnode tree are all correct.
691          * We do this by scanning through the tnode tree and
692          * checking the tags for every chunk match.
693          */
694
695         if (yaffs_SkipNANDVerification(dev))
696                 return;
697
698         for (i = 1; i <= lastChunk; i++) {
699                 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
700
701                 if (tn) {
702                         __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
703                         if (theChunk > 0) {
704                                 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
705                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
706                                 if (tags.objectId != objectId || tags.chunkId != i) {
707                                         T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
708                                                 objectId, i, theChunk,
709                                                 tags.objectId, tags.chunkId));
710                                 }
711                         }
712                 }
713         }
714 }
715
716
717 static void yaffs_VerifyHardLink(yaffs_Object *obj)
718 {
719         if (obj && yaffs_SkipVerification(obj->myDev))
720                 return;
721
722         /* Verify sane equivalent object */
723 }
724
725 static void yaffs_VerifySymlink(yaffs_Object *obj)
726 {
727         if (obj && yaffs_SkipVerification(obj->myDev))
728                 return;
729
730         /* Verify symlink string */
731 }
732
733 static void yaffs_VerifySpecial(yaffs_Object *obj)
734 {
735         if (obj && yaffs_SkipVerification(obj->myDev))
736                 return;
737 }
738
739 static void yaffs_VerifyObject(yaffs_Object *obj)
740 {
741         yaffs_Device *dev;
742
743         __u32 chunkMin;
744         __u32 chunkMax;
745
746         __u32 chunkIdOk;
747         __u32 chunkInRange;
748         __u32 chunkShouldNotBeDeleted;
749         __u32 chunkValid;
750
751         if (!obj)
752                 return;
753
754         if (obj->beingCreated)
755                 return;
756
757         dev = obj->myDev;
758
759         if (yaffs_SkipVerification(dev))
760                 return;
761
762         /* Check sane object header chunk */
763
764         chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
765         chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
766
767         chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
768         chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
769         chunkValid = chunkInRange &&
770                         yaffs_CheckChunkBit(dev,
771                                         obj->hdrChunk / dev->nChunksPerBlock,
772                                         obj->hdrChunk % dev->nChunksPerBlock);
773         chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
774
775         if (!obj->fake &&
776                         (!chunkIdOk || chunkShouldNotBeDeleted)) {
777                 T(YAFFS_TRACE_VERIFY,
778                         (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
779                         obj->objectId, obj->hdrChunk,
780                         chunkIdOk ? "" : ",out of range",
781                         chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
782         }
783
784         if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
785                 yaffs_ExtendedTags tags;
786                 yaffs_ObjectHeader *oh;
787                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
788
789                 oh = (yaffs_ObjectHeader *)buffer;
790
791                 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
792                                 &tags);
793
794                 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
795
796                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
797         }
798
799         /* Verify it has a parent */
800         if (obj && !obj->fake &&
801                         (!obj->parent || obj->parent->myDev != dev)) {
802                 T(YAFFS_TRACE_VERIFY,
803                         (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
804                         obj->objectId, obj->parent));
805         }
806
807         /* Verify parent is a directory */
808         if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
809                 T(YAFFS_TRACE_VERIFY,
810                         (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
811                         obj->objectId, obj->parent->variantType));
812         }
813
814         switch (obj->variantType) {
815         case YAFFS_OBJECT_TYPE_FILE:
816                 yaffs_VerifyFile(obj);
817                 break;
818         case YAFFS_OBJECT_TYPE_SYMLINK:
819                 yaffs_VerifySymlink(obj);
820                 break;
821         case YAFFS_OBJECT_TYPE_DIRECTORY:
822                 yaffs_VerifyDirectory(obj);
823                 break;
824         case YAFFS_OBJECT_TYPE_HARDLINK:
825                 yaffs_VerifyHardLink(obj);
826                 break;
827         case YAFFS_OBJECT_TYPE_SPECIAL:
828                 yaffs_VerifySpecial(obj);
829                 break;
830         case YAFFS_OBJECT_TYPE_UNKNOWN:
831         default:
832                 T(YAFFS_TRACE_VERIFY,
833                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
834                 obj->objectId, obj->variantType));
835                 break;
836         }
837 }
838
839 static void yaffs_VerifyObjects(yaffs_Device *dev)
840 {
841         yaffs_Object *obj;
842         int i;
843         struct ylist_head *lh;
844
845         if (yaffs_SkipVerification(dev))
846                 return;
847
848         /* Iterate through the objects in each hash entry */
849
850         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
851                 ylist_for_each(lh, &dev->objectBucket[i].list) {
852                         if (lh) {
853                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
854                                 yaffs_VerifyObject(obj);
855                         }
856                 }
857         }
858 }
859
860
861 /*
862  *  Simple hash function. Needs to have a reasonable spread
863  */
864
865 static Y_INLINE int yaffs_HashFunction(int n)
866 {
867         n = abs(n);
868         return n % YAFFS_NOBJECT_BUCKETS;
869 }
870
871 /*
872  * Access functions to useful fake objects.
873  * Note that root might have a presence in NAND if permissions are set.
874  */
875
876 yaffs_Object *yaffs_Root(yaffs_Device *dev)
877 {
878         return dev->rootDir;
879 }
880
881 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
882 {
883         return dev->lostNFoundDir;
884 }
885
886
887 /*
888  *  Erased NAND checking functions
889  */
890
891 int yaffs_CheckFF(__u8 *buffer, int nBytes)
892 {
893         /* Horrible, slow implementation */
894         while (nBytes--) {
895                 if (*buffer != 0xFF)
896                         return 0;
897                 buffer++;
898         }
899         return 1;
900 }
901
902 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
903                                 int chunkInNAND)
904 {
905         int retval = YAFFS_OK;
906         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
907         yaffs_ExtendedTags tags;
908         int result;
909
910         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
911
912         if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
913                 retval = YAFFS_FAIL;
914
915         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
916                 T(YAFFS_TRACE_NANDACCESS,
917                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
918                 retval = YAFFS_FAIL;
919         }
920
921         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
922
923         return retval;
924
925 }
926
927
928 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
929                                         int chunkInNAND,
930                                         const __u8 *data,
931                                         yaffs_ExtendedTags *tags)
932 {
933         int retval = YAFFS_OK;
934         yaffs_ExtendedTags tempTags;
935         __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
936         int result;
937         
938         result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
939         if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
940                 tempTags.objectId != tags->objectId ||
941                 tempTags.chunkId  != tags->chunkId ||
942                 tempTags.byteCount != tags->byteCount)
943                 retval = YAFFS_FAIL;
944
945         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
946
947         return retval;
948 }
949
950 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
951                                         const __u8 *data,
952                                         yaffs_ExtendedTags *tags,
953                                         int useReserve)
954 {
955         int attempts = 0;
956         int writeOk = 0;
957         int chunk;
958
959         yaffs_InvalidateCheckpoint(dev);
960
961         do {
962                 yaffs_BlockInfo *bi = 0;
963                 int erasedOk = 0;
964
965                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
966                 if (chunk < 0) {
967                         /* no space */
968                         break;
969                 }
970
971                 /* First check this chunk is erased, if it needs
972                  * checking.  The checking policy (unless forced
973                  * always on) is as follows:
974                  *
975                  * Check the first page we try to write in a block.
976                  * If the check passes then we don't need to check any
977                  * more.        If the check fails, we check again...
978                  * If the block has been erased, we don't need to check.
979                  *
980                  * However, if the block has been prioritised for gc,
981                  * then we think there might be something odd about
982                  * this block and stop using it.
983                  *
984                  * Rationale: We should only ever see chunks that have
985                  * not been erased if there was a partially written
986                  * chunk due to power loss.  This checking policy should
987                  * catch that case with very few checks and thus save a
988                  * lot of checks that are most likely not needed.
989                  *
990                  * Mods to the above
991                  * If an erase check fails or the write fails we skip the 
992                  * rest of the block.
993                  */
994
995                 /* let's give it a try */
996                 attempts++;
997
998 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
999                 bi->skipErasedCheck = 0;
1000 #endif
1001                 if (!bi->skipErasedCheck) {
1002                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
1003                         if (erasedOk != YAFFS_OK) {
1004                                 T(YAFFS_TRACE_ERROR,
1005                                 (TSTR("**>> yaffs chunk %d was not erased"
1006                                 TENDSTR), chunk));
1007
1008                                 /* If not erased, delete this one,
1009                                  * skip rest of block and
1010                                  * try another chunk */
1011                                  yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1012                                  yaffs_SkipRestOfBlock(dev);
1013                                 continue;
1014                         }
1015                 }
1016
1017                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1018                                 data, tags);
1019
1020                 if(!bi->skipErasedCheck)
1021                         writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1022
1023                 if (writeOk != YAFFS_OK) {
1024                         /* Clean up aborted write, skip to next block and
1025                          * try another chunk */
1026                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1027                         continue;
1028                 }
1029
1030                 bi->skipErasedCheck = 1;
1031
1032                 /* Copy the data into the robustification buffer */
1033                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1034
1035         } while (writeOk != YAFFS_OK &&
1036                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1037
1038         if (!writeOk)
1039                 chunk = -1;
1040
1041         if (attempts > 1) {
1042                 T(YAFFS_TRACE_ERROR,
1043                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1044                         attempts));
1045
1046                 dev->nRetriedWrites += (attempts - 1);
1047         }
1048
1049         return chunk;
1050 }
1051
1052 /*
1053  * Block retiring for handling a broken block.
1054  */
1055
1056 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1057 {
1058         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1059
1060         yaffs_InvalidateCheckpoint(dev);
1061
1062         if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1063                 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1064                         T(YAFFS_TRACE_ALWAYS, (TSTR(
1065                                 "yaffs: Failed to mark bad and erase block %d"
1066                                 TENDSTR), blockInNAND));
1067                 } else {
1068                         yaffs_ExtendedTags tags;
1069                         int chunkId = blockInNAND * dev->nChunksPerBlock;
1070
1071                         __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1072
1073                         memset(buffer, 0xff, dev->nDataBytesPerChunk);
1074                         yaffs_InitialiseTags(&tags);
1075                         tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1076                         if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1077                                 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1078                                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1079                                         TCONT("write bad block marker to block %d")
1080                                         TENDSTR), blockInNAND));
1081
1082                         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1083                 }
1084         }
1085
1086         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1087         bi->gcPrioritise = 0;
1088         bi->needsRetiring = 0;
1089
1090         dev->nRetiredBlocks++;
1091 }
1092
1093 /*
1094  * Functions for robustisizing TODO
1095  *
1096  */
1097
1098 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1099                                 const __u8 *data,
1100                                 const yaffs_ExtendedTags *tags)
1101 {
1102 }
1103
1104 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1105                                 const yaffs_ExtendedTags *tags)
1106 {
1107 }
1108
1109 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1110 {
1111         if (!bi->gcPrioritise) {
1112                 bi->gcPrioritise = 1;
1113                 dev->hasPendingPrioritisedGCs = 1;
1114                 bi->chunkErrorStrikes++;
1115
1116                 if (bi->chunkErrorStrikes > 3) {
1117                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1118                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1119
1120                 }
1121         }
1122 }
1123
1124 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1125                 int erasedOk)
1126 {
1127         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1128         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1129
1130         yaffs_HandleChunkError(dev, bi);
1131
1132         if (erasedOk) {
1133                 /* Was an actual write failure, so mark the block for retirement  */
1134                 bi->needsRetiring = 1;
1135                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1136                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1137         }
1138
1139         /* Delete the chunk */
1140         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1141         yaffs_SkipRestOfBlock(dev);
1142 }
1143
1144
1145 /*---------------- Name handling functions ------------*/
1146
1147 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1148 {
1149         __u16 sum = 0;
1150         __u16 i = 1;
1151
1152         const YUCHAR *bname = (const YUCHAR *) name;
1153         if (bname) {
1154                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1155
1156 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1157                         sum += yaffs_toupper(*bname) * i;
1158 #else
1159                         sum += (*bname) * i;
1160 #endif
1161                         i++;
1162                         bname++;
1163                 }
1164         }
1165         return sum;
1166 }
1167
1168 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1169 {
1170 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1171         memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1172         if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1173                 yaffs_strcpy(obj->shortName, name);
1174         else
1175                 obj->shortName[0] = _Y('\0');
1176 #endif
1177         obj->sum = yaffs_CalcNameSum(name);
1178 }
1179
1180 /*-------------------- TNODES -------------------
1181
1182  * List of spare tnodes
1183  * The list is hooked together using the first pointer
1184  * in the tnode.
1185  */
1186
1187 /* yaffs_CreateTnodes creates a bunch more tnodes and
1188  * adds them to the tnode free list.
1189  * Don't use this function directly
1190  */
1191
1192 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1193 {
1194         int i;
1195         int tnodeSize;
1196         yaffs_Tnode *newTnodes;
1197         __u8 *mem;
1198         yaffs_Tnode *curr;
1199         yaffs_Tnode *next;
1200         yaffs_TnodeList *tnl;
1201
1202         if (nTnodes < 1)
1203                 return YAFFS_OK;
1204
1205         /* Calculate the tnode size in bytes for variable width tnode support.
1206          * Must be a multiple of 32-bits  */
1207         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1208
1209         if (tnodeSize < sizeof(yaffs_Tnode))
1210                 tnodeSize = sizeof(yaffs_Tnode);
1211
1212         /* make these things */
1213
1214         newTnodes = YMALLOC(nTnodes * tnodeSize);
1215         mem = (__u8 *)newTnodes;
1216
1217         if (!newTnodes) {
1218                 T(YAFFS_TRACE_ERROR,
1219                         (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1220                 return YAFFS_FAIL;
1221         }
1222
1223         /* Hook them into the free list */
1224 #if 0
1225         for (i = 0; i < nTnodes - 1; i++) {
1226                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1227 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1228                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1229 #endif
1230         }
1231
1232         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1233 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1234         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1235 #endif
1236         dev->freeTnodes = newTnodes;
1237 #else
1238         /* New hookup for wide tnodes */
1239         for (i = 0; i < nTnodes - 1; i++) {
1240                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1241                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1242                 curr->internal[0] = next;
1243         }
1244
1245         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1246         curr->internal[0] = dev->freeTnodes;
1247         dev->freeTnodes = (yaffs_Tnode *)mem;
1248
1249 #endif
1250
1251
1252         dev->nFreeTnodes += nTnodes;
1253         dev->nTnodesCreated += nTnodes;
1254
1255         /* Now add this bunch of tnodes to a list for freeing up.
1256          * NB If we can't add this to the management list it isn't fatal
1257          * but it just means we can't free this bunch of tnodes later.
1258          */
1259
1260         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1261         if (!tnl) {
1262                 T(YAFFS_TRACE_ERROR,
1263                   (TSTR
1264                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1265                    return YAFFS_FAIL;
1266         } else {
1267                 tnl->tnodes = newTnodes;
1268                 tnl->next = dev->allocatedTnodeList;
1269                 dev->allocatedTnodeList = tnl;
1270         }
1271
1272         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1273
1274         return YAFFS_OK;
1275 }
1276
1277 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1278
1279 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1280 {
1281         yaffs_Tnode *tn = NULL;
1282
1283         /* If there are none left make more */
1284         if (!dev->freeTnodes)
1285                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1286
1287         if (dev->freeTnodes) {
1288                 tn = dev->freeTnodes;
1289 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1290                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1291                         /* Hoosterman, this thing looks like it isn't in the list */
1292                         T(YAFFS_TRACE_ALWAYS,
1293                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1294                 }
1295 #endif
1296                 dev->freeTnodes = dev->freeTnodes->internal[0];
1297                 dev->nFreeTnodes--;
1298         }
1299
1300         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1301
1302         return tn;
1303 }
1304
1305 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1306 {
1307         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1308         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1309
1310         if (tnodeSize < sizeof(yaffs_Tnode))
1311                 tnodeSize = sizeof(yaffs_Tnode);
1312
1313         if (tn)
1314                 memset(tn, 0, tnodeSize);
1315
1316         return tn;
1317 }
1318
1319 /* FreeTnode frees up a tnode and puts it back on the free list */
1320 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1321 {
1322         if (tn) {
1323 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1324                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1325                         /* Hoosterman, this thing looks like it is already in the list */
1326                         T(YAFFS_TRACE_ALWAYS,
1327                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1328                 }
1329                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1330 #endif
1331                 tn->internal[0] = dev->freeTnodes;
1332                 dev->freeTnodes = tn;
1333                 dev->nFreeTnodes++;
1334         }
1335         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1336 }
1337
1338 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1339 {
1340         /* Free the list of allocated tnodes */
1341         yaffs_TnodeList *tmp;
1342
1343         while (dev->allocatedTnodeList) {
1344                 tmp = dev->allocatedTnodeList->next;
1345
1346                 YFREE(dev->allocatedTnodeList->tnodes);
1347                 YFREE(dev->allocatedTnodeList);
1348                 dev->allocatedTnodeList = tmp;
1349
1350         }
1351
1352         dev->freeTnodes = NULL;
1353         dev->nFreeTnodes = 0;
1354         dev->nTnodesCreated = 0;
1355 }
1356
1357 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1358 {
1359         dev->allocatedTnodeList = NULL;
1360         dev->freeTnodes = NULL;
1361         dev->nFreeTnodes = 0;
1362         dev->nTnodesCreated = 0;
1363 }
1364
1365
1366 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1367                 unsigned val)
1368 {
1369         __u32 *map = (__u32 *)tn;
1370         __u32 bitInMap;
1371         __u32 bitInWord;
1372         __u32 wordInMap;
1373         __u32 mask;
1374
1375         pos &= YAFFS_TNODES_LEVEL0_MASK;
1376         val >>= dev->chunkGroupBits;
1377
1378         bitInMap = pos * dev->tnodeWidth;
1379         wordInMap = bitInMap / 32;
1380         bitInWord = bitInMap & (32 - 1);
1381
1382         mask = dev->tnodeMask << bitInWord;
1383
1384         map[wordInMap] &= ~mask;
1385         map[wordInMap] |= (mask & (val << bitInWord));
1386
1387         if (dev->tnodeWidth > (32 - bitInWord)) {
1388                 bitInWord = (32 - bitInWord);
1389                 wordInMap++;;
1390                 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1391                 map[wordInMap] &= ~mask;
1392                 map[wordInMap] |= (mask & (val >> bitInWord));
1393         }
1394 }
1395
1396 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1397                 unsigned pos)
1398 {
1399         __u32 *map = (__u32 *)tn;
1400         __u32 bitInMap;
1401         __u32 bitInWord;
1402         __u32 wordInMap;
1403         __u32 val;
1404
1405         pos &= YAFFS_TNODES_LEVEL0_MASK;
1406
1407         bitInMap = pos * dev->tnodeWidth;
1408         wordInMap = bitInMap / 32;
1409         bitInWord = bitInMap & (32 - 1);
1410
1411         val = map[wordInMap] >> bitInWord;
1412
1413         if      (dev->tnodeWidth > (32 - bitInWord)) {
1414                 bitInWord = (32 - bitInWord);
1415                 wordInMap++;;
1416                 val |= (map[wordInMap] << bitInWord);
1417         }
1418
1419         val &= dev->tnodeMask;
1420         val <<= dev->chunkGroupBits;
1421
1422         return val;
1423 }
1424
1425 /* ------------------- End of individual tnode manipulation -----------------*/
1426
1427 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1428  * The look up tree is represented by the top tnode and the number of topLevel
1429  * in the tree. 0 means only the level 0 tnode is in the tree.
1430  */
1431
1432 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1433 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1434                                         yaffs_FileStructure *fStruct,
1435                                         __u32 chunkId)
1436 {
1437         yaffs_Tnode *tn = fStruct->top;
1438         __u32 i;
1439         int requiredTallness;
1440         int level = fStruct->topLevel;
1441
1442         /* Check sane level and chunk Id */
1443         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1444                 return NULL;
1445
1446         if (chunkId > YAFFS_MAX_CHUNK_ID)
1447                 return NULL;
1448
1449         /* First check we're tall enough (ie enough topLevel) */
1450
1451         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1452         requiredTallness = 0;
1453         while (i) {
1454                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1455                 requiredTallness++;
1456         }
1457
1458         if (requiredTallness > fStruct->topLevel)
1459                 return NULL; /* Not tall enough, so we can't find it */
1460
1461         /* Traverse down to level 0 */
1462         while (level > 0 && tn) {
1463                 tn = tn->internal[(chunkId >>
1464                         (YAFFS_TNODES_LEVEL0_BITS +
1465                                 (level - 1) *
1466                                 YAFFS_TNODES_INTERNAL_BITS)) &
1467                         YAFFS_TNODES_INTERNAL_MASK];
1468                 level--;
1469         }
1470
1471         return tn;
1472 }
1473
1474 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1475  * This happens in two steps:
1476  *  1. If the tree isn't tall enough, then make it taller.
1477  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1478  *
1479  * Used when modifying the tree.
1480  *
1481  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1482  *  be plugged into the ttree.
1483  */
1484
1485 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1486                                         yaffs_FileStructure *fStruct,
1487                                         __u32 chunkId,
1488                                         yaffs_Tnode *passedTn)
1489 {
1490         int requiredTallness;
1491         int i;
1492         int l;
1493         yaffs_Tnode *tn;
1494
1495         __u32 x;
1496
1497
1498         /* Check sane level and page Id */
1499         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1500                 return NULL;
1501
1502         if (chunkId > YAFFS_MAX_CHUNK_ID)
1503                 return NULL;
1504
1505         /* First check we're tall enough (ie enough topLevel) */
1506
1507         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1508         requiredTallness = 0;
1509         while (x) {
1510                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1511                 requiredTallness++;
1512         }
1513
1514
1515         if (requiredTallness > fStruct->topLevel) {
1516                 /* Not tall enough, gotta make the tree taller */
1517                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1518
1519                         tn = yaffs_GetTnode(dev);
1520
1521                         if (tn) {
1522                                 tn->internal[0] = fStruct->top;
1523                                 fStruct->top = tn;
1524                                 fStruct->topLevel++;
1525                         } else {
1526                                 T(YAFFS_TRACE_ERROR,
1527                                         (TSTR("yaffs: no more tnodes" TENDSTR)));
1528                                 return NULL;
1529                         }
1530                 }
1531         }
1532
1533         /* Traverse down to level 0, adding anything we need */
1534
1535         l = fStruct->topLevel;
1536         tn = fStruct->top;
1537
1538         if (l > 0) {
1539                 while (l > 0 && tn) {
1540                         x = (chunkId >>
1541                              (YAFFS_TNODES_LEVEL0_BITS +
1542                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1543                             YAFFS_TNODES_INTERNAL_MASK;
1544
1545
1546                         if ((l > 1) && !tn->internal[x]) {
1547                                 /* Add missing non-level-zero tnode */
1548                                 tn->internal[x] = yaffs_GetTnode(dev);
1549                                 if(!tn->internal[x])
1550                                         return NULL;
1551
1552                         } else if (l == 1) {
1553                                 /* Looking from level 1 at level 0 */
1554                                 if (passedTn) {
1555                                         /* If we already have one, then release it.*/
1556                                         if (tn->internal[x])
1557                                                 yaffs_FreeTnode(dev, tn->internal[x]);
1558                                         tn->internal[x] = passedTn;
1559
1560                                 } else if (!tn->internal[x]) {
1561                                         /* Don't have one, none passed in */
1562                                         tn->internal[x] = yaffs_GetTnode(dev);
1563                                         if(!tn->internal[x])
1564                                                 return NULL;
1565                                 }
1566                         }
1567
1568                         tn = tn->internal[x];
1569                         l--;
1570                 }
1571         } else {
1572                 /* top is level 0 */
1573                 if (passedTn) {
1574                         memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1575                         yaffs_FreeTnode(dev, passedTn);
1576                 }
1577         }
1578
1579         return tn;
1580 }
1581
1582 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1583                                 yaffs_ExtendedTags *tags, int objectId,
1584                                 int chunkInInode)
1585 {
1586         int j;
1587
1588         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1589                 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1590                                 theChunk % dev->nChunksPerBlock)) {
1591                         
1592                         if(dev->chunkGroupSize == 1)
1593                                 return theChunk;
1594                         else {
1595                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1596                                                                 tags);
1597                                 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1598                                         /* found it; */
1599                                         return theChunk;
1600                                 }
1601                         }
1602                 }
1603                 theChunk++;
1604         }
1605         return -1;
1606 }
1607
1608
1609 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1610  * chunks and tnodes in the file
1611  * Returns 1 if the tree was deleted.
1612  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1613  */
1614
1615 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1616                               int chunkOffset, int *limit)
1617 {
1618         int i;
1619         int chunkInInode;
1620         int theChunk;
1621         yaffs_ExtendedTags tags;
1622         int foundChunk;
1623         yaffs_Device *dev = in->myDev;
1624
1625         int allDone = 1;
1626
1627         if (tn) {
1628                 if (level > 0) {
1629                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1630                              i--) {
1631                                 if (tn->internal[i]) {
1632                                         if (limit && (*limit) < 0) {
1633                                                 allDone = 0;
1634                                         } else {
1635                                                 allDone =
1636                                                         yaffs_DeleteWorker(in,
1637                                                                 tn->
1638                                                                 internal
1639                                                                 [i],
1640                                                                 level -
1641                                                                 1,
1642                                                                 (chunkOffset
1643                                                                         <<
1644                                                                         YAFFS_TNODES_INTERNAL_BITS)
1645                                                                 + i,
1646                                                                 limit);
1647                                         }
1648                                         if (allDone) {
1649                                                 yaffs_FreeTnode(dev,
1650                                                                 tn->
1651                                                                 internal[i]);
1652                                                 tn->internal[i] = NULL;
1653                                         }
1654                                 }
1655                         }
1656                         return (allDone) ? 1 : 0;
1657                 } else if (level == 0) {
1658                         int hitLimit = 0;
1659
1660                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1661                                         i--) {
1662                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1663                                 if (theChunk) {
1664
1665                                         chunkInInode = (chunkOffset <<
1666                                                 YAFFS_TNODES_LEVEL0_BITS) + i;
1667
1668                                         foundChunk =
1669                                                 yaffs_FindChunkInGroup(dev,
1670                                                                 theChunk,
1671                                                                 &tags,
1672                                                                 in->objectId,
1673                                                                 chunkInInode);
1674
1675                                         if (foundChunk > 0) {
1676                                                 yaffs_DeleteChunk(dev,
1677                                                                   foundChunk, 1,
1678                                                                   __LINE__);
1679                                                 in->nDataChunks--;
1680                                                 if (limit) {
1681                                                         *limit = *limit - 1;
1682                                                         if (*limit <= 0)
1683                                                                 hitLimit = 1;
1684                                                 }
1685
1686                                         }
1687
1688                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1689                                 }
1690
1691                         }
1692                         return (i < 0) ? 1 : 0;
1693
1694                 }
1695
1696         }
1697
1698         return 1;
1699
1700 }
1701
1702 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1703 {
1704         yaffs_BlockInfo *theBlock;
1705
1706         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1707
1708         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1709         if (theBlock) {
1710                 theBlock->softDeletions++;
1711                 dev->nFreeChunks++;
1712         }
1713 }
1714
1715 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1716  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1717  * of the tnode.
1718  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1719  */
1720
1721 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1722                                   __u32 level, int chunkOffset)
1723 {
1724         int i;
1725         int theChunk;
1726         int allDone = 1;
1727         yaffs_Device *dev = in->myDev;
1728
1729         if (tn) {
1730                 if (level > 0) {
1731
1732                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1733                              i--) {
1734                                 if (tn->internal[i]) {
1735                                         allDone =
1736                                             yaffs_SoftDeleteWorker(in,
1737                                                                    tn->
1738                                                                    internal[i],
1739                                                                    level - 1,
1740                                                                    (chunkOffset
1741                                                                     <<
1742                                                                     YAFFS_TNODES_INTERNAL_BITS)
1743                                                                    + i);
1744                                         if (allDone) {
1745                                                 yaffs_FreeTnode(dev,
1746                                                                 tn->
1747                                                                 internal[i]);
1748                                                 tn->internal[i] = NULL;
1749                                         } else {
1750                                                 /* Hoosterman... how could this happen? */
1751                                         }
1752                                 }
1753                         }
1754                         return (allDone) ? 1 : 0;
1755                 } else if (level == 0) {
1756
1757                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1758                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1759                                 if (theChunk) {
1760                                         /* Note this does not find the real chunk, only the chunk group.
1761                                          * We make an assumption that a chunk group is not larger than
1762                                          * a block.
1763                                          */
1764                                         yaffs_SoftDeleteChunk(dev, theChunk);
1765                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1766                                 }
1767
1768                         }
1769                         return 1;
1770
1771                 }
1772
1773         }
1774
1775         return 1;
1776
1777 }
1778
1779 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1780 {
1781         if (obj->deleted &&
1782             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1783                 if (obj->nDataChunks <= 0) {
1784                         /* Empty file with no duplicate object headers, just delete it immediately */
1785                         yaffs_FreeTnode(obj->myDev,
1786                                         obj->variant.fileVariant.top);
1787                         obj->variant.fileVariant.top = NULL;
1788                         T(YAFFS_TRACE_TRACING,
1789                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1790                            obj->objectId));
1791                         yaffs_DoGenericObjectDeletion(obj);
1792                 } else {
1793                         yaffs_SoftDeleteWorker(obj,
1794                                                obj->variant.fileVariant.top,
1795                                                obj->variant.fileVariant.
1796                                                topLevel, 0);
1797                         obj->softDeleted = 1;
1798                 }
1799         }
1800 }
1801
1802 /* Pruning removes any part of the file structure tree that is beyond the
1803  * bounds of the file (ie that does not point to chunks).
1804  *
1805  * A file should only get pruned when its size is reduced.
1806  *
1807  * Before pruning, the chunks must be pulled from the tree and the
1808  * level 0 tnode entries must be zeroed out.
1809  * Could also use this for file deletion, but that's probably better handled
1810  * by a special case.
1811  *
1812  * This function is recursive. For levels > 0 the function is called again on
1813  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1814  * If there is no data in a subtree then it is pruned.
1815  */
1816
1817 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1818                                 __u32 level, int del0)
1819 {
1820         int i;
1821         int hasData;
1822
1823         if (tn) {
1824                 hasData = 0;
1825
1826                 if(level > 0){
1827                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1828                                 if (tn->internal[i]) {
1829                                         tn->internal[i] =
1830                                                 yaffs_PruneWorker(dev, tn->internal[i],
1831                                                         level - 1,
1832                                                         (i == 0) ? del0 : 1);
1833                                 }
1834
1835                                 if (tn->internal[i])
1836                                         hasData++;
1837                         }
1838                 } else {
1839                         int tnodeSize;
1840                         __u32 *map = (__u32 *)tn;
1841                         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1842
1843                         if (tnodeSize < sizeof(yaffs_Tnode))
1844                                 tnodeSize = sizeof(yaffs_Tnode);
1845                         tnodeSize /= sizeof(__u32);
1846
1847                         for(i = 0; !hasData && i < tnodeSize; i++){
1848                                 if(map[i])
1849                                         hasData++;
1850                         }
1851                 }
1852
1853                 if (hasData == 0 && del0) {
1854                         /* Free and return NULL */
1855
1856                         yaffs_FreeTnode(dev, tn);
1857                         tn = NULL;
1858                 }
1859
1860         }
1861
1862         return tn;
1863
1864 }
1865
1866 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1867                                 yaffs_FileStructure *fStruct)
1868 {
1869         int i;
1870         int hasData;
1871         int done = 0;
1872         yaffs_Tnode *tn;
1873
1874         if (fStruct->topLevel > 0) {
1875                 fStruct->top =
1876                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1877
1878                 /* Now we have a tree with all the non-zero branches NULL but the height
1879                  * is the same as it was.
1880                  * Let's see if we can trim internal tnodes to shorten the tree.
1881                  * We can do this if only the 0th element in the tnode is in use
1882                  * (ie all the non-zero are NULL)
1883                  */
1884
1885                 while (fStruct->topLevel && !done) {
1886                         tn = fStruct->top;
1887
1888                         hasData = 0;
1889                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1890                                 if (tn->internal[i])
1891                                         hasData++;
1892                         }
1893
1894                         if (!hasData) {
1895                                 fStruct->top = tn->internal[0];
1896                                 fStruct->topLevel--;
1897                                 yaffs_FreeTnode(dev, tn);
1898                         } else {
1899                                 done = 1;
1900                         }
1901                 }
1902         }
1903
1904         return YAFFS_OK;
1905 }
1906
1907 /*-------------------- End of File Structure functions.-------------------*/
1908
1909 /* yaffs_CreateFreeObjects creates a bunch more objects and
1910  * adds them to the object free list.
1911  */
1912 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1913 {
1914         int i;
1915         yaffs_Object *newObjects;
1916         yaffs_ObjectList *list;
1917
1918         if (nObjects < 1)
1919                 return YAFFS_OK;
1920
1921         /* make these things */
1922         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1923         list = YMALLOC(sizeof(yaffs_ObjectList));
1924
1925         if (!newObjects || !list) {
1926                 if (newObjects){
1927                         YFREE(newObjects);
1928                         newObjects = NULL;
1929                 }
1930                 if (list){
1931                         YFREE(list);
1932                         list = NULL;
1933                 }
1934                 T(YAFFS_TRACE_ALLOCATE,
1935                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1936                 return YAFFS_FAIL;
1937         }
1938
1939         /* Hook them into the free list */
1940         for (i = 0; i < nObjects - 1; i++) {
1941                 newObjects[i].siblings.next =
1942                                 (struct ylist_head *)(&newObjects[i + 1]);
1943         }
1944
1945         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1946         dev->freeObjects = newObjects;
1947         dev->nFreeObjects += nObjects;
1948         dev->nObjectsCreated += nObjects;
1949
1950         /* Now add this bunch of Objects to a list for freeing up. */
1951
1952         list->objects = newObjects;
1953         list->next = dev->allocatedObjectList;
1954         dev->allocatedObjectList = list;
1955
1956         return YAFFS_OK;
1957 }
1958
1959
1960 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1961 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1962 {
1963         yaffs_Object *tn = NULL;
1964
1965 #ifdef VALGRIND_TEST
1966         tn = YMALLOC(sizeof(yaffs_Object));
1967 #else
1968         /* If there are none left make more */
1969         if (!dev->freeObjects)
1970                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1971
1972         if (dev->freeObjects) {
1973                 tn = dev->freeObjects;
1974                 dev->freeObjects =
1975                         (yaffs_Object *) (dev->freeObjects->siblings.next);
1976                 dev->nFreeObjects--;
1977         }
1978 #endif
1979         if (tn) {
1980                 /* Now sweeten it up... */
1981
1982                 memset(tn, 0, sizeof(yaffs_Object));
1983                 tn->beingCreated = 1;
1984
1985                 tn->myDev = dev;
1986                 tn->hdrChunk = 0;
1987                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1988                 YINIT_LIST_HEAD(&(tn->hardLinks));
1989                 YINIT_LIST_HEAD(&(tn->hashLink));
1990                 YINIT_LIST_HEAD(&tn->siblings);
1991
1992
1993                 /* Now make the directory sane */
1994                 if (dev->rootDir) {
1995                         tn->parent = dev->rootDir;
1996                         ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1997                 }
1998
1999                 /* Add it to the lost and found directory.
2000                  * NB Can't put root or lostNFound in lostNFound so
2001                  * check if lostNFound exists first
2002                  */
2003                 if (dev->lostNFoundDir)
2004                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2005
2006                 tn->beingCreated = 0;
2007         }
2008
2009         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2010
2011         return tn;
2012 }
2013
2014 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2015                                                __u32 mode)
2016 {
2017
2018         yaffs_Object *obj =
2019             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2020         if (obj) {
2021                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
2022                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2023                 obj->unlinkAllowed = 0; /* ... or unlink it */
2024                 obj->deleted = 0;
2025                 obj->unlinked = 0;
2026                 obj->yst_mode = mode;
2027                 obj->myDev = dev;
2028                 obj->hdrChunk = 0;      /* Not a valid chunk. */
2029         }
2030
2031         return obj;
2032
2033 }
2034
2035 static void yaffs_UnhashObject(yaffs_Object *tn)
2036 {
2037         int bucket;
2038         yaffs_Device *dev = tn->myDev;
2039
2040         /* If it is still linked into the bucket list, free from the list */
2041         if (!ylist_empty(&tn->hashLink)) {
2042                 ylist_del_init(&tn->hashLink);
2043                 bucket = yaffs_HashFunction(tn->objectId);
2044                 dev->objectBucket[bucket].count--;
2045         }
2046 }
2047
2048 /*  FreeObject frees up a Object and puts it back on the free list */
2049 static void yaffs_FreeObject(yaffs_Object *tn)
2050 {
2051         yaffs_Device *dev = tn->myDev;
2052
2053         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2054
2055         if (tn->parent)
2056                 YBUG();
2057         if (!ylist_empty(&tn->siblings))
2058                 YBUG();
2059
2060
2061         if (tn->myInode) {
2062                 /* We're still hooked up to a cached inode.
2063                  * Don't delete now, but mark for later deletion
2064                  */
2065                 tn->deferedFree = 1;
2066                 return;
2067         }
2068
2069         yaffs_UnhashObject(tn);
2070
2071 #ifdef VALGRIND_TEST
2072         YFREE(tn);
2073         tn = NULL;
2074 #else
2075         /* Link into the free list. */
2076         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2077         dev->freeObjects = tn;
2078         dev->nFreeObjects++;
2079 #endif
2080         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2081 }
2082
2083 #ifdef __KERNEL__
2084
2085 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2086 {
2087         if (obj->deferedFree)
2088                 yaffs_FreeObject(obj);
2089 }
2090
2091 #endif
2092
2093 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2094 {
2095         /* Free the list of allocated Objects */
2096
2097         yaffs_ObjectList *tmp;
2098
2099         while (dev->allocatedObjectList) {
2100                 tmp = dev->allocatedObjectList->next;
2101                 YFREE(dev->allocatedObjectList->objects);
2102                 YFREE(dev->allocatedObjectList);
2103
2104                 dev->allocatedObjectList = tmp;
2105         }
2106
2107         dev->freeObjects = NULL;
2108         dev->nFreeObjects = 0;
2109         dev->nObjectsCreated = 0;
2110 }
2111
2112 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2113 {
2114         int i;
2115
2116         dev->allocatedObjectList = NULL;
2117         dev->freeObjects = NULL;
2118         dev->nFreeObjects = 0;
2119
2120         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2121                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2122                 dev->objectBucket[i].count = 0;
2123         }
2124 }
2125
2126 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2127 {
2128         static int x;
2129         int i;
2130         int l = 999;
2131         int lowest = 999999;
2132
2133         /* First let's see if we can find one that's empty. */
2134
2135         for (i = 0; i < 10 && lowest > 0; i++) {
2136                 x++;
2137                 x %= YAFFS_NOBJECT_BUCKETS;
2138                 if (dev->objectBucket[x].count < lowest) {
2139                         lowest = dev->objectBucket[x].count;
2140                         l = x;
2141                 }
2142
2143         }
2144
2145         /* If we didn't find an empty list, then try
2146          * looking a bit further for a short one
2147          */
2148
2149         for (i = 0; i < 10 && lowest > 3; i++) {
2150                 x++;
2151                 x %= YAFFS_NOBJECT_BUCKETS;
2152                 if (dev->objectBucket[x].count < lowest) {
2153                         lowest = dev->objectBucket[x].count;
2154                         l = x;
2155                 }
2156
2157         }
2158
2159         return l;
2160 }
2161
2162 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2163 {
2164         int bucket = yaffs_FindNiceObjectBucket(dev);
2165
2166         /* Now find an object value that has not already been taken
2167          * by scanning the list.
2168          */
2169
2170         int found = 0;
2171         struct ylist_head *i;
2172
2173         __u32 n = (__u32) bucket;
2174
2175         /* yaffs_CheckObjectHashSanity();  */
2176
2177         while (!found) {
2178                 found = 1;
2179                 n += YAFFS_NOBJECT_BUCKETS;
2180                 if (1 || dev->objectBucket[bucket].count > 0) {
2181                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2182                                 /* If there is already one in the list */
2183                                 if (i && ylist_entry(i, yaffs_Object,
2184                                                 hashLink)->objectId == n) {
2185                                         found = 0;
2186                                 }
2187                         }
2188                 }
2189         }
2190
2191         return n;
2192 }
2193
2194 static void yaffs_HashObject(yaffs_Object *in)
2195 {
2196         int bucket = yaffs_HashFunction(in->objectId);
2197         yaffs_Device *dev = in->myDev;
2198
2199         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2200         dev->objectBucket[bucket].count++;
2201 }
2202
2203 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2204 {
2205         int bucket = yaffs_HashFunction(number);
2206         struct ylist_head *i;
2207         yaffs_Object *in;
2208
2209         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2210                 /* Look if it is in the list */
2211                 if (i) {
2212                         in = ylist_entry(i, yaffs_Object, hashLink);
2213                         if (in->objectId == number) {
2214 #ifdef __KERNEL__
2215                                 /* Don't tell the VFS about this one if it is defered free */
2216                                 if (in->deferedFree)
2217                                         return NULL;
2218 #endif
2219
2220                                 return in;
2221                         }
2222                 }
2223         }
2224
2225         return NULL;
2226 }
2227
2228 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2229                                     yaffs_ObjectType type)
2230 {
2231         yaffs_Object *theObject;
2232         yaffs_Tnode *tn = NULL;
2233
2234         if (number < 0)
2235                 number = yaffs_CreateNewObjectNumber(dev);
2236
2237         if (type == YAFFS_OBJECT_TYPE_FILE) {
2238                 tn = yaffs_GetTnode(dev);
2239                 if (!tn)
2240                         return NULL;
2241         }
2242
2243         theObject = yaffs_AllocateEmptyObject(dev);
2244         if (!theObject){
2245                 if(tn)
2246                         yaffs_FreeTnode(dev,tn);
2247                 return NULL;
2248         }
2249
2250
2251         if (theObject) {
2252                 theObject->fake = 0;
2253                 theObject->renameAllowed = 1;
2254                 theObject->unlinkAllowed = 1;
2255                 theObject->objectId = number;
2256                 yaffs_HashObject(theObject);
2257                 theObject->variantType = type;
2258 #ifdef CONFIG_YAFFS_WINCE
2259                 yfsd_WinFileTimeNow(theObject->win_atime);
2260                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2261                     theObject->win_atime[0];
2262                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2263                     theObject->win_atime[1];
2264
2265 #else
2266
2267                 theObject->yst_atime = theObject->yst_mtime =
2268                     theObject->yst_ctime = Y_CURRENT_TIME;
2269 #endif
2270                 switch (type) {
2271                 case YAFFS_OBJECT_TYPE_FILE:
2272                         theObject->variant.fileVariant.fileSize = 0;
2273                         theObject->variant.fileVariant.scannedFileSize = 0;
2274                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2275                         theObject->variant.fileVariant.topLevel = 0;
2276                         theObject->variant.fileVariant.top = tn;
2277                         break;
2278                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2279                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2280                                         children);
2281                         break;
2282                 case YAFFS_OBJECT_TYPE_SYMLINK:
2283                 case YAFFS_OBJECT_TYPE_HARDLINK:
2284                 case YAFFS_OBJECT_TYPE_SPECIAL:
2285                         /* No action required */
2286                         break;
2287                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2288                         /* todo this should not happen */
2289                         break;
2290                 }
2291         }
2292
2293         return theObject;
2294 }
2295
2296 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2297                                                       int number,
2298                                                       yaffs_ObjectType type)
2299 {
2300         yaffs_Object *theObject = NULL;
2301
2302         if (number > 0)
2303                 theObject = yaffs_FindObjectByNumber(dev, number);
2304
2305         if (!theObject)
2306                 theObject = yaffs_CreateNewObject(dev, number, type);
2307
2308         return theObject;
2309
2310 }
2311
2312
2313 static YCHAR *yaffs_CloneString(const YCHAR *str)
2314 {
2315         YCHAR *newStr = NULL;
2316         int len;
2317
2318         if (!str)
2319                 str = _Y("");
2320
2321         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2322         newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2323         if (newStr){
2324                 yaffs_strncpy(newStr, str,len);
2325                 newStr[len] = 0;
2326         }
2327         return newStr;
2328
2329 }
2330
2331 /*
2332  * Mknod (create) a new object.
2333  * equivalentObject only has meaning for a hard link;
2334  * aliasString only has meaning for a symlink.
2335  * rdev only has meaning for devices (a subset of special objects)
2336  */
2337
2338 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2339                                        yaffs_Object *parent,
2340                                        const YCHAR *name,
2341                                        __u32 mode,
2342                                        __u32 uid,
2343                                        __u32 gid,
2344                                        yaffs_Object *equivalentObject,
2345                                        const YCHAR *aliasString, __u32 rdev)
2346 {
2347         yaffs_Object *in;
2348         YCHAR *str = NULL;
2349
2350         yaffs_Device *dev = parent->myDev;
2351
2352         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2353         if (yaffs_FindObjectByName(parent, name))
2354                 return NULL;
2355
2356         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2357                 str = yaffs_CloneString(aliasString);
2358                 if (!str)
2359                         return NULL;
2360         }
2361
2362         in = yaffs_CreateNewObject(dev, -1, type);
2363
2364         if (!in){
2365                 if(str)
2366                         YFREE(str);
2367                 return NULL;
2368         }
2369
2370
2371
2372
2373         if (in) {
2374                 in->hdrChunk = 0;
2375                 in->valid = 1;
2376                 in->variantType = type;
2377
2378                 in->yst_mode = mode;
2379
2380 #ifdef CONFIG_YAFFS_WINCE
2381                 yfsd_WinFileTimeNow(in->win_atime);
2382                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2383                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2384
2385 #else
2386                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2387
2388                 in->yst_rdev = rdev;
2389                 in->yst_uid = uid;
2390                 in->yst_gid = gid;
2391 #endif
2392                 in->nDataChunks = 0;
2393
2394                 yaffs_SetObjectName(in, name);
2395                 in->dirty = 1;
2396
2397                 yaffs_AddObjectToDirectory(parent, in);
2398
2399                 in->myDev = parent->myDev;
2400
2401                 switch (type) {
2402                 case YAFFS_OBJECT_TYPE_SYMLINK:
2403                         in->variant.symLinkVariant.alias = str;
2404                         break;
2405                 case YAFFS_OBJECT_TYPE_HARDLINK:
2406                         in->variant.hardLinkVariant.equivalentObject =
2407                                 equivalentObject;
2408                         in->variant.hardLinkVariant.equivalentObjectId =
2409                                 equivalentObject->objectId;
2410                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2411                         break;
2412                 case YAFFS_OBJECT_TYPE_FILE:
2413                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2414                 case YAFFS_OBJECT_TYPE_SPECIAL:
2415                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2416                         /* do nothing */
2417                         break;
2418                 }
2419
2420                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2421                         /* Could not create the object header, fail the creation */
2422                         yaffs_DeleteObject(in);
2423                         in = NULL;
2424                 }
2425
2426                 yaffs_UpdateParent(parent);
2427         }
2428
2429         return in;
2430 }
2431
2432 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2433                         __u32 mode, __u32 uid, __u32 gid)
2434 {
2435         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2436                                 uid, gid, NULL, NULL, 0);
2437 }
2438
2439 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2440                                 __u32 mode, __u32 uid, __u32 gid)
2441 {
2442         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2443                                  mode, uid, gid, NULL, NULL, 0);
2444 }
2445
2446 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2447                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2448 {
2449         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2450                                  uid, gid, NULL, NULL, rdev);
2451 }
2452
2453 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2454                                 __u32 mode, __u32 uid, __u32 gid,
2455                                 const YCHAR *alias)
2456 {
2457         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2458                                 uid, gid, NULL, alias, 0);
2459 }
2460
2461 /* yaffs_Link returns the object id of the equivalent object.*/
2462 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2463                         yaffs_Object *equivalentObject)
2464 {
2465         /* Get the real object in case we were fed a hard link as an equivalent object */
2466         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2467
2468         if (yaffs_MknodObject
2469             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2470              equivalentObject, NULL, 0)) {
2471                 return equivalentObject;
2472         } else {
2473                 return NULL;
2474         }
2475
2476 }
2477
2478 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2479                                 const YCHAR *newName, int force, int shadows)
2480 {
2481         int unlinkOp;
2482         int deleteOp;
2483
2484         yaffs_Object *existingTarget;
2485
2486         if (newDir == NULL)
2487                 newDir = obj->parent;   /* use the old directory */
2488
2489         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2490                 T(YAFFS_TRACE_ALWAYS,
2491                   (TSTR
2492                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2493                     TENDSTR)));
2494                 YBUG();
2495         }
2496
2497         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2498         if (obj->myDev->isYaffs2)
2499                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2500         else
2501                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2502                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2503
2504         deleteOp = (newDir == obj->myDev->deletedDir);
2505
2506         existingTarget = yaffs_FindObjectByName(newDir, newName);
2507
2508         /* If the object is a file going into the unlinked directory,
2509          *   then it is OK to just stuff it in since duplicate names are allowed.
2510          *   else only proceed if the new name does not exist and if we're putting
2511          *   it into a directory.
2512          */
2513         if ((unlinkOp ||
2514              deleteOp ||
2515              force ||
2516              (shadows > 0) ||
2517              !existingTarget) &&
2518             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2519                 yaffs_SetObjectName(obj, newName);
2520                 obj->dirty = 1;
2521
2522                 yaffs_AddObjectToDirectory(newDir, obj);
2523
2524                 if (unlinkOp)
2525                         obj->unlinked = 1;
2526
2527                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2528                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2529                         return YAFFS_OK;
2530         }
2531
2532         return YAFFS_FAIL;
2533 }
2534
2535 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2536                 yaffs_Object *newDir, const YCHAR *newName)
2537 {
2538         yaffs_Object *obj = NULL;
2539         yaffs_Object *existingTarget = NULL;
2540         int force = 0;
2541         int result;
2542         yaffs_Device *dev;
2543
2544
2545         if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2546                 YBUG();
2547         if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2548                 YBUG();
2549
2550         dev = oldDir->myDev;
2551
2552 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2553         /* Special case for case insemsitive systems (eg. WinCE).
2554          * While look-up is case insensitive, the name isn't.
2555          * Therefore we might want to change x.txt to X.txt
2556         */
2557         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2558                 force = 1;
2559 #endif
2560
2561         if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2562                 /* ENAMETOOLONG */
2563                 return YAFFS_FAIL;
2564
2565         obj = yaffs_FindObjectByName(oldDir, oldName);
2566
2567         if (obj && obj->renameAllowed) {
2568
2569                 /* Now do the handling for an existing target, if there is one */
2570
2571                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2572                 if (existingTarget &&
2573                         existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2574                         !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2575                         /* There is a target that is a non-empty directory, so we fail */
2576                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2577                 } else if (existingTarget && existingTarget != obj) {
2578                         /* Nuke the target first, using shadowing,
2579                          * but only if it isn't the same object.
2580                          *
2581                          * Note we must disable gc otherwise it can mess up the shadowing.
2582                          *
2583                          */
2584                         dev->isDoingGC=1;
2585                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2586                                                 existingTarget->objectId);
2587                         existingTarget->isShadowed = 1;
2588                         yaffs_UnlinkObject(existingTarget);
2589                         dev->isDoingGC=0;
2590                 }
2591
2592                 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2593
2594                 yaffs_UpdateParent(oldDir);
2595                 if(newDir != oldDir)
2596                         yaffs_UpdateParent(newDir);
2597                 
2598                 return result;
2599         }
2600         return YAFFS_FAIL;
2601 }
2602
2603 /*------------------------- Block Management and Page Allocation ----------------*/
2604
2605 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2606 {
2607         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2608
2609         dev->blockInfo = NULL;
2610         dev->chunkBits = NULL;
2611
2612         dev->allocationBlock = -1;      /* force it to get a new one */
2613
2614         /* If the first allocation strategy fails, thry the alternate one */
2615         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2616         if (!dev->blockInfo) {
2617                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2618                 dev->blockInfoAlt = 1;
2619         } else
2620                 dev->blockInfoAlt = 0;
2621
2622         if (dev->blockInfo) {
2623                 /* Set up dynamic blockinfo stuff. */
2624                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2625                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2626                 if (!dev->chunkBits) {
2627                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2628                         dev->chunkBitsAlt = 1;
2629                 } else
2630                         dev->chunkBitsAlt = 0;
2631         }
2632
2633         if (dev->blockInfo && dev->chunkBits) {
2634                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2635                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2636                 return YAFFS_OK;
2637         }
2638
2639         return YAFFS_FAIL;
2640 }
2641
2642 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2643 {
2644         if (dev->blockInfoAlt && dev->blockInfo)
2645                 YFREE_ALT(dev->blockInfo);
2646         else if (dev->blockInfo)
2647                 YFREE(dev->blockInfo);
2648
2649         dev->blockInfoAlt = 0;
2650
2651         dev->blockInfo = NULL;
2652
2653         if (dev->chunkBitsAlt && dev->chunkBits)
2654                 YFREE_ALT(dev->chunkBits);
2655         else if (dev->chunkBits)
2656                 YFREE(dev->chunkBits);
2657         dev->chunkBitsAlt = 0;
2658         dev->chunkBits = NULL;
2659 }
2660
2661 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2662                                         yaffs_BlockInfo *bi)
2663 {
2664         int i;
2665         __u32 seq;
2666         yaffs_BlockInfo *b;
2667
2668         if (!dev->isYaffs2)
2669                 return 1;       /* disqualification only applies to yaffs2. */
2670
2671         if (!bi->hasShrinkHeader)
2672                 return 1;       /* can gc */
2673
2674         /* Find the oldest dirty sequence number if we don't know it and save it
2675          * so we don't have to keep recomputing it.
2676          */
2677         if (!dev->oldestDirtySequence) {
2678                 seq = dev->sequenceNumber;
2679
2680                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2681                                 i++) {
2682                         b = yaffs_GetBlockInfo(dev, i);
2683                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2684                             (b->pagesInUse - b->softDeletions) <
2685                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2686                                 seq = b->sequenceNumber;
2687                         }
2688                 }
2689                 dev->oldestDirtySequence = seq;
2690         }
2691
2692         /* Can't do gc of this block if there are any blocks older than this one that have
2693          * discarded pages.
2694          */
2695         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2696 }
2697
2698 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2699  * for garbage collection.
2700  */
2701
2702 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2703                                         int aggressive)
2704 {
2705         int b = dev->currentDirtyChecker;
2706
2707         int i;
2708         int iterations;
2709         int dirtiest = -1;
2710         int pagesInUse = 0;
2711         int prioritised = 0;
2712         yaffs_BlockInfo *bi;
2713         int pendingPrioritisedExist = 0;
2714
2715         /* First let's see if we need to grab a prioritised block */
2716         if (dev->hasPendingPrioritisedGCs) {
2717                 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2718
2719                         bi = yaffs_GetBlockInfo(dev, i);
2720                         /* yaffs_VerifyBlock(dev,bi,i); */
2721
2722                         if (bi->gcPrioritise) {
2723                                 pendingPrioritisedExist = 1;
2724                                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2725                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2726                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2727                                         dirtiest = i;
2728                                         prioritised = 1;
2729                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2730                                 }
2731                         }
2732                 }
2733
2734                 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2735                         dev->hasPendingPrioritisedGCs = 0;
2736         }
2737
2738         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2739          * search harder.
2740          * else (we're doing a leasurely gc), then we only bother to do this if the
2741          * block has only a few pages in use.
2742          */
2743
2744         dev->nonAggressiveSkip--;
2745
2746         if (!aggressive && (dev->nonAggressiveSkip > 0))
2747                 return -1;
2748
2749         if (!prioritised)
2750                 pagesInUse =
2751                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2752
2753         if (aggressive)
2754                 iterations =
2755                     dev->internalEndBlock - dev->internalStartBlock + 1;
2756         else {
2757                 iterations =
2758                     dev->internalEndBlock - dev->internalStartBlock + 1;
2759                 iterations = iterations / 16;
2760                 if (iterations > 200)
2761                         iterations = 200;
2762         }
2763
2764         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2765                 b++;
2766                 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2767                         b = dev->internalStartBlock;
2768
2769                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2770                         T(YAFFS_TRACE_ERROR,
2771                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2772                         YBUG();
2773                 }
2774
2775                 bi = yaffs_GetBlockInfo(dev, b);
2776
2777                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2778                         (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2779                                 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2780                         dirtiest = b;
2781                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2782                 }
2783         }
2784
2785         dev->currentDirtyChecker = b;
2786
2787         if (dirtiest > 0) {
2788                 T(YAFFS_TRACE_GC,
2789                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2790                    dev->nChunksPerBlock - pagesInUse, prioritised));
2791         }
2792
2793         dev->oldestDirtySequence = 0;
2794
2795         if (dirtiest > 0)
2796                 dev->nonAggressiveSkip = 4;
2797
2798         return dirtiest;
2799 }
2800
2801 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2802 {
2803         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2804
2805         int erasedOk = 0;
2806
2807         /* If the block is still healthy erase it and mark as clean.
2808          * If the block has had a data failure, then retire it.
2809          */
2810
2811         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2812                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2813                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2814
2815         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2816
2817         if (!bi->needsRetiring) {
2818                 yaffs_InvalidateCheckpoint(dev);
2819                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2820                 if (!erasedOk) {
2821                         dev->nErasureFailures++;
2822                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2823                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2824                 }
2825         }
2826
2827         if (erasedOk &&
2828             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2829                 int i;
2830                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2831                         if (!yaffs_CheckChunkErased
2832                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2833                                 T(YAFFS_TRACE_ERROR,
2834                                   (TSTR
2835                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2836                                     TENDSTR), blockNo, i));
2837                         }
2838                 }
2839         }
2840
2841         if (erasedOk) {
2842                 /* Clean it up... */
2843                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2844                 dev->nErasedBlocks++;
2845                 bi->pagesInUse = 0;
2846                 bi->softDeletions = 0;
2847                 bi->hasShrinkHeader = 0;
2848                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2849                 bi->gcPrioritise = 0;
2850                 yaffs_ClearChunkBits(dev, blockNo);
2851
2852                 T(YAFFS_TRACE_ERASE,
2853                   (TSTR("Erased block %d" TENDSTR), blockNo));
2854         } else {
2855                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2856
2857                 yaffs_RetireBlock(dev, blockNo);
2858                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2859                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2860         }
2861 }
2862
2863 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2864 {
2865         int i;
2866
2867         yaffs_BlockInfo *bi;
2868
2869         if (dev->nErasedBlocks < 1) {
2870                 /* Hoosterman we've got a problem.
2871                  * Can't get space to gc
2872                  */
2873                 T(YAFFS_TRACE_ERROR,
2874                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2875
2876                 return -1;
2877         }
2878
2879         /* Find an empty block. */
2880
2881         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2882                 dev->allocationBlockFinder++;
2883                 if (dev->allocationBlockFinder < dev->internalStartBlock
2884                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2885                         dev->allocationBlockFinder = dev->internalStartBlock;
2886                 }
2887
2888                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2889
2890                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2891                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2892                         dev->sequenceNumber++;
2893                         bi->sequenceNumber = dev->sequenceNumber;
2894                         dev->nErasedBlocks--;
2895                         T(YAFFS_TRACE_ALLOCATE,
2896                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2897                            dev->allocationBlockFinder, dev->sequenceNumber,
2898                            dev->nErasedBlocks));
2899                         return dev->allocationBlockFinder;
2900                 }
2901         }
2902
2903         T(YAFFS_TRACE_ALWAYS,
2904           (TSTR
2905            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2906             TENDSTR), dev->nErasedBlocks));
2907
2908         return -1;
2909 }
2910
2911
2912
2913 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2914 {
2915         if (!dev->nCheckpointBlocksRequired &&
2916            dev->isYaffs2) {
2917                 /* Not a valid value so recalculate */
2918                 int nBytes = 0;
2919                 int nBlocks;
2920                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2921                 int tnodeSize;
2922
2923                 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2924
2925                 if (tnodeSize < sizeof(yaffs_Tnode))
2926                         tnodeSize = sizeof(yaffs_Tnode);
2927
2928                 nBytes += sizeof(yaffs_CheckpointValidity);
2929                 nBytes += sizeof(yaffs_CheckpointDevice);
2930                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2931                 nBytes += devBlocks * dev->chunkBitmapStride;
2932                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2933                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2934                 nBytes += sizeof(yaffs_CheckpointValidity);
2935                 nBytes += sizeof(__u32); /* checksum*/
2936
2937                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2938
2939                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2940
2941                 dev->nCheckpointBlocksRequired = nBlocks;
2942         }
2943
2944         return dev->nCheckpointBlocksRequired;
2945 }
2946
2947 /*
2948  * Check if there's space to allocate...
2949  * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2950  */
2951 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2952 {
2953         int reservedChunks;
2954         int reservedBlocks = dev->nReservedBlocks;
2955         int checkpointBlocks;
2956
2957         if (dev->isYaffs2) {
2958                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) -
2959                                     dev->blocksInCheckpoint;
2960                 if (checkpointBlocks < 0)
2961                         checkpointBlocks = 0;
2962         } else {
2963                 checkpointBlocks = 0;
2964         }
2965
2966         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2967
2968         return (dev->nFreeChunks > reservedChunks);
2969 }
2970
2971 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2972                 yaffs_BlockInfo **blockUsedPtr)
2973 {
2974         int retVal;
2975         yaffs_BlockInfo *bi;
2976
2977         if (dev->allocationBlock < 0) {
2978                 /* Get next block to allocate off */
2979                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2980                 dev->allocationPage = 0;
2981         }
2982
2983         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2984                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2985                 return -1;
2986         }
2987
2988         if (dev->nErasedBlocks < dev->nReservedBlocks
2989                         && dev->allocationPage == 0) {
2990                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2991         }
2992
2993         /* Next page please.... */
2994         if (dev->allocationBlock >= 0) {
2995                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2996
2997                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2998                         dev->allocationPage;
2999                 bi->pagesInUse++;
3000                 yaffs_SetChunkBit(dev, dev->allocationBlock,
3001                                 dev->allocationPage);
3002
3003                 dev->allocationPage++;
3004
3005                 dev->nFreeChunks--;
3006
3007                 /* If the block is full set the state to full */
3008                 if (dev->allocationPage >= dev->nChunksPerBlock) {
3009                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3010                         dev->allocationBlock = -1;
3011                 }
3012
3013                 if (blockUsedPtr)
3014                         *blockUsedPtr = bi;
3015
3016                 return retVal;
3017         }
3018
3019         T(YAFFS_TRACE_ERROR,
3020                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3021
3022         return -1;
3023 }
3024
3025 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3026 {
3027         int n;
3028
3029         n = dev->nErasedBlocks * dev->nChunksPerBlock;
3030
3031         if (dev->allocationBlock > 0)
3032                 n += (dev->nChunksPerBlock - dev->allocationPage);
3033
3034         return n;
3035
3036 }
3037
3038 /*
3039  * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3040  * if we don't want to write to it.
3041  */
3042 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3043 {
3044         if(dev->allocationBlock > 0){
3045                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3046                 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3047                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3048                         dev->allocationBlock = -1;
3049                 }
3050         }
3051 }
3052
3053
3054 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3055                 int wholeBlock)
3056 {
3057         int oldChunk;
3058         int newChunk;
3059         int markNAND;
3060         int retVal = YAFFS_OK;
3061         int cleanups = 0;
3062         int i;
3063         int isCheckpointBlock;
3064         int matchingChunk;
3065         int maxCopies;
3066
3067         int chunksBefore = yaffs_GetErasedChunks(dev);
3068         int chunksAfter;
3069
3070         yaffs_ExtendedTags tags;
3071
3072         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3073
3074         yaffs_Object *object;
3075
3076         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3077
3078
3079         T(YAFFS_TRACE_TRACING,
3080                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3081                          block,
3082                          bi->pagesInUse,
3083                          bi->hasShrinkHeader,
3084                          wholeBlock));
3085
3086         /*yaffs_VerifyFreeChunks(dev); */
3087
3088         if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3089                 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3090         
3091         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3092
3093         /* Take off the number of soft deleted entries because
3094          * they're going to get really deleted during GC.
3095          */
3096         if(dev->gcChunk == 0) /* first time through for this block */
3097                 dev->nFreeChunks -= bi->softDeletions;
3098
3099         dev->isDoingGC = 1;
3100
3101         if (isCheckpointBlock ||
3102                         !yaffs_StillSomeChunkBits(dev, block)) {
3103                 T(YAFFS_TRACE_TRACING,
3104                                 (TSTR
3105                                  ("Collecting block %d that has no chunks in use" TENDSTR),
3106                                  block));
3107                 yaffs_BlockBecameDirty(dev, block);
3108         } else {
3109
3110                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3111
3112                 yaffs_VerifyBlock(dev, bi, block);
3113
3114                 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3115                 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3116
3117                 for (/* init already done */;
3118                      retVal == YAFFS_OK &&
3119                      dev->gcChunk < dev->nChunksPerBlock &&
3120                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3121                      maxCopies > 0;
3122                      dev->gcChunk++, oldChunk++) {
3123                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3124
3125                                 /* This page is in use and might need to be copied off */
3126
3127                                 maxCopies--;
3128
3129                                 markNAND = 1;
3130
3131                                 yaffs_InitialiseTags(&tags);
3132
3133                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3134                                                                 buffer, &tags);
3135
3136                                 object =
3137                                     yaffs_FindObjectByNumber(dev,
3138                                                              tags.objectId);
3139
3140                                 T(YAFFS_TRACE_GC_DETAIL,
3141                                   (TSTR
3142                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3143                                    dev->gcChunk, tags.objectId, tags.chunkId,
3144                                    tags.byteCount));
3145
3146                                 if (object && !yaffs_SkipVerification(dev)) {
3147                                         if (tags.chunkId == 0)
3148                                                 matchingChunk = object->hdrChunk;
3149                                         else if (object->softDeleted)
3150                                                 matchingChunk = oldChunk; /* Defeat the test */
3151                                         else
3152                                                 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3153
3154                                         if (oldChunk != matchingChunk)
3155                                                 T(YAFFS_TRACE_ERROR,
3156                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3157                                                   oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3158
3159                                 }
3160
3161                                 if (!object) {
3162                                         T(YAFFS_TRACE_ERROR,
3163                                           (TSTR
3164                                            ("page %d in gc has no object: %d %d %d "
3165                                             TENDSTR), oldChunk,
3166                                             tags.objectId, tags.chunkId, tags.byteCount));
3167                                 }
3168
3169                                 if (object &&
3170                                     object->deleted &&
3171                                     object->softDeleted &&
3172                                     tags.chunkId != 0) {
3173                                         /* Data chunk in a soft deleted file, throw it away
3174                                          * It's a soft deleted data chunk,
3175                                          * No need to copy this, just forget about it and
3176                                          * fix up the object.
3177                                          */
3178
3179                                         object->nDataChunks--;
3180
3181                                         if (object->nDataChunks <= 0) {
3182                                                 /* remeber to clean up the object */
3183                                                 dev->gcCleanupList[cleanups] =
3184                                                     tags.objectId;
3185                                                 cleanups++;
3186                                         }
3187                                         markNAND = 0;
3188                                 } else if (0) {
3189                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
3190                                         /* Deleted object header with no data chunks.
3191                                          * Can be discarded and the file deleted.
3192                                          */
3193                                         object->hdrChunk = 0;
3194                                         yaffs_FreeTnode(object->myDev,
3195                                                         object->variant.
3196                                                         fileVariant.top);
3197                                         object->variant.fileVariant.top = NULL;
3198                                         yaffs_DoGenericObjectDeletion(object);
3199
3200                                 } else if (object) {
3201                                         /* It's either a data chunk in a live file or
3202                                          * an ObjectHeader, so we're interested in it.
3203                                          * NB Need to keep the ObjectHeaders of deleted files
3204                                          * until the whole file has been deleted off
3205                                          */
3206                                         tags.serialNumber++;
3207
3208                                         dev->nGCCopies++;
3209
3210                                         if (tags.chunkId == 0) {
3211                                                 /* It is an object Id,
3212                                                  * We need to nuke the shrinkheader flags first
3213                                                  * Also need to clean up shadowing.
3214                                                  * We no longer want the shrinkHeader flag since its work is done
3215                                                  * and if it is left in place it will mess up scanning.
3216                                                  */
3217
3218                                                 yaffs_ObjectHeader *oh;
3219                                                 oh = (yaffs_ObjectHeader *)buffer;
3220                                                 oh->isShrink = 0;
3221                                                 tags.extraIsShrinkHeader = 0;
3222                                                 oh->shadowsObject = 0;
3223                                                 oh->inbandShadowsObject = 0;
3224                                                 tags.extraShadows = 0;
3225
3226                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3227                                         }
3228
3229                                         newChunk =
3230                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3231
3232                                         if (newChunk < 0) {
3233                                                 retVal = YAFFS_FAIL;
3234                                         } else {
3235
3236                                                 /* Ok, now fix up the Tnodes etc. */
3237
3238                                                 if (tags.chunkId == 0) {
3239                                                         /* It's a header */
3240                                                         object->hdrChunk =  newChunk;
3241                                                         object->serial =   tags.serialNumber;
3242                                                 } else {
3243                                                         /* It's a data chunk */
3244                                                         yaffs_PutChunkIntoFile
3245                                                             (object,
3246                                                              tags.chunkId,
3247                                                              newChunk, 0);
3248                                                 }
3249                                         }
3250                                 }
3251
3252                                 if (retVal == YAFFS_OK)
3253                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3254
3255                         }
3256                 }
3257
3258                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3259
3260
3261                 /* Do any required cleanups */
3262                 for (i = 0; i < cleanups; i++) {
3263                         /* Time to delete the file too */
3264                         object =
3265                             yaffs_FindObjectByNumber(dev,
3266                                                      dev->gcCleanupList[i]);
3267                         if (object) {
3268                                 yaffs_FreeTnode(dev,
3269                                                 object->variant.fileVariant.
3270                                                 top);
3271                                 object->variant.fileVariant.top = NULL;
3272                                 T(YAFFS_TRACE_GC,
3273                                   (TSTR
3274                                    ("yaffs: About to finally delete object %d"
3275                                     TENDSTR), object->objectId));
3276                                 yaffs_DoGenericObjectDeletion(object);
3277                                 object->myDev->nDeletedFiles--;
3278                         }
3279
3280                 }
3281
3282         }
3283
3284         yaffs_VerifyCollectedBlock(dev, bi, block);
3285
3286         chunksAfter = yaffs_GetErasedChunks(dev);
3287         if (chunksBefore >= chunksAfter) {
3288                 T(YAFFS_TRACE_GC,
3289                   (TSTR
3290                    ("gc did not increase free chunks before %d after %d"
3291                     TENDSTR), chunksBefore, chunksAfter));
3292         }
3293
3294         /* If the gc completed then clear the current gcBlock so that we find another. */
3295         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3296                 dev->gcBlock = -1;
3297                 dev->gcChunk = 0;
3298         }
3299
3300         dev->isDoingGC = 0;
3301
3302         return retVal;
3303 }
3304
3305 /* New garbage collector
3306  * If we're very low on erased blocks then we do aggressive garbage collection
3307  * otherwise we do "leasurely" garbage collection.
3308  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3309  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3310  *
3311  * The idea is to help clear out space in a more spread-out manner.
3312  * Dunno if it really does anything useful.
3313  */
3314 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3315 {
3316         int block;
3317         int aggressive;
3318         int gcOk = YAFFS_OK;
3319         int maxTries = 0;
3320
3321         int checkpointBlockAdjust;
3322
3323         if (dev->isDoingGC) {
3324                 /* Bail out so we don't get recursive gc */
3325                 return YAFFS_OK;
3326         }
3327
3328         /* This loop should pass the first time.
3329          * We'll only see looping here if the erase of the collected block fails.
3330          */
3331
3332         do {
3333                 maxTries++;
3334
3335                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3336                 if (checkpointBlockAdjust < 0)
3337                         checkpointBlockAdjust = 0;
3338
3339                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3340                         /* We need a block soon...*/
3341                         aggressive = 1;
3342                 } else {
3343                         /* We're in no hurry */
3344                         aggressive = 0;
3345                 }
3346
3347                 if (dev->gcBlock <= 0) {
3348                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3349                         dev->gcChunk = 0;
3350                 }
3351
3352                 block = dev->gcBlock;
3353
3354                 if (block > 0) {
3355                         dev->garbageCollections++;
3356                         if (!aggressive)
3357                                 dev->passiveGarbageCollections++;
3358
3359                         T(YAFFS_TRACE_GC,
3360                           (TSTR
3361                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3362                            dev->nErasedBlocks, aggressive));
3363
3364                         gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3365                 }
3366
3367                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3368                         T(YAFFS_TRACE_GC,
3369                           (TSTR
3370                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3371                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3372                 }
3373         } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3374                  (block > 0) &&
3375                  (maxTries < 2));
3376
3377         return aggressive ? gcOk : YAFFS_OK;
3378 }
3379
3380 /*-------------------------  TAGS --------------------------------*/
3381
3382 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3383                            int chunkInObject)
3384 {
3385         return (tags->chunkId == chunkInObject &&
3386                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3387
3388 }
3389
3390
3391 /*-------------------- Data file manipulation -----------------*/
3392
3393 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3394                                  yaffs_ExtendedTags *tags)
3395 {
3396         /*Get the Tnode, then get the level 0 offset chunk offset */
3397         yaffs_Tnode *tn;
3398         int theChunk = -1;
3399         yaffs_ExtendedTags localTags;
3400         int retVal = -1;
3401
3402         yaffs_Device *dev = in->myDev;
3403
3404         if (!tags) {
3405                 /* Passed a NULL, so use our own tags space */
3406                 tags = &localTags;
3407         }
3408
3409         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3410
3411         if (tn) {
3412                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3413
3414                 retVal =
3415                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3416                                            chunkInInode);
3417         }
3418         return retVal;
3419 }
3420
3421 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3422                                           yaffs_ExtendedTags *tags)
3423 {
3424         /* Get the Tnode, then get the level 0 offset chunk offset */
3425         yaffs_Tnode *tn;
3426         int theChunk = -1;
3427         yaffs_ExtendedTags localTags;
3428
3429         yaffs_Device *dev = in->myDev;
3430         int retVal = -1;
3431
3432         if (!tags) {
3433                 /* Passed a NULL, so use our own tags space */
3434                 tags = &localTags;
3435         }
3436
3437         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3438
3439         if (tn) {
3440
3441                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3442
3443                 retVal =
3444                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3445                                            chunkInInode);
3446
3447                 /* Delete the entry in the filestructure (if found) */
3448                 if (retVal != -1)
3449                         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3450         }
3451
3452         return retVal;
3453 }
3454
3455 #ifdef YAFFS_PARANOID
3456
3457 static int yaffs_CheckFileSanity(yaffs_Object *in)
3458 {
3459         int chunk;
3460         int nChunks;
3461         int fSize;
3462         int failed = 0;
3463         int objId;
3464         yaffs_Tnode *tn;
3465         yaffs_Tags localTags;
3466         yaffs_Tags *tags = &localTags;
3467         int theChunk;
3468         int chunkDeleted;
3469
3470         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3471                 return YAFFS_FAIL;
3472
3473         objId = in->objectId;
3474         fSize = in->variant.fileVariant.fileSize;
3475         nChunks =
3476             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3477
3478         for (chunk = 1; chunk <= nChunks; chunk++) {
3479                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3480                                            chunk);
3481
3482                 if (tn) {
3483
3484                         theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3485
3486                         if (yaffs_CheckChunkBits
3487                             (dev, theChunk / dev->nChunksPerBlock,
3488                              theChunk % dev->nChunksPerBlock)) {
3489
3490                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3491                                                             tags,
3492                                                             &chunkDeleted);
3493                                 if (yaffs_TagsMatch
3494                                     (tags, in->objectId, chunk, chunkDeleted)) {
3495                                         /* found it; */
3496
3497                                 }
3498                         } else {
3499
3500                                 failed = 1;
3501                         }
3502
3503                 } else {
3504                         /* T(("No level 0 found for %d\n", chunk)); */
3505                 }
3506         }
3507
3508         return failed ? YAFFS_FAIL : YAFFS_OK;
3509 }
3510
3511 #endif
3512
3513 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3514                                   int chunkInNAND, int inScan)
3515 {
3516         /* NB inScan is zero unless scanning.
3517          * For forward scanning, inScan is > 0;
3518          * for backward scanning inScan is < 0
3519          *
3520          * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3521          */
3522
3523         yaffs_Tnode *tn;
3524         yaffs_Device *dev = in->myDev;
3525         int existingChunk;
3526         yaffs_ExtendedTags existingTags;
3527         yaffs_ExtendedTags newTags;
3528         unsigned existingSerial, newSerial;
3529
3530         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3531                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3532                  * If it is not during Scanning then something went wrong!
3533                  */
3534                 if (!inScan) {
3535                         T(YAFFS_TRACE_ERROR,
3536                           (TSTR
3537                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3538                             TENDSTR)));
3539                         YBUG();
3540                 }
3541
3542                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3543                 return YAFFS_OK;
3544         }
3545
3546         tn = yaffs_AddOrFindLevel0Tnode(dev,
3547                                         &in->variant.fileVariant,
3548                                         chunkInInode,
3549                                         NULL);
3550         if (!tn)
3551                 return YAFFS_FAIL;
3552         
3553         if(!chunkInNAND)
3554                 /* Dummy insert, bail now */
3555                 return YAFFS_OK;
3556                 
3557
3558         existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3559
3560         if (inScan != 0) {
3561                 /* If we're scanning then we need to test for duplicates
3562                  * NB This does not need to be efficient since it should only ever
3563                  * happen when the power fails during a write, then only one
3564                  * chunk should ever be affected.
3565                  *
3566                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3567                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3568                  */
3569
3570                 if (existingChunk > 0) {
3571                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3572                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3573                          *
3574                          * We have a duplicate now we need to decide which one to use:
3575                          *
3576                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3577                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3578                          * YAFFS1: Get both sets of tags and compare serial numbers.
3579                          */
3580
3581                         if (inScan > 0) {
3582                                 /* Only do this for forward scanning */
3583                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3584                                                                 chunkInNAND,
3585                                                                 NULL, &newTags);
3586
3587                                 /* Do a proper find */
3588                                 existingChunk =
3589                                     yaffs_FindChunkInFile(in, chunkInInode,
3590                                                           &existingTags);
3591                         }
3592
3593                         if (existingChunk <= 0) {
3594                                 /*Hoosterman - how did this happen? */
3595
3596                                 T(YAFFS_TRACE_ERROR,
3597                                   (TSTR
3598                                    ("yaffs tragedy: existing chunk < 0 in scan"
3599                                     TENDSTR)));
3600
3601                         }
3602
3603                         /* NB The deleted flags should be false, otherwise the chunks will
3604                          * not be loaded during a scan
3605                          */
3606
3607                         if (inScan > 0) {
3608                                 newSerial = newTags.serialNumber;
3609                                 existingSerial = existingTags.serialNumber;
3610                         }
3611
3612                         if ((inScan > 0) &&
3613                             (in->myDev->isYaffs2 ||
3614                              existingChunk <= 0 ||
3615                              ((existingSerial + 1) & 3) == newSerial)) {
3616                                 /* Forward scanning.
3617                                  * Use new
3618                                  * Delete the old one and drop through to update the tnode
3619                                  */
3620                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3621                                                   __LINE__);
3622                         } else {
3623                                 /* Backward scanning or we want to use the existing one
3624                                  * Use existing.
3625                                  * Delete the new one and return early so that the tnode isn't changed
3626                                  */
3627                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3628                                                   __LINE__);
3629                                 return YAFFS_OK;
3630                         }
3631                 }
3632
3633         }
3634
3635         if (existingChunk == 0)
3636                 in->nDataChunks++;
3637
3638         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3639
3640         return YAFFS_OK;
3641 }
3642
3643 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3644                                         __u8 *buffer)
3645 {
3646         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3647
3648         if (chunkInNAND >= 0)
3649                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3650                                                 buffer, NULL);
3651         else {
3652                 T(YAFFS_TRACE_NANDACCESS,
3653                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3654                    chunkInNAND));
3655                 /* get sane (zero) data if you read a hole */
3656                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3657                 return 0;
3658         }
3659
3660 }
3661
3662 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3663 {
3664         int block;
3665         int page;
3666         yaffs_ExtendedTags tags;
3667         yaffs_BlockInfo *bi;
3668
3669         if (chunkId <= 0)
3670                 return;
3671
3672         dev->nDeletions++;
3673         block = chunkId / dev->nChunksPerBlock;
3674         page = chunkId % dev->nChunksPerBlock;
3675
3676
3677         if (!yaffs_CheckChunkBit(dev, block, page))
3678                 T(YAFFS_TRACE_VERIFY,
3679                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3680                          chunkId));
3681
3682         bi = yaffs_GetBlockInfo(dev, block);
3683
3684         T(YAFFS_TRACE_DELETION,
3685           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3686
3687         if (markNAND &&
3688             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3689
3690                 yaffs_InitialiseTags(&tags);
3691
3692                 tags.chunkDeleted = 1;
3693
3694                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3695                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3696         } else {
3697                 dev->nUnmarkedDeletions++;
3698         }
3699
3700         /* Pull out of the management area.
3701          * If the whole block became dirty, this will kick off an erasure.
3702          */
3703         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3704             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3705             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3706             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3707                 dev->nFreeChunks++;
3708
3709                 yaffs_ClearChunkBit(dev, block, page);
3710
3711                 bi->pagesInUse--;
3712
3713                 if (bi->pagesInUse == 0 &&
3714                     !bi->hasShrinkHeader &&
3715                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3716                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3717                         yaffs_BlockBecameDirty(dev, block);
3718                 }
3719
3720         }
3721
3722 }
3723
3724 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3725                                         const __u8 *buffer, int nBytes,
3726                                         int useReserve)
3727 {
3728         /* Find old chunk Need to do this to get serial number
3729          * Write new one and patch into tree.
3730          * Invalidate old tags.
3731          */
3732
3733         int prevChunkId;
3734         yaffs_ExtendedTags prevTags;
3735
3736         int newChunkId;
3737         yaffs_ExtendedTags newTags;
3738
3739         yaffs_Device *dev = in->myDev;
3740
3741         yaffs_CheckGarbageCollection(dev);
3742
3743         /* Get the previous chunk at this location in the file if it exists */
3744         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3745
3746         /* Set up new tags */
3747         yaffs_InitialiseTags(&newTags);
3748
3749         newTags.chunkId = chunkInInode;
3750         newTags.objectId = in->objectId;
3751         newTags.serialNumber =
3752             (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3753         newTags.byteCount = nBytes;
3754
3755         if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3756                 T(YAFFS_TRACE_ERROR,
3757                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3758                 YBUG();
3759         }
3760         
3761         /*
3762          * If there isn't already a chunk there then do a dummy
3763          * insert to make sue we have the desired tnode structure.
3764          */
3765         if(prevChunkId < 1 &&
3766                 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3767                 return -1;
3768                 
3769         newChunkId =
3770             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3771                                               useReserve);
3772
3773         if (newChunkId > 0) {
3774                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3775
3776                 if (prevChunkId > 0)
3777                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3778
3779                 yaffs_CheckFileSanity(in);
3780         }
3781         return newChunkId;
3782
3783 }
3784
3785 /* UpdateObjectHeader updates the header on NAND for an object.
3786  * If name is not NULL, then that new name is used.
3787  */
3788 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3789                              int isShrink, int shadows)
3790 {
3791
3792         yaffs_BlockInfo *bi;
3793
3794         yaffs_Device *dev = in->myDev;
3795
3796         int prevChunkId;
3797         int retVal = 0;
3798         int result = 0;
3799
3800         int newChunkId;
3801         yaffs_ExtendedTags newTags;
3802         yaffs_ExtendedTags oldTags;
3803         YCHAR *alias = NULL;
3804
3805         __u8 *buffer = NULL;
3806         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3807
3808         yaffs_ObjectHeader *oh = NULL;
3809
3810         yaffs_strcpy(oldName, _Y("silly old name"));
3811
3812
3813         if (!in->fake ||
3814                 in == dev->rootDir || /* The rootDir should also be saved */
3815                 force) {
3816
3817                 yaffs_CheckGarbageCollection(dev);
3818                 yaffs_CheckObjectDetailsLoaded(in);
3819
3820                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3821                 oh = (yaffs_ObjectHeader *) buffer;
3822
3823                 prevChunkId = in->hdrChunk;
3824
3825                 if (prevChunkId > 0) {
3826                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3827                                                         buffer, &oldTags);
3828
3829                         yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3830
3831                         memcpy(oldName, oh->name, sizeof(oh->name));
3832                 }
3833
3834                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3835
3836                 oh->type = in->variantType;
3837                 oh->yst_mode = in->yst_mode;
3838                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3839
3840 #ifdef CONFIG_YAFFS_WINCE
3841                 oh->win_atime[0] = in->win_atime[0];
3842                 oh->win_ctime[0] = in->win_ctime[0];
3843                 oh->win_mtime[0] = in->win_mtime[0];
3844                 oh->win_atime[1] = in->win_atime[1];
3845                 oh->win_ctime[1] = in->win_ctime[1];
3846                 oh->win_mtime[1] = in->win_mtime[1];
3847 #else
3848                 oh->yst_uid = in->yst_uid;
3849                 oh->yst_gid = in->yst_gid;
3850                 oh->yst_atime = in->yst_atime;
3851                 oh->yst_mtime = in->yst_mtime;
3852                 oh->yst_ctime = in->yst_ctime;
3853                 oh->yst_rdev = in->yst_rdev;
3854 #endif
3855                 if (in->parent)
3856                         oh->parentObjectId = in->parent->objectId;
3857                 else
3858                         oh->parentObjectId = 0;
3859
3860                 if (name && *name) {
3861                         memset(oh->name, 0, sizeof(oh->name));
3862                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3863                 } else if (prevChunkId > 0)
3864                         memcpy(oh->name, oldName, sizeof(oh->name));
3865                 else
3866                         memset(oh->name, 0, sizeof(oh->name));
3867
3868                 oh->isShrink = isShrink;
3869
3870                 switch (in->variantType) {
3871                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3872                         /* Should not happen */
3873                         break;
3874                 case YAFFS_OBJECT_TYPE_FILE:
3875                         oh->fileSize =
3876                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3877                              || oh->parentObjectId ==
3878                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3879                             fileVariant.fileSize;
3880                         break;
3881                 case YAFFS_OBJECT_TYPE_HARDLINK:
3882                         oh->equivalentObjectId =
3883                             in->variant.hardLinkVariant.equivalentObjectId;
3884                         break;
3885                 case YAFFS_OBJECT_TYPE_SPECIAL:
3886                         /* Do nothing */
3887                         break;
3888                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3889                         /* Do nothing */
3890                         break;
3891                 case YAFFS_OBJECT_TYPE_SYMLINK:
3892                         alias = in->variant.symLinkVariant.alias;
3893                         if(!alias)
3894                                 alias = _Y("no alias");
3895                         yaffs_strncpy(oh->alias,
3896                                         alias,
3897                                       YAFFS_MAX_ALIAS_LENGTH);
3898                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3899                         break;
3900                 }
3901
3902                 /* Tags */
3903                 yaffs_InitialiseTags(&newTags);
3904                 in->serial++;
3905                 newTags.chunkId = 0;
3906                 newTags.objectId = in->objectId;
3907                 newTags.serialNumber = in->serial;
3908
3909                 /* Add extra info for file header */
3910
3911                 newTags.extraHeaderInfoAvailable = 1;
3912                 newTags.extraParentObjectId = oh->parentObjectId;
3913                 newTags.extraFileLength = oh->fileSize;
3914                 newTags.extraIsShrinkHeader = oh->isShrink;
3915                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3916                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3917                 newTags.extraObjectType = in->variantType;
3918
3919                 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3920
3921                 /* Create new chunk in NAND */
3922                 newChunkId =
3923                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3924                                                       (prevChunkId > 0) ? 1 : 0);
3925
3926                 if (newChunkId >= 0) {
3927
3928                         in->hdrChunk = newChunkId;
3929
3930                         if (prevChunkId > 0) {
3931                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3932                                                   __LINE__);
3933                         }
3934
3935                         if (!yaffs_ObjectHasCachedWriteData(in))
3936                                 in->dirty = 0;
3937
3938                         /* If this was a shrink, then mark the block that the chunk lives on */
3939                         if (isShrink) {
3940                                 bi = yaffs_GetBlockInfo(in->myDev,
3941                                         newChunkId / in->myDev->nChunksPerBlock);
3942                                 bi->hasShrinkHeader = 1;
3943                         }
3944
3945                 }
3946
3947                 retVal = newChunkId;
3948
3949         }
3950
3951         if (buffer)
3952                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3953
3954         return retVal;
3955 }
3956
3957 /*------------------------ Short Operations Cache ----------------------------------------
3958  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3959  *   reads might be short sequential reads, and a lot of writes may be short
3960  *   sequential writes. eg. scanning/writing a jpeg file.
3961  *   In these cases, a short read/write cache can provide a huge perfomance benefit
3962  *   with dumb-as-a-rock code.
3963  *   In Linux, the page cache provides read buffering aand the short op cache provides write
3964  *   buffering.
3965  *
3966  *   There are a limited number (~10) of cache chunks per device so that we don't
3967  *   need a very intelligent search.
3968  */
3969
3970 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3971 {
3972         yaffs_Device *dev = obj->myDev;
3973         int i;
3974         yaffs_ChunkCache *cache;
3975         int nCaches = obj->myDev->nShortOpCaches;
3976
3977         for (i = 0; i < nCaches; i++) {
3978                 cache = &dev->srCache[i];
3979                 if (cache->object == obj &&
3980                     cache->dirty)
3981                         return 1;
3982         }
3983
3984         return 0;
3985 }
3986
3987
3988 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3989 {
3990         yaffs_Device *dev = obj->myDev;
3991         int lowest = -99;       /* Stop compiler whining. */
3992         int i;
3993         yaffs_ChunkCache *cache;
3994         int chunkWritten = 0;
3995         int nCaches = obj->myDev->nShortOpCaches;
3996
3997         if (nCaches > 0) {
3998                 do {
3999                         cache = NULL;
4000
4001                         /* Find the dirty cache for this object with the lowest chunk id. */
4002                         for (i = 0; i < nCaches; i++) {
4003                                 if (dev->srCache[i].object == obj &&
4004                                     dev->srCache[i].dirty) {
4005                                         if (!cache
4006                                             || dev->srCache[i].chunkId <
4007                                             lowest) {
4008                                                 cache = &dev->srCache[i];
4009                                                 lowest = cache->chunkId;
4010                                         }
4011                                 }
4012                         }
4013
4014                         if (cache && !cache->locked) {
4015                                 /* Write it out and free it up */
4016
4017                                 chunkWritten =
4018                                     yaffs_WriteChunkDataToObject(cache->object,
4019                                                                  cache->chunkId,
4020                                                                  cache->data,
4021                                                                  cache->nBytes,
4022                                                                  1);
4023                                 cache->dirty = 0;
4024                                 cache->object = NULL;
4025                         }
4026
4027                 } while (cache && chunkWritten > 0);
4028
4029                 if (cache) {
4030                         /* Hoosterman, disk full while writing cache out. */
4031                         T(YAFFS_TRACE_ERROR,
4032                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4033
4034                 }
4035         }
4036
4037 }
4038
4039 /*yaffs_FlushEntireDeviceCache(dev)
4040  *
4041  *
4042  */
4043
4044 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4045 {
4046         yaffs_Object *obj;
4047         int nCaches = dev->nShortOpCaches;
4048         int i;
4049
4050         /* Find a dirty object in the cache and flush it...
4051          * until there are no further dirty objects.
4052          */
4053         do {
4054                 obj = NULL;
4055                 for (i = 0; i < nCaches && !obj; i++) {
4056                         if (dev->srCache[i].object &&
4057                             dev->srCache[i].dirty)
4058                                 obj = dev->srCache[i].object;
4059
4060                 }
4061                 if (obj)
4062                         yaffs_FlushFilesChunkCache(obj);
4063
4064         } while (obj);
4065
4066 }
4067
4068
4069 /* Grab us a cache chunk for use.
4070  * First look for an empty one.
4071  * Then look for the least recently used non-dirty one.
4072  * Then look for the least recently used dirty one...., flush and look again.
4073  */
4074 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4075 {
4076         int i;
4077
4078         if (dev->nShortOpCaches > 0) {
4079                 for (i = 0; i < dev->nShortOpCaches; i++) {
4080                         if (!dev->srCache[i].object)
4081                                 return &dev->srCache[i];
4082                 }
4083         }
4084
4085         return NULL;
4086 }
4087
4088 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4089 {
4090         yaffs_ChunkCache *cache;
4091         yaffs_Object *theObj;
4092         int usage;
4093         int i;
4094         int pushout;
4095
4096         if (dev->nShortOpCaches > 0) {
4097                 /* Try find a non-dirty one... */
4098
4099                 cache = yaffs_GrabChunkCacheWorker(dev);
4100
4101                 if (!cache) {
4102                         /* They were all dirty, find the last recently used object and flush
4103                          * its cache, then  find again.
4104                          * NB what's here is not very accurate, we actually flush the object
4105                          * the last recently used page.
4106                          */
4107
4108                         /* With locking we can't assume we can use entry zero */
4109
4110                         theObj = NULL;
4111                         usage = -1;
4112                         cache = NULL;
4113                         pushout = -1;
4114
4115                         for (i = 0; i < dev->nShortOpCaches; i++) {
4116                                 if (dev->srCache[i].object &&
4117                                     !dev->srCache[i].locked &&
4118                                     (dev->srCache[i].lastUse < usage || !cache)) {
4119                                         usage = dev->srCache[i].lastUse;
4120                                         theObj = dev->srCache[i].object;
4121                                         cache = &dev->srCache[i];
4122                                         pushout = i;
4123                                 }
4124                         }
4125
4126                         if (!cache || cache->dirty) {
4127                                 /* Flush and try again */
4128                                 yaffs_FlushFilesChunkCache(theObj);
4129                                 cache = yaffs_GrabChunkCacheWorker(dev);
4130                         }
4131
4132                 }
4133                 return cache;
4134         } else
4135                 return NULL;
4136
4137 }
4138
4139 /* Find a cached chunk */
4140 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4141                                               int chunkId)
4142 {
4143         yaffs_Device *dev = obj->myDev;
4144         int i;
4145         if (dev->nShortOpCaches > 0) {
4146                 for (i = 0; i < dev->nShortOpCaches; i++) {
4147                         if (dev->srCache[i].object == obj &&
4148                             dev->srCache[i].chunkId == chunkId) {
4149                                 dev->cacheHits++;
4150
4151                                 return &dev->srCache[i];
4152                         }
4153                 }
4154         }
4155         return NULL;
4156 }
4157
4158 /* Mark the chunk for the least recently used algorithym */
4159 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4160                                 int isAWrite)
4161 {
4162
4163         if (dev->nShortOpCaches > 0) {
4164                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4165                         /* Reset the cache usages */
4166                         int i;
4167                         for (i = 1; i < dev->nShortOpCaches; i++)
4168                                 dev->srCache[i].lastUse = 0;
4169
4170                         dev->srLastUse = 0;
4171                 }
4172
4173                 dev->srLastUse++;
4174
4175                 cache->lastUse = dev->srLastUse;
4176
4177                 if (isAWrite)
4178                         cache->dirty = 1;
4179         }
4180 }
4181
4182 /* Invalidate a single cache page.
4183  * Do this when a whole page gets written,
4184  * ie the short cache for this page is no longer valid.
4185  */
4186 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4187 {
4188         if (object->myDev->nShortOpCaches > 0) {
4189                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4190
4191                 if (cache)
4192                         cache->object = NULL;
4193         }
4194 }
4195
4196 /* Invalidate all the cache pages associated with this object
4197  * Do this whenever ther file is deleted or resized.
4198  */
4199 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4200 {
4201         int i;
4202         yaffs_Device *dev = in->myDev;
4203
4204         if (dev->nShortOpCaches > 0) {
4205                 /* Invalidate it. */
4206                 for (i = 0; i < dev->nShortOpCaches; i++) {
4207                         if (dev->srCache[i].object == in)
4208                                 dev->srCache[i].object = NULL;
4209                 }
4210         }
4211 }
4212
4213 /*--------------------- Checkpointing --------------------*/
4214
4215
4216 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4217 {
4218         yaffs_CheckpointValidity cp;
4219
4220         memset(&cp, 0, sizeof(cp));
4221
4222         cp.structType = sizeof(cp);
4223         cp.magic = YAFFS_MAGIC;
4224         cp.version = YAFFS_CHECKPOINT_VERSION;
4225         cp.head = (head) ? 1 : 0;
4226
4227         return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4228                 1 : 0;
4229 }
4230
4231 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4232 {
4233         yaffs_CheckpointValidity cp;
4234         int ok;
4235
4236         ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4237
4238         if (ok)
4239                 ok = (cp.structType == sizeof(cp)) &&
4240                      (cp.magic == YAFFS_MAGIC) &&
4241                      (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4242                      (cp.head == ((head) ? 1 : 0));
4243         return ok ? 1 : 0;
4244 }
4245
4246 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4247                                            yaffs_Device *dev)
4248 {
4249         cp->nErasedBlocks = dev->nErasedBlocks;
4250         cp->allocationBlock = dev->allocationBlock;
4251         cp->allocationPage = dev->allocationPage;
4252         cp->nFreeChunks = dev->nFreeChunks;
4253
4254         cp->nDeletedFiles = dev->nDeletedFiles;
4255         cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4256         cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4257         cp->sequenceNumber = dev->sequenceNumber;
4258         cp->oldestDirtySequence = dev->oldestDirtySequence;
4259
4260 }
4261
4262 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4263                                            yaffs_CheckpointDevice *cp)
4264 {
4265         dev->nErasedBlocks = cp->nErasedBlocks;
4266         dev->allocationBlock = cp->allocationBlock;
4267         dev->allocationPage = cp->allocationPage;
4268         dev->nFreeChunks = cp->nFreeChunks;
4269
4270         dev->nDeletedFiles = cp->nDeletedFiles;
4271         dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4272         dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4273         dev->sequenceNumber = cp->sequenceNumber;
4274         dev->oldestDirtySequence = cp->oldestDirtySequence;
4275 }
4276
4277
4278 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4279 {
4280         yaffs_CheckpointDevice cp;
4281         __u32 nBytes;
4282         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4283
4284         int ok;
4285
4286         /* Write device runtime values*/
4287         yaffs_DeviceToCheckpointDevice(&cp, dev);
4288         cp.structType = sizeof(cp);
4289
4290         ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4291
4292         /* Write block info */
4293         if (ok) {
4294                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4295                 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4296         }
4297
4298         /* Write chunk bits */
4299         if (ok) {
4300                 nBytes = nBlocks * dev->chunkBitmapStride;
4301                 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4302         }
4303         return   ok ? 1 : 0;
4304
4305 }
4306
4307 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4308 {
4309         yaffs_CheckpointDevice cp;
4310         __u32 nBytes;
4311         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4312
4313         int ok;
4314
4315         ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4316         if (!ok)
4317                 return 0;
4318
4319         if (cp.structType != sizeof(cp))
4320                 return 0;
4321
4322
4323         yaffs_CheckpointDeviceToDevice(dev, &cp);
4324
4325         nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4326
4327         ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4328
4329         if (!ok)
4330                 return 0;
4331         nBytes = nBlocks * dev->chunkBitmapStride;
4332
4333         ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4334
4335         return ok ? 1 : 0;
4336 }
4337
4338 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4339                                            yaffs_Object *obj)
4340 {
4341
4342         cp->objectId = obj->objectId;
4343         cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4344         cp->hdrChunk = obj->hdrChunk;
4345         cp->variantType = obj->variantType;
4346         cp->deleted = obj->deleted;
4347         cp->softDeleted = obj->softDeleted;
4348         cp->unlinked = obj->unlinked;
4349         cp->fake = obj->fake;
4350         cp->renameAllowed = obj->renameAllowed;
4351         cp->unlinkAllowed = obj->unlinkAllowed;
4352         cp->serial = obj->serial;
4353         cp->nDataChunks = obj->nDataChunks;
4354
4355         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4356                 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4357         else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4358                 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4359 }
4360
4361 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4362 {
4363
4364         yaffs_Object *parent;
4365
4366         if (obj->variantType != cp->variantType) {
4367                 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4368                         TCONT("chunk %d does not match existing object type %d")
4369                         TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4370                         obj->variantType));
4371                 return 0;
4372         }
4373
4374         obj->objectId = cp->objectId;
4375
4376         if (cp->parentId)
4377                 parent = yaffs_FindOrCreateObjectByNumber(
4378                                         obj->myDev,
4379                                         cp->parentId,
4380                                         YAFFS_OBJECT_TYPE_DIRECTORY);
4381         else
4382                 parent = NULL;
4383
4384         if (parent) {
4385                 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4386                         T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4387                                 TCONT(" chunk %d Parent type, %d, not directory")
4388                                 TENDSTR),
4389                                 cp->objectId, cp->parentId, cp->variantType,
4390                                 cp->hdrChunk, parent->variantType));
4391                         return 0;
4392                 }
4393                 yaffs_AddObjectToDirectory(parent, obj);
4394         }
4395
4396         obj->hdrChunk = cp->hdrChunk;
4397         obj->variantType = cp->variantType;
4398         obj->deleted = cp->deleted;
4399         obj->softDeleted = cp->softDeleted;
4400         obj->unlinked = cp->unlinked;
4401         obj->fake = cp->fake;
4402         obj->renameAllowed = cp->renameAllowed;
4403         obj->unlinkAllowed = cp->unlinkAllowed;
4404         obj->serial = cp->serial;
4405         obj->nDataChunks = cp->nDataChunks;
4406
4407         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4408                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4409         else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4410                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4411
4412         if (obj->hdrChunk > 0)
4413                 obj->lazyLoaded = 1;
4414         return 1;
4415 }
4416
4417
4418
4419 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4420                                         __u32 level, int chunkOffset)
4421 {
4422         int i;
4423         yaffs_Device *dev = in->myDev;
4424         int ok = 1;
4425         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4426
4427         if (tnodeSize < sizeof(yaffs_Tnode))
4428                 tnodeSize = sizeof(yaffs_Tnode);
4429
4430
4431         if (tn) {
4432                 if (level > 0) {
4433
4434                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4435                                 if (tn->internal[i]) {
4436                                         ok = yaffs_CheckpointTnodeWorker(in,
4437                                                         tn->internal[i],
4438                                                         level - 1,
4439                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4440                                 }
4441                         }
4442                 } else if (level == 0) {
4443                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
4444                         ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4445                         if (ok)
4446                                 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4447                 }
4448         }
4449
4450         return ok;
4451
4452 }
4453
4454 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4455 {
4456         __u32 endMarker = ~0;
4457         int ok = 1;
4458
4459         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4460                 ok = yaffs_CheckpointTnodeWorker(obj,
4461                                             obj->variant.fileVariant.top,
4462                                             obj->variant.fileVariant.topLevel,
4463                                             0);
4464                 if (ok)
4465                         ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4466                                 sizeof(endMarker));
4467         }
4468
4469         return ok ? 1 : 0;
4470 }
4471
4472 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4473 {
4474         __u32 baseChunk;
4475         int ok = 1;
4476         yaffs_Device *dev = obj->myDev;
4477         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4478         yaffs_Tnode *tn;
4479         int nread = 0;
4480         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4481
4482         if (tnodeSize < sizeof(yaffs_Tnode))
4483                 tnodeSize = sizeof(yaffs_Tnode);
4484
4485         ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4486
4487         while (ok && (~baseChunk)) {
4488                 nread++;
4489                 /* Read level 0 tnode */
4490
4491
4492                 tn = yaffs_GetTnodeRaw(dev);
4493                 if (tn)
4494                         ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4495                 else
4496                         ok = 0;
4497
4498                 if (tn && ok)
4499                         ok = yaffs_AddOrFindLevel0Tnode(dev,
4500                                                         fileStructPtr,
4501                                                         baseChunk,
4502                                                         tn) ? 1 : 0;
4503
4504                 if (ok)
4505                         ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4506
4507         }
4508
4509         T(YAFFS_TRACE_CHECKPOINT, (
4510                 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4511                 nread, baseChunk, ok));
4512
4513         return ok ? 1 : 0;
4514 }
4515
4516
4517 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4518 {
4519         yaffs_Object *obj;
4520         yaffs_CheckpointObject cp;
4521         int i;
4522         int ok = 1;
4523         struct ylist_head *lh;
4524
4525
4526         /* Iterate through the objects in each hash entry,
4527          * dumping them to the checkpointing stream.
4528          */
4529
4530         for (i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++) {
4531                 ylist_for_each(lh, &dev->objectBucket[i].list) {
4532                         if (lh) {
4533                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
4534                                 if (!obj->deferedFree) {
4535                                         yaffs_ObjectToCheckpointObject(&cp, obj);
4536                                         cp.structType = sizeof(cp);
4537
4538                                         T(YAFFS_TRACE_CHECKPOINT, (
4539                                                 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4540                                                 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4541
4542                                         ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4543
4544                                         if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4545                                                 ok = yaffs_WriteCheckpointTnodes(obj);
4546                                 }
4547                         }
4548                 }
4549         }
4550
4551         /* Dump end of list */
4552         memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4553         cp.structType = sizeof(cp);
4554
4555         if (ok)
4556                 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4557
4558         return ok ? 1 : 0;
4559 }
4560
4561 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4562 {
4563         yaffs_Object *obj;
4564         yaffs_CheckpointObject cp;
4565         int ok = 1;
4566         int done = 0;
4567         yaffs_Object *hardList = NULL;
4568
4569         while (ok && !done) {
4570                 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4571                 if (cp.structType != sizeof(cp)) {
4572                         T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4573                                 cp.structType, (int)sizeof(cp), ok));
4574                         ok = 0;
4575                 }
4576
4577                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4578                         cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4579
4580                 if (ok && cp.objectId == ~0)
4581                         done = 1;
4582                 else if (ok) {
4583                         obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4584                         if (obj) {
4585                                 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4586                                 if (!ok)
4587                                         break;
4588                                 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4589                                         ok = yaffs_ReadCheckpointTnodes(obj);
4590                                 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4591                                         obj->hardLinks.next =
4592                                                 (struct ylist_head *) hardList;
4593                                         hardList = obj;
4594                                 }
4595                         } else
4596                                 ok = 0;
4597                 }
4598         }
4599
4600         if (ok)
4601                 yaffs_HardlinkFixup(dev, hardList);
4602
4603         return ok ? 1 : 0;
4604 }
4605
4606 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4607 {
4608         __u32 checkpointSum;
4609         int ok;
4610
4611         yaffs_GetCheckpointSum(dev, &checkpointSum);
4612
4613         ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4614
4615         if (!ok)
4616                 return 0;
4617
4618         return 1;
4619 }
4620
4621 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4622 {
4623         __u32 checkpointSum0;
4624         __u32 checkpointSum1;
4625         int ok;
4626
4627         yaffs_GetCheckpointSum(dev, &checkpointSum0);
4628
4629         ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4630
4631         if (!ok)
4632                 return 0;
4633
4634         if (checkpointSum0 != checkpointSum1)
4635                 return 0;
4636
4637         return 1;
4638 }
4639
4640
4641 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4642 {
4643         int ok = 1;
4644
4645         if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4646                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4647                 ok = 0;
4648         }
4649
4650         if (ok)
4651                 ok = yaffs_CheckpointOpen(dev, 1);
4652
4653         if (ok) {
4654                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4655                 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4656         }
4657         if (ok) {
4658                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4659                 ok = yaffs_WriteCheckpointDevice(dev);
4660         }
4661         if (ok) {
4662                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4663                 ok = yaffs_WriteCheckpointObjects(dev);
4664         }
4665         if (ok) {
4666                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4667                 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4668         }
4669
4670         if (ok)
4671                 ok = yaffs_WriteCheckpointSum(dev);
4672
4673         if (!yaffs_CheckpointClose(dev))
4674                 ok = 0;
4675
4676         if (ok)
4677                 dev->isCheckpointed = 1;
4678         else
4679                 dev->isCheckpointed = 0;
4680
4681         return dev->isCheckpointed;
4682 }
4683
4684 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4685 {
4686         int ok = 1;
4687
4688         if (dev->skipCheckpointRead || !dev->isYaffs2) {
4689                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4690                 ok = 0;
4691         }
4692
4693         if (ok)
4694                 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4695
4696         if (ok) {
4697                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4698                 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4699         }
4700         if (ok) {
4701                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4702                 ok = yaffs_ReadCheckpointDevice(dev);
4703         }
4704         if (ok) {
4705                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4706                 ok = yaffs_ReadCheckpointObjects(dev);
4707         }
4708         if (ok) {
4709                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4710                 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4711         }
4712
4713         if (ok) {
4714                 ok = yaffs_ReadCheckpointSum(dev);
4715                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4716         }
4717
4718         if (!yaffs_CheckpointClose(dev))
4719                 ok = 0;
4720
4721         if (ok)
4722                 dev->isCheckpointed = 1;
4723         else
4724                 dev->isCheckpointed = 0;
4725
4726         return ok ? 1 : 0;
4727
4728 }
4729
4730 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4731 {
4732         if (dev->isCheckpointed ||
4733                         dev->blocksInCheckpoint > 0) {
4734                 dev->isCheckpointed = 0;
4735                 yaffs_CheckpointInvalidateStream(dev);
4736                 if (dev->superBlock && dev->markSuperBlockDirty)
4737                         dev->markSuperBlockDirty(dev->superBlock);
4738         }
4739 }
4740
4741
4742 int yaffs_CheckpointSave(yaffs_Device *dev)
4743 {
4744
4745         T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4746
4747         yaffs_VerifyObjects(dev);
4748         yaffs_VerifyBlocks(dev);
4749         yaffs_VerifyFreeChunks(dev);
4750
4751         if (!dev->isCheckpointed) {
4752                 yaffs_InvalidateCheckpoint(dev);
4753                 yaffs_WriteCheckpointData(dev);
4754         }
4755
4756         T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4757
4758         return dev->isCheckpointed;
4759 }
4760
4761 int yaffs_CheckpointRestore(yaffs_Device *dev)
4762 {
4763         int retval;
4764         T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4765
4766         retval = yaffs_ReadCheckpointData(dev);
4767
4768         if (dev->isCheckpointed) {
4769                 yaffs_VerifyObjects(dev);
4770                 yaffs_VerifyBlocks(dev);
4771                 yaffs_VerifyFreeChunks(dev);
4772         }
4773
4774         T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4775
4776         return retval;
4777 }
4778
4779 /*--------------------- File read/write ------------------------
4780  * Read and write have very similar structures.
4781  * In general the read/write has three parts to it
4782  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4783  * Some complete chunks
4784  * An incomplete chunk to end off with
4785  *
4786  * Curve-balls: the first chunk might also be the last chunk.
4787  */
4788
4789 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4790                         int nBytes)
4791 {
4792
4793         int chunk;
4794         __u32 start;
4795         int nToCopy;
4796         int n = nBytes;
4797         int nDone = 0;
4798         yaffs_ChunkCache *cache;
4799
4800         yaffs_Device *dev;
4801
4802         dev = in->myDev;
4803
4804         while (n > 0) {
4805                 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4806                 /* start = offset % dev->nDataBytesPerChunk; */
4807                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4808                 chunk++;
4809
4810                 /* OK now check for the curveball where the start and end are in
4811                  * the same chunk.
4812                  */
4813                 if ((start + n) < dev->nDataBytesPerChunk)
4814                         nToCopy = n;
4815                 else
4816                         nToCopy = dev->nDataBytesPerChunk - start;
4817
4818                 cache = yaffs_FindChunkCache(in, chunk);
4819
4820                 /* If the chunk is already in the cache or it is less than a whole chunk
4821                  * or we're using inband tags then use the cache (if there is caching)
4822                  * else bypass the cache.
4823                  */
4824                 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4825                         if (dev->nShortOpCaches > 0) {
4826
4827                                 /* If we can't find the data in the cache, then load it up. */
4828
4829                                 if (!cache) {
4830                                         cache = yaffs_GrabChunkCache(in->myDev);
4831                                         cache->object = in;
4832                                         cache->chunkId = chunk;
4833                                         cache->dirty = 0;
4834                                         cache->locked = 0;
4835                                         yaffs_ReadChunkDataFromObject(in, chunk,
4836                                                                       cache->
4837                                                                       data);
4838                                         cache->nBytes = 0;
4839                                 }
4840
4841                                 yaffs_UseChunkCache(dev, cache, 0);
4842
4843                                 cache->locked = 1;
4844
4845
4846                                 memcpy(buffer, &cache->data[start], nToCopy);
4847
4848                                 cache->locked = 0;
4849                         } else {
4850                                 /* Read into the local buffer then copy..*/
4851
4852                                 __u8 *localBuffer =
4853                                     yaffs_GetTempBuffer(dev, __LINE__);
4854                                 yaffs_ReadChunkDataFromObject(in, chunk,
4855                                                               localBuffer);
4856
4857                                 memcpy(buffer, &localBuffer[start], nToCopy);
4858
4859
4860                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4861                                                         __LINE__);
4862                         }
4863
4864                 } else {
4865
4866                         /* A full chunk. Read directly into the supplied buffer. */
4867                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4868
4869                 }
4870
4871                 n -= nToCopy;
4872                 offset += nToCopy;
4873                 buffer += nToCopy;
4874                 nDone += nToCopy;
4875
4876         }
4877
4878         return nDone;
4879 }
4880
4881 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4882                         int nBytes, int writeThrough)
4883 {
4884
4885         int chunk;
4886         __u32 start;
4887         int nToCopy;
4888         int n = nBytes;
4889         int nDone = 0;
4890         int nToWriteBack;
4891         int startOfWrite = offset;
4892         int chunkWritten = 0;
4893         __u32 nBytesRead;
4894         __u32 chunkStart;
4895
4896         yaffs_Device *dev;
4897
4898         dev = in->myDev;
4899
4900         while (n > 0 && chunkWritten >= 0) {
4901                 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4902                 /* start = offset % dev->nDataBytesPerChunk; */
4903                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4904
4905                 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4906                                 start >= dev->nDataBytesPerChunk) {
4907                         T(YAFFS_TRACE_ERROR, (
4908                            TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4909                            TENDSTR),
4910                            (int)offset, chunk, start));
4911                 }
4912                 chunk++;
4913
4914                 /* OK now check for the curveball where the start and end are in
4915                  * the same chunk.
4916                  */
4917
4918                 if ((start + n) < dev->nDataBytesPerChunk) {
4919                         nToCopy = n;
4920
4921                         /* Now folks, to calculate how many bytes to write back....
4922                          * If we're overwriting and not writing to then end of file then
4923                          * we need to write back as much as was there before.
4924                          */
4925
4926                         chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4927
4928                         if (chunkStart > in->variant.fileVariant.fileSize)
4929                                 nBytesRead = 0; /* Past end of file */
4930                         else
4931                                 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4932
4933                         if (nBytesRead > dev->nDataBytesPerChunk)
4934                                 nBytesRead = dev->nDataBytesPerChunk;
4935
4936                         nToWriteBack =
4937                             (nBytesRead >
4938                              (start + n)) ? nBytesRead : (start + n);
4939
4940                         if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4941                                 YBUG();
4942
4943                 } else {
4944                         nToCopy = dev->nDataBytesPerChunk - start;
4945                         nToWriteBack = dev->nDataBytesPerChunk;
4946                 }
4947
4948                 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4949                         /* An incomplete start or end chunk (or maybe both start and end chunk),
4950                          * or we're using inband tags, so we want to use the cache buffers.
4951                          */
4952                         if (dev->nShortOpCaches > 0) {
4953                                 yaffs_ChunkCache *cache;
4954                                 /* If we can't find the data in the cache, then load the cache */
4955                                 cache = yaffs_FindChunkCache(in, chunk);
4956
4957                                 if (!cache
4958                                     && yaffs_CheckSpaceForAllocation(in->
4959                                                                      myDev)) {
4960                                         cache = yaffs_GrabChunkCache(in->myDev);
4961                                         cache->object = in;
4962                                         cache->chunkId = chunk;
4963                                         cache->dirty = 0;
4964                                         cache->locked = 0;
4965                                         yaffs_ReadChunkDataFromObject(in, chunk,
4966                                                                       cache->
4967                                                                       data);
4968                                 } else if (cache &&
4969                                         !cache->dirty &&
4970                                         !yaffs_CheckSpaceForAllocation(in->myDev)) {
4971                                         /* Drop the cache if it was a read cache item and
4972                                          * no space check has been made for it.
4973                                          */
4974                                          cache = NULL;
4975                                 }
4976
4977                                 if (cache) {
4978                                         yaffs_UseChunkCache(dev, cache, 1);
4979                                         cache->locked = 1;
4980
4981
4982                                         memcpy(&cache->data[start], buffer,
4983                                                nToCopy);
4984
4985
4986                                         cache->locked = 0;
4987                                         cache->nBytes = nToWriteBack;
4988
4989                                         if (writeThrough) {
4990                                                 chunkWritten =
4991                                                     yaffs_WriteChunkDataToObject
4992                                                     (cache->object,
4993                                                      cache->chunkId,
4994                                                      cache->data, cache->nBytes,
4995                                                      1);
4996                                                 cache->dirty = 0;
4997                                         }
4998
4999                                 } else {
5000                                         chunkWritten = -1;      /* fail the write */
5001                                 }
5002                         } else {
5003                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
5004                                  * Read into the local buffer then copy, then copy over and write back.
5005                                  */
5006
5007                                 __u8 *localBuffer =
5008                                     yaffs_GetTempBuffer(dev, __LINE__);
5009
5010                                 yaffs_ReadChunkDataFromObject(in, chunk,
5011                                                               localBuffer);
5012
5013
5014
5015                                 memcpy(&localBuffer[start], buffer, nToCopy);
5016
5017                                 chunkWritten =
5018                                     yaffs_WriteChunkDataToObject(in, chunk,
5019                                                                  localBuffer,
5020                                                                  nToWriteBack,
5021                                                                  0);
5022
5023                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
5024                                                         __LINE__);
5025
5026                         }
5027
5028                 } else {
5029                         /* A full chunk. Write directly from the supplied buffer. */
5030
5031
5032
5033                         chunkWritten =
5034                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
5035                                                          dev->nDataBytesPerChunk,
5036                                                          0);
5037
5038                         /* Since we've overwritten the cached data, we better invalidate it. */
5039                         yaffs_InvalidateChunkCache(in, chunk);
5040                 }
5041
5042                 if (chunkWritten >= 0) {
5043                         n -= nToCopy;
5044                         offset += nToCopy;
5045                         buffer += nToCopy;
5046                         nDone += nToCopy;
5047                 }
5048
5049         }
5050
5051         /* Update file object */
5052
5053         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5054                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5055
5056         in->dirty = 1;
5057
5058         return nDone;
5059 }
5060
5061
5062 /* ---------------------- File resizing stuff ------------------ */
5063
5064 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5065 {
5066
5067         yaffs_Device *dev = in->myDev;
5068         int oldFileSize = in->variant.fileVariant.fileSize;
5069
5070         int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5071
5072         int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5073             dev->nDataBytesPerChunk;
5074         int i;
5075         int chunkId;
5076
5077         /* Delete backwards so that we don't end up with holes if
5078          * power is lost part-way through the operation.
5079          */
5080         for (i = lastDel; i >= startDel; i--) {
5081                 /* NB this could be optimised somewhat,
5082                  * eg. could retrieve the tags and write them without
5083                  * using yaffs_DeleteChunk
5084                  */
5085
5086                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5087                 if (chunkId > 0) {
5088                         if (chunkId <
5089                             (dev->internalStartBlock * dev->nChunksPerBlock)
5090                             || chunkId >=
5091                             ((dev->internalEndBlock +
5092                               1) * dev->nChunksPerBlock)) {
5093                                 T(YAFFS_TRACE_ALWAYS,
5094                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
5095                                    chunkId, i));
5096                         } else {
5097                                 in->nDataChunks--;
5098                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5099                         }
5100                 }
5101         }
5102
5103 }
5104
5105 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5106 {
5107
5108         int oldFileSize = in->variant.fileVariant.fileSize;
5109         __u32 newSizeOfPartialChunk;
5110         int newFullChunks;
5111
5112         yaffs_Device *dev = in->myDev;
5113
5114         yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5115
5116         yaffs_FlushFilesChunkCache(in);
5117         yaffs_InvalidateWholeChunkCache(in);
5118
5119         yaffs_CheckGarbageCollection(dev);
5120
5121         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5122                 return YAFFS_FAIL;
5123
5124         if (newSize == oldFileSize)
5125                 return YAFFS_OK;
5126
5127         if (newSize < oldFileSize) {
5128
5129                 yaffs_PruneResizedChunks(in, newSize);
5130
5131                 if (newSizeOfPartialChunk != 0) {
5132                         int lastChunk = 1 + newFullChunks;
5133
5134                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5135
5136                         /* Got to read and rewrite the last chunk with its new size and zero pad */
5137                         yaffs_ReadChunkDataFromObject(in, lastChunk,
5138                                                       localBuffer);
5139
5140                         memset(localBuffer + newSizeOfPartialChunk, 0,
5141                                dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5142
5143                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5144                                                      newSizeOfPartialChunk, 1);
5145
5146                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5147                 }
5148
5149                 in->variant.fileVariant.fileSize = newSize;
5150
5151                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5152         } else {
5153                 /* newsSize > oldFileSize */
5154                 in->variant.fileVariant.fileSize = newSize;
5155         }
5156
5157
5158         /* Write a new object header to reflect the resize.
5159          * show we've shrunk the file, if need be
5160          * Do this only if the file is not in the deleted directories
5161          * and is not shadowed.
5162          */
5163         if (in->parent &&
5164             !in->isShadowed &&
5165             in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5166             in->parent->objectId != YAFFS_OBJECTID_DELETED)
5167                 yaffs_UpdateObjectHeader(in, NULL, 0,
5168                                          (newSize < oldFileSize) ? 1 : 0, 0);
5169
5170         return YAFFS_OK;
5171 }
5172
5173 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5174 {
5175         YCHAR *alias = NULL;
5176         obj = yaffs_GetEquivalentObject(obj);
5177
5178         switch (obj->variantType) {
5179         case YAFFS_OBJECT_TYPE_FILE:
5180                 return obj->variant.fileVariant.fileSize;
5181         case YAFFS_OBJECT_TYPE_SYMLINK:
5182                 alias = obj->variant.symLinkVariant.alias;
5183                 if(!alias)
5184                         return 0;
5185                 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5186         default:
5187                 return 0;
5188         }
5189 }
5190
5191
5192
5193 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5194 {
5195         int retVal;
5196         if (in->dirty) {
5197                 yaffs_FlushFilesChunkCache(in);
5198                 if(dataSync) /* Only sync data */
5199                         retVal=YAFFS_OK;
5200                 else {
5201                         if (updateTime) {
5202 #ifdef CONFIG_YAFFS_WINCE
5203                                 yfsd_WinFileTimeNow(in->win_mtime);
5204 #else
5205
5206                                 in->yst_mtime = Y_CURRENT_TIME;
5207
5208 #endif
5209                         }
5210
5211                         retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5212                                 0) ? YAFFS_OK : YAFFS_FAIL;
5213                 }
5214         } else {
5215                 retVal = YAFFS_OK;
5216         }
5217
5218         return retVal;
5219
5220 }
5221
5222 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5223 {
5224
5225         /* First off, invalidate the file's data in the cache, without flushing. */
5226         yaffs_InvalidateWholeChunkCache(in);
5227
5228         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5229                 /* Move to the unlinked directory so we have a record that it was deleted. */
5230                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5231
5232         }
5233
5234         yaffs_RemoveObjectFromDirectory(in);
5235         yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5236         in->hdrChunk = 0;
5237
5238         yaffs_FreeObject(in);
5239         return YAFFS_OK;
5240
5241 }
5242
5243 /* yaffs_DeleteFile deletes the whole file data
5244  * and the inode associated with the file.
5245  * It does not delete the links associated with the file.
5246  */
5247 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5248 {
5249
5250         int retVal;
5251         int immediateDeletion = 0;
5252
5253         if (!in->myInode)
5254                 immediateDeletion = 1;
5255
5256         if (immediateDeletion) {
5257                 retVal =
5258                     yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5259                                            _Y("deleted"), 0, 0);
5260                 T(YAFFS_TRACE_TRACING,
5261                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5262                    in->objectId));
5263                 in->deleted = 1;
5264                 in->myDev->nDeletedFiles++;
5265                 if (1 || in->myDev->isYaffs2)
5266                         yaffs_ResizeFile(in, 0);
5267                 yaffs_SoftDeleteFile(in);
5268         } else {
5269                 retVal =
5270                     yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5271                                            _Y("unlinked"), 0, 0);
5272         }
5273
5274
5275         return retVal;
5276 }
5277
5278 int yaffs_DeleteFile(yaffs_Object *in)
5279 {
5280         int retVal = YAFFS_OK;
5281         int deleted = in->deleted;
5282
5283         yaffs_ResizeFile(in, 0);
5284
5285         if (in->nDataChunks > 0) {
5286                 /* Use soft deletion if there is data in the file.
5287                  * That won't be the case if it has been resized to zero.
5288                  */
5289                 if (!in->unlinked)
5290                         retVal = yaffs_UnlinkFileIfNeeded(in);
5291
5292                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5293                         in->deleted = 1;
5294                         deleted = 1;
5295                         in->myDev->nDeletedFiles++;
5296                         yaffs_SoftDeleteFile(in);
5297                 }
5298                 return deleted ? YAFFS_OK : YAFFS_FAIL;
5299         } else {
5300                 /* The file has no data chunks so we toss it immediately */
5301                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5302                 in->variant.fileVariant.top = NULL;
5303                 yaffs_DoGenericObjectDeletion(in);
5304
5305                 return YAFFS_OK;
5306         }
5307 }
5308
5309 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5310 {
5311         return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5312                 !(ylist_empty(&obj->variant.directoryVariant.children));
5313 }
5314
5315 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5316 {
5317         /* First check that the directory is empty. */
5318         if (yaffs_IsNonEmptyDirectory(obj))
5319                 return YAFFS_FAIL;
5320
5321         return yaffs_DoGenericObjectDeletion(obj);
5322 }
5323
5324 static int yaffs_DeleteSymLink(yaffs_Object *in)
5325 {
5326         if(in->variant.symLinkVariant.alias)
5327                 YFREE(in->variant.symLinkVariant.alias);
5328         in->variant.symLinkVariant.alias=NULL;
5329
5330         return yaffs_DoGenericObjectDeletion(in);
5331 }
5332
5333 static int yaffs_DeleteHardLink(yaffs_Object *in)
5334 {
5335         /* remove this hardlink from the list assocaited with the equivalent
5336          * object
5337          */
5338         ylist_del_init(&in->hardLinks);
5339         return yaffs_DoGenericObjectDeletion(in);
5340 }
5341
5342 int yaffs_DeleteObject(yaffs_Object *obj)
5343 {
5344 int retVal = -1;
5345         switch (obj->variantType) {
5346         case YAFFS_OBJECT_TYPE_FILE:
5347                 retVal = yaffs_DeleteFile(obj);
5348                 break;
5349         case YAFFS_OBJECT_TYPE_DIRECTORY:
5350                 return yaffs_DeleteDirectory(obj);
5351                 break;
5352         case YAFFS_OBJECT_TYPE_SYMLINK:
5353                 retVal = yaffs_DeleteSymLink(obj);
5354                 break;
5355         case YAFFS_OBJECT_TYPE_HARDLINK:
5356                 retVal = yaffs_DeleteHardLink(obj);
5357                 break;
5358         case YAFFS_OBJECT_TYPE_SPECIAL:
5359                 retVal = yaffs_DoGenericObjectDeletion(obj);
5360                 break;
5361         case YAFFS_OBJECT_TYPE_UNKNOWN:
5362                 retVal = 0;
5363                 break;          /* should not happen. */
5364         }
5365
5366         return retVal;
5367 }
5368
5369 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5370 {
5371
5372         int immediateDeletion = 0;
5373
5374         if (!obj->myInode)
5375                 immediateDeletion = 1;
5376
5377         if(obj)
5378                 yaffs_UpdateParent(obj->parent);
5379
5380         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5381                 return yaffs_DeleteHardLink(obj);
5382         } else if (!ylist_empty(&obj->hardLinks)) {
5383                 /* Curve ball: We're unlinking an object that has a hardlink.
5384                  *
5385                  * This problem arises because we are not strictly following
5386                  * The Linux link/inode model.
5387                  *
5388                  * We can't really delete the object.
5389                  * Instead, we do the following:
5390                  * - Select a hardlink.
5391                  * - Unhook it from the hard links
5392                  * - Move it from its parent directory (so that the rename can work)
5393                  * - Rename the object to the hardlink's name.
5394                  * - Delete the hardlink
5395                  */
5396
5397                 yaffs_Object *hl;
5398                 yaffs_Object *parent;
5399                 int retVal;
5400                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5401
5402                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5403
5404                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5405                 parent = hl->parent;
5406
5407                 ylist_del_init(&hl->hardLinks);
5408
5409                 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5410
5411                 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5412
5413                 if (retVal == YAFFS_OK)
5414                         retVal = yaffs_DoGenericObjectDeletion(hl);
5415
5416                 return retVal;
5417
5418         } else if (immediateDeletion) {
5419                 switch (obj->variantType) {
5420                 case YAFFS_OBJECT_TYPE_FILE:
5421                         return yaffs_DeleteFile(obj);
5422                         break;
5423                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5424                         return yaffs_DeleteDirectory(obj);
5425                         break;
5426                 case YAFFS_OBJECT_TYPE_SYMLINK:
5427                         return yaffs_DeleteSymLink(obj);
5428                         break;
5429                 case YAFFS_OBJECT_TYPE_SPECIAL:
5430                         return yaffs_DoGenericObjectDeletion(obj);
5431                         break;
5432                 case YAFFS_OBJECT_TYPE_HARDLINK:
5433                 case YAFFS_OBJECT_TYPE_UNKNOWN:
5434                 default:
5435                         return YAFFS_FAIL;
5436                 }
5437         } else if(yaffs_IsNonEmptyDirectory(obj))
5438                 return YAFFS_FAIL;
5439         else
5440                 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5441                                            _Y("unlinked"), 0, 0);
5442 }
5443
5444
5445 static int yaffs_UnlinkObject(yaffs_Object *obj)
5446 {
5447
5448         if (obj && obj->unlinkAllowed)
5449                 return yaffs_UnlinkWorker(obj);
5450
5451         return YAFFS_FAIL;
5452
5453 }
5454 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5455 {
5456         yaffs_Object *obj;
5457
5458         obj = yaffs_FindObjectByName(dir, name);
5459         return yaffs_UnlinkObject(obj);
5460 }
5461
5462 /*----------------------- Initialisation Scanning ---------------------- */
5463
5464 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5465                                 int backwardScanning)
5466 {
5467         yaffs_Object *obj;
5468
5469         if (!backwardScanning) {
5470                 /* Handle YAFFS1 forward scanning case
5471                  * For YAFFS1 we always do the deletion
5472                  */
5473
5474         } else {
5475                 /* Handle YAFFS2 case (backward scanning)
5476                  * If the shadowed object exists then ignore.
5477                  */
5478                 obj = yaffs_FindObjectByNumber(dev, objId);
5479                 if(obj)
5480                         return;
5481         }
5482
5483         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5484          * We put it in unlinked dir to be cleaned up after the scanning
5485          */
5486         obj =
5487             yaffs_FindOrCreateObjectByNumber(dev, objId,
5488                                              YAFFS_OBJECT_TYPE_FILE);
5489         if (!obj)
5490                 return;
5491         obj->isShadowed = 1;
5492         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5493         obj->variant.fileVariant.shrinkSize = 0;
5494         obj->valid = 1;         /* So that we don't read any other info for this file */
5495
5496 }
5497
5498 typedef struct {
5499         int seq;
5500         int block;
5501 } yaffs_BlockIndex;
5502
5503
5504 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5505 {
5506         yaffs_Object *hl;
5507         yaffs_Object *in;
5508
5509         while (hardList) {
5510                 hl = hardList;
5511                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5512
5513                 in = yaffs_FindObjectByNumber(dev,
5514                                               hl->variant.hardLinkVariant.
5515                                               equivalentObjectId);
5516
5517                 if (in) {
5518                         /* Add the hardlink pointers */
5519                         hl->variant.hardLinkVariant.equivalentObject = in;
5520                         ylist_add(&hl->hardLinks, &in->hardLinks);
5521                 } else {
5522                         /* Todo Need to report/handle this better.
5523                          * Got a problem... hardlink to a non-existant object
5524                          */
5525                         hl->variant.hardLinkVariant.equivalentObject = NULL;
5526                         YINIT_LIST_HEAD(&hl->hardLinks);
5527
5528                 }
5529         }
5530 }
5531
5532
5533
5534
5535
5536 static int ybicmp(const void *a, const void *b)
5537 {
5538         register int aseq = ((yaffs_BlockIndex *)a)->seq;
5539         register int bseq = ((yaffs_BlockIndex *)b)->seq;
5540         register int ablock = ((yaffs_BlockIndex *)a)->block;
5541         register int bblock = ((yaffs_BlockIndex *)b)->block;
5542         if (aseq == bseq)
5543                 return ablock - bblock;
5544         else
5545                 return aseq - bseq;
5546 }
5547
5548
5549 struct yaffs_ShadowFixerStruct {
5550         int objectId;
5551         int shadowedId;
5552         struct yaffs_ShadowFixerStruct *next;
5553 };
5554
5555
5556 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5557 {
5558         /*
5559         *  Sort out state of unlinked and deleted objects after scanning.
5560         */
5561         struct ylist_head *i;
5562         struct ylist_head *n;
5563         yaffs_Object *l;
5564
5565         /* Soft delete all the unlinked files */
5566         ylist_for_each_safe(i, n,
5567                 &dev->unlinkedDir->variant.directoryVariant.children) {
5568                 if (i) {
5569                         l = ylist_entry(i, yaffs_Object, siblings);
5570                         yaffs_DeleteObject(l);
5571                 }
5572         }
5573
5574         ylist_for_each_safe(i, n,
5575                 &dev->deletedDir->variant.directoryVariant.children) {
5576                 if (i) {
5577                         l = ylist_entry(i, yaffs_Object, siblings);
5578                         yaffs_DeleteObject(l);
5579                 }
5580         }
5581
5582 }
5583
5584 /*
5585  * This code iterates through all the objects making sure that they are rooted.
5586  * Any unrooted objects are re-rooted in lost+found.
5587  * An object needs to be in one of:
5588  * - Directly under deleted, unlinked
5589  * - Directly or indirectly under root.
5590  *
5591  * Note:
5592  *  This code assumes that we don't ever change the current relationships between
5593  *  directories:
5594  *   rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5595  *   lostNfound->parent == rootDir
5596  *
5597  * This fixes the problem where directories might have inadvertently been deleted
5598  * leaving the object "hanging" without being rooted in the directory tree.
5599  */
5600  
5601 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5602 {
5603         return (obj == dev->deletedDir ||
5604                 obj == dev->unlinkedDir||
5605                 obj == dev->rootDir);
5606 }
5607
5608 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5609 {
5610         yaffs_Object *obj;
5611         yaffs_Object *parent;
5612         int i;
5613         struct ylist_head *lh;
5614         struct ylist_head *n;
5615         int depthLimit;
5616         int hanging;
5617
5618
5619         /* Iterate through the objects in each hash entry,
5620          * looking at each object.
5621          * Make sure it is rooted.
5622          */
5623
5624         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
5625                 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5626                         if (lh) {
5627                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
5628                                 parent= obj->parent;
5629                                 
5630                                 if(yaffs_HasNULLParent(dev,obj)){
5631                                         /* These directories are not hanging */
5632                                         hanging = 0;
5633                                 }
5634                                 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5635                                         hanging = 1;
5636                                 else if(yaffs_HasNULLParent(dev,parent))
5637                                         hanging = 0;
5638                                 else {
5639                                         /*
5640                                          * Need to follow the parent chain to see if it is hanging.
5641                                          */
5642                                         hanging = 0;
5643                                         depthLimit=100;
5644
5645                                         while(parent != dev->rootDir &&
5646                                                 parent->parent &&
5647                                                 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5648                                                 depthLimit > 0){
5649                                                 parent = parent->parent;
5650                                                 depthLimit--;
5651                                         }
5652                                         if(parent != dev->rootDir)
5653                                                 hanging = 1;
5654                                 }
5655                                 if(hanging){
5656                                         T(YAFFS_TRACE_SCAN,
5657                                           (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5658                                                 obj->objectId));
5659                                         yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5660                                 }
5661                         }
5662                 }
5663         }
5664 }
5665
5666
5667 /*
5668  * Delete directory contents for cleaning up lost and found.
5669  */
5670 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5671 {
5672         yaffs_Object *obj;
5673         struct ylist_head *lh;
5674         struct ylist_head *n;
5675
5676         if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5677                 YBUG();
5678         
5679         ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5680                 if (lh) {
5681                         obj = ylist_entry(lh, yaffs_Object, siblings);
5682                         if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5683                                 yaffs_DeleteDirectoryContents(obj);
5684
5685                         T(YAFFS_TRACE_SCAN,
5686                                 (TSTR("Deleting lost_found object %d" TENDSTR),
5687                                 obj->objectId));
5688
5689                         /* Need to use UnlinkObject since Delete would not handle
5690                          * hardlinked objects correctly.
5691                          */
5692                         yaffs_UnlinkObject(obj); 
5693                 }
5694         }
5695                         
5696 }
5697
5698 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5699 {
5700         yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5701 }
5702
5703 static int yaffs_Scan(yaffs_Device *dev)
5704 {
5705         yaffs_ExtendedTags tags;
5706         int blk;
5707         int blockIterator;
5708         int startIterator;
5709         int endIterator;
5710         int result;
5711
5712         int chunk;
5713         int c;
5714         int deleted;
5715         yaffs_BlockState state;
5716         yaffs_Object *hardList = NULL;
5717         yaffs_BlockInfo *bi;
5718         __u32 sequenceNumber;
5719         yaffs_ObjectHeader *oh;
5720         yaffs_Object *in;
5721         yaffs_Object *parent;
5722
5723         int alloc_failed = 0;
5724
5725         struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5726
5727
5728         __u8 *chunkData;
5729
5730
5731
5732         T(YAFFS_TRACE_SCAN,
5733           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
5734            dev->internalStartBlock, dev->internalEndBlock));
5735
5736         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5737
5738         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5739
5740         /* Scan all the blocks to determine their state */
5741         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5742                 bi = yaffs_GetBlockInfo(dev, blk);
5743                 yaffs_ClearChunkBits(dev, blk);
5744                 bi->pagesInUse = 0;
5745                 bi->softDeletions = 0;
5746
5747                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5748
5749                 bi->blockState = state;
5750                 bi->sequenceNumber = sequenceNumber;
5751
5752                 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5753                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5754
5755                 T(YAFFS_TRACE_SCAN_DEBUG,
5756                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5757                    state, sequenceNumber));
5758
5759                 if (state == YAFFS_BLOCK_STATE_DEAD) {
5760                         T(YAFFS_TRACE_BAD_BLOCKS,
5761                           (TSTR("block %d is bad" TENDSTR), blk));
5762                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5763                         T(YAFFS_TRACE_SCAN_DEBUG,
5764                           (TSTR("Block empty " TENDSTR)));
5765                         dev->nErasedBlocks++;
5766                         dev->nFreeChunks += dev->nChunksPerBlock;
5767                 }
5768         }
5769
5770         startIterator = dev->internalStartBlock;
5771         endIterator = dev->internalEndBlock;
5772
5773         /* For each block.... */
5774         for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5775              blockIterator++) {
5776
5777                 YYIELD();
5778
5779                 YYIELD();
5780
5781                 blk = blockIterator;
5782
5783                 bi = yaffs_GetBlockInfo(dev, blk);
5784                 state = bi->blockState;
5785
5786                 deleted = 0;
5787
5788                 /* For each chunk in each block that needs scanning....*/
5789                 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5790                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5791                         /* Read the tags and decide what to do */
5792                         chunk = blk * dev->nChunksPerBlock + c;
5793
5794                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5795                                                         &tags);
5796
5797                         /* Let's have a good look at this chunk... */
5798
5799                         if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5800                                 /* YAFFS1 only...
5801                                  * A deleted chunk
5802                                  */
5803                                 deleted++;
5804                                 dev->nFreeChunks++;
5805                                 /*T((" %d %d deleted\n",blk,c)); */
5806                         } else if (!tags.chunkUsed) {
5807                                 /* An unassigned chunk in the block
5808                                  * This means that either the block is empty or
5809                                  * this is the one being allocated from
5810                                  */
5811
5812                                 if (c == 0) {
5813                                         /* We're looking at the first chunk in the block so the block is unused */
5814                                         state = YAFFS_BLOCK_STATE_EMPTY;
5815                                         dev->nErasedBlocks++;
5816                                 } else {
5817                                         /* this is the block being allocated from */
5818                                         T(YAFFS_TRACE_SCAN,
5819                                           (TSTR
5820                                            (" Allocating from %d %d" TENDSTR),
5821                                            blk, c));
5822                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
5823                                         dev->allocationBlock = blk;
5824                                         dev->allocationPage = c;
5825                                         dev->allocationBlockFinder = blk;
5826                                         /* Set block finder here to encourage the allocator to go forth from here. */
5827
5828                                 }
5829
5830                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5831                         } else if (tags.chunkId > 0) {
5832                                 /* chunkId > 0 so it is a data chunk... */
5833                                 unsigned int endpos;
5834
5835                                 yaffs_SetChunkBit(dev, blk, c);
5836                                 bi->pagesInUse++;
5837
5838                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5839                                                                       tags.
5840                                                                       objectId,
5841                                                                       YAFFS_OBJECT_TYPE_FILE);
5842                                 /* PutChunkIntoFile checks for a clash (two data chunks with
5843                                  * the same chunkId).
5844                                  */
5845
5846                                 if (!in)
5847                                         alloc_failed = 1;
5848
5849                                 if (in) {
5850                                         if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5851                                                 alloc_failed = 1;
5852                                 }
5853
5854                                 endpos =
5855                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5856                                     tags.byteCount;
5857                                 if (in &&
5858                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
5859                                     && in->variant.fileVariant.scannedFileSize <
5860                                     endpos) {
5861                                         in->variant.fileVariant.
5862                                             scannedFileSize = endpos;
5863                                         if (!dev->useHeaderFileSize) {
5864                                                 in->variant.fileVariant.
5865                                                     fileSize =
5866                                                     in->variant.fileVariant.
5867                                                     scannedFileSize;
5868                                         }
5869
5870                                 }
5871                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
5872                         } else {
5873                                 /* chunkId == 0, so it is an ObjectHeader.
5874                                  * Thus, we read in the object header and make the object
5875                                  */
5876                                 yaffs_SetChunkBit(dev, blk, c);
5877                                 bi->pagesInUse++;
5878
5879                                 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5880                                                                 chunkData,
5881                                                                 NULL);
5882
5883                                 oh = (yaffs_ObjectHeader *) chunkData;
5884
5885                                 in = yaffs_FindObjectByNumber(dev,
5886                                                               tags.objectId);
5887                                 if (in && in->variantType != oh->type) {
5888                                         /* This should not happen, but somehow
5889                                          * Wev'e ended up with an objectId that has been reused but not yet
5890                                          * deleted, and worse still it has changed type. Delete the old object.
5891                                          */
5892
5893                                         yaffs_DeleteObject(in);
5894
5895                                         in = 0;
5896                                 }
5897
5898                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5899                                                                       tags.
5900                                                                       objectId,
5901                                                                       oh->type);
5902
5903                                 if (!in)
5904                                         alloc_failed = 1;
5905
5906                                 if (in && oh->shadowsObject > 0) {
5907
5908                                         struct yaffs_ShadowFixerStruct *fixer;
5909                                         fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5910                                         if (fixer) {
5911                                                 fixer->next = shadowFixerList;
5912                                                 shadowFixerList = fixer;
5913                                                 fixer->objectId = tags.objectId;
5914                                                 fixer->shadowedId = oh->shadowsObject;
5915                                         }
5916
5917                                 }
5918
5919                                 if (in && in->valid) {
5920                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
5921
5922                                         unsigned existingSerial = in->serial;
5923                                         unsigned newSerial = tags.serialNumber;
5924
5925                                         if (((existingSerial + 1) & 3) == newSerial) {
5926                                                 /* Use new one - destroy the exisiting one */
5927                                                 yaffs_DeleteChunk(dev,
5928                                                                   in->hdrChunk,
5929                                                                   1, __LINE__);
5930                                                 in->valid = 0;
5931                                         } else {
5932                                                 /* Use existing - destroy this one. */
5933                                                 yaffs_DeleteChunk(dev, chunk, 1,
5934                                                                   __LINE__);
5935                                         }
5936                                 }
5937
5938                                 if (in && !in->valid &&
5939                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5940                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5941                                         /* We only load some info, don't fiddle with directory structure */
5942                                         in->valid = 1;
5943                                         in->variantType = oh->type;
5944
5945                                         in->yst_mode = oh->yst_mode;
5946 #ifdef CONFIG_YAFFS_WINCE
5947                                         in->win_atime[0] = oh->win_atime[0];
5948                                         in->win_ctime[0] = oh->win_ctime[0];
5949                                         in->win_mtime[0] = oh->win_mtime[0];
5950                                         in->win_atime[1] = oh->win_atime[1];
5951                                         in->win_ctime[1] = oh->win_ctime[1];
5952                                         in->win_mtime[1] = oh->win_mtime[1];
5953 #else
5954                                         in->yst_uid = oh->yst_uid;
5955                                         in->yst_gid = oh->yst_gid;
5956                                         in->yst_atime = oh->yst_atime;
5957                                         in->yst_mtime = oh->yst_mtime;
5958                                         in->yst_ctime = oh->yst_ctime;
5959                                         in->yst_rdev = oh->yst_rdev;
5960 #endif
5961                                         in->hdrChunk = chunk;
5962                                         in->serial = tags.serialNumber;
5963
5964                                 } else if (in && !in->valid) {
5965                                         /* we need to load this info */
5966
5967                                         in->valid = 1;
5968                                         in->variantType = oh->type;
5969
5970                                         in->yst_mode = oh->yst_mode;
5971 #ifdef CONFIG_YAFFS_WINCE
5972                                         in->win_atime[0] = oh->win_atime[0];
5973                                         in->win_ctime[0] = oh->win_ctime[0];
5974                                         in->win_mtime[0] = oh->win_mtime[0];
5975                                         in->win_atime[1] = oh->win_atime[1];
5976                                         in->win_ctime[1] = oh->win_ctime[1];
5977                                         in->win_mtime[1] = oh->win_mtime[1];
5978 #else
5979                                         in->yst_uid = oh->yst_uid;
5980                                         in->yst_gid = oh->yst_gid;
5981                                         in->yst_atime = oh->yst_atime;
5982                                         in->yst_mtime = oh->yst_mtime;
5983                                         in->yst_ctime = oh->yst_ctime;
5984                                         in->yst_rdev = oh->yst_rdev;
5985 #endif
5986                                         in->hdrChunk = chunk;
5987                                         in->serial = tags.serialNumber;
5988
5989                                         yaffs_SetObjectName(in, oh->name);
5990                                         in->dirty = 0;
5991
5992                                         /* directory stuff...
5993                                          * hook up to parent
5994                                          */
5995
5996                                         parent =
5997                                             yaffs_FindOrCreateObjectByNumber
5998                                             (dev, oh->parentObjectId,
5999                                              YAFFS_OBJECT_TYPE_DIRECTORY);
6000                                         if (!parent)
6001                                                 alloc_failed = 1;
6002                                         if (parent && parent->variantType ==
6003                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6004                                                 /* Set up as a directory */
6005                                                 parent->variantType =
6006                                                         YAFFS_OBJECT_TYPE_DIRECTORY;
6007                                                 YINIT_LIST_HEAD(&parent->variant.
6008                                                                 directoryVariant.
6009                                                                 children);
6010                                         } else if (!parent || parent->variantType !=
6011                                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
6012                                                 /* Hoosterman, another problem....
6013                                                  * We're trying to use a non-directory as a directory
6014                                                  */
6015
6016                                                 T(YAFFS_TRACE_ERROR,
6017                                                   (TSTR
6018                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6019                                                     TENDSTR)));
6020                                                 parent = dev->lostNFoundDir;
6021                                         }
6022
6023                                         yaffs_AddObjectToDirectory(parent, in);
6024
6025                                         if (0 && (parent == dev->deletedDir ||
6026                                                   parent == dev->unlinkedDir)) {
6027                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
6028                                                 dev->nDeletedFiles++;
6029                                         }
6030                                         /* Note re hardlinks.
6031                                          * Since we might scan a hardlink before its equivalent object is scanned
6032                                          * we put them all in a list.
6033                                          * After scanning is complete, we should have all the objects, so we run through this
6034                                          * list and fix up all the chains.
6035                                          */
6036
6037                                         switch (in->variantType) {
6038                                         case YAFFS_OBJECT_TYPE_UNKNOWN:
6039                                                 /* Todo got a problem */
6040                                                 break;
6041                                         case YAFFS_OBJECT_TYPE_FILE:
6042                                                 if (dev->useHeaderFileSize)
6043
6044                                                         in->variant.fileVariant.
6045                                                             fileSize =
6046                                                             oh->fileSize;
6047
6048                                                 break;
6049                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6050                                                 in->variant.hardLinkVariant.
6051                                                         equivalentObjectId =
6052                                                         oh->equivalentObjectId;
6053                                                 in->hardLinks.next =
6054                                                         (struct ylist_head *)
6055                                                         hardList;
6056                                                 hardList = in;
6057                                                 break;
6058                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6059                                                 /* Do nothing */
6060                                                 break;
6061                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6062                                                 /* Do nothing */
6063                                                 break;
6064                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6065                                                 in->variant.symLinkVariant.alias =
6066                                                     yaffs_CloneString(oh->alias);
6067                                                 if (!in->variant.symLinkVariant.alias)
6068                                                         alloc_failed = 1;
6069                                                 break;
6070                                         }
6071
6072                                 }
6073                         }
6074                 }
6075
6076                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6077                         /* If we got this far while scanning, then the block is fully allocated.*/
6078                         state = YAFFS_BLOCK_STATE_FULL;
6079                 }
6080
6081                 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6082                         /* If the block was partially allocated then treat it as fully allocated.*/
6083                         state = YAFFS_BLOCK_STATE_FULL;
6084                         dev->allocationBlock = -1;
6085                 }
6086
6087                 bi->blockState = state;
6088
6089                 /* Now let's see if it was dirty */
6090                 if (bi->pagesInUse == 0 &&
6091                     !bi->hasShrinkHeader &&
6092                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6093                         yaffs_BlockBecameDirty(dev, blk);
6094                 }
6095
6096         }
6097
6098
6099         /* Ok, we've done all the scanning.
6100          * Fix up the hard link chains.
6101          * We should now have scanned all the objects, now it's time to add these
6102          * hardlinks.
6103          */
6104
6105         yaffs_HardlinkFixup(dev, hardList);
6106
6107         /* Fix up any shadowed objects */
6108         {
6109                 struct yaffs_ShadowFixerStruct *fixer;
6110                 yaffs_Object *obj;
6111
6112                 while (shadowFixerList) {
6113                         fixer = shadowFixerList;
6114                         shadowFixerList = fixer->next;
6115                         /* Complete the rename transaction by deleting the shadowed object
6116                          * then setting the object header to unshadowed.
6117                          */
6118                         obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6119                         if (obj)
6120                                 yaffs_DeleteObject(obj);
6121
6122                         obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6123
6124                         if (obj)
6125                                 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6126
6127                         YFREE(fixer);
6128                 }
6129         }
6130
6131         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6132
6133         if (alloc_failed)
6134                 return YAFFS_FAIL;
6135
6136         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6137
6138
6139         return YAFFS_OK;
6140 }
6141
6142 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6143 {
6144         __u8 *chunkData;
6145         yaffs_ObjectHeader *oh;
6146         yaffs_Device *dev;
6147         yaffs_ExtendedTags tags;
6148         int result;
6149         int alloc_failed = 0;
6150
6151         if (!in)
6152                 return;
6153
6154         dev = in->myDev;
6155
6156 #if 0
6157         T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6158                 in->objectId,
6159                 in->lazyLoaded ? "not yet" : "already"));
6160 #endif
6161
6162         if (in->lazyLoaded && in->hdrChunk > 0) {
6163                 in->lazyLoaded = 0;
6164                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6165
6166                 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6167                 oh = (yaffs_ObjectHeader *) chunkData;
6168
6169                 in->yst_mode = oh->yst_mode;
6170 #ifdef CONFIG_YAFFS_WINCE
6171                 in->win_atime[0] = oh->win_atime[0];
6172                 in->win_ctime[0] = oh->win_ctime[0];
6173                 in->win_mtime[0] = oh->win_mtime[0];
6174                 in->win_atime[1] = oh->win_atime[1];
6175                 in->win_ctime[1] = oh->win_ctime[1];
6176                 in->win_mtime[1] = oh->win_mtime[1];
6177 #else
6178                 in->yst_uid = oh->yst_uid;
6179                 in->yst_gid = oh->yst_gid;
6180                 in->yst_atime = oh->yst_atime;
6181                 in->yst_mtime = oh->yst_mtime;
6182                 in->yst_ctime = oh->yst_ctime;
6183                 in->yst_rdev = oh->yst_rdev;
6184
6185 #endif
6186                 yaffs_SetObjectName(in, oh->name);
6187
6188                 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6189                         in->variant.symLinkVariant.alias =
6190                                                     yaffs_CloneString(oh->alias);
6191                         if (!in->variant.symLinkVariant.alias)
6192                                 alloc_failed = 1; /* Not returned to caller */
6193                 }
6194
6195                 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6196         }
6197 }
6198
6199 static int yaffs_ScanBackwards(yaffs_Device *dev)
6200 {
6201         yaffs_ExtendedTags tags;
6202         int blk;
6203         int blockIterator;
6204         int startIterator;
6205         int endIterator;
6206         int nBlocksToScan = 0;
6207
6208         int chunk;
6209         int result;
6210         int c;
6211         int deleted;
6212         yaffs_BlockState state;
6213         yaffs_Object *hardList = NULL;
6214         yaffs_BlockInfo *bi;
6215         __u32 sequenceNumber;
6216         yaffs_ObjectHeader *oh;
6217         yaffs_Object *in;
6218         yaffs_Object *parent;
6219         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6220         int itsUnlinked;
6221         __u8 *chunkData;
6222
6223         int fileSize;
6224         int isShrink;
6225         int foundChunksInBlock;
6226         int equivalentObjectId;
6227         int alloc_failed = 0;
6228
6229
6230         yaffs_BlockIndex *blockIndex = NULL;
6231         int altBlockIndex = 0;
6232
6233         if (!dev->isYaffs2) {
6234                 T(YAFFS_TRACE_SCAN,
6235                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6236                 return YAFFS_FAIL;
6237         }
6238
6239         T(YAFFS_TRACE_SCAN,
6240           (TSTR
6241            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
6242             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6243
6244
6245         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6246
6247         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6248
6249         if (!blockIndex) {
6250                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6251                 altBlockIndex = 1;
6252         }
6253
6254         if (!blockIndex) {
6255                 T(YAFFS_TRACE_SCAN,
6256                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6257                 return YAFFS_FAIL;
6258         }
6259
6260         dev->blocksInCheckpoint = 0;
6261
6262         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6263
6264         /* Scan all the blocks to determine their state */
6265         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6266                 bi = yaffs_GetBlockInfo(dev, blk);
6267                 yaffs_ClearChunkBits(dev, blk);
6268                 bi->pagesInUse = 0;
6269                 bi->softDeletions = 0;
6270
6271                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6272
6273                 bi->blockState = state;
6274                 bi->sequenceNumber = sequenceNumber;
6275
6276                 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6277                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6278                 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6279                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6280
6281                 T(YAFFS_TRACE_SCAN_DEBUG,
6282                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6283                    state, sequenceNumber));
6284
6285
6286                 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6287                         dev->blocksInCheckpoint++;
6288
6289                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6290                         T(YAFFS_TRACE_BAD_BLOCKS,
6291                           (TSTR("block %d is bad" TENDSTR), blk));
6292                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6293                         T(YAFFS_TRACE_SCAN_DEBUG,
6294                           (TSTR("Block empty " TENDSTR)));
6295                         dev->nErasedBlocks++;
6296                         dev->nFreeChunks += dev->nChunksPerBlock;
6297                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6298
6299                         /* Determine the highest sequence number */
6300                         if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6301                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6302
6303                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
6304                                 blockIndex[nBlocksToScan].block = blk;
6305
6306                                 nBlocksToScan++;
6307
6308                                 if (sequenceNumber >= dev->sequenceNumber)
6309                                         dev->sequenceNumber = sequenceNumber;
6310                         } else {
6311                                 /* TODO: Nasty sequence number! */
6312                                 T(YAFFS_TRACE_SCAN,
6313                                   (TSTR
6314                                    ("Block scanning block %d has bad sequence number %d"
6315                                     TENDSTR), blk, sequenceNumber));
6316
6317                         }
6318                 }
6319         }
6320
6321         T(YAFFS_TRACE_SCAN,
6322         (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6323
6324
6325
6326         YYIELD();
6327
6328         /* Sort the blocks */
6329 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6330         {
6331                 /* Use qsort now. */
6332                 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6333         }
6334 #else
6335         {
6336                 /* Dungy old bubble sort... */
6337
6338                 yaffs_BlockIndex temp;
6339                 int i;
6340                 int j;
6341
6342                 for (i = 0; i < nBlocksToScan; i++)
6343                         for (j = i + 1; j < nBlocksToScan; j++)
6344                                 if (blockIndex[i].seq > blockIndex[j].seq) {
6345                                         temp = blockIndex[j];
6346                                         blockIndex[j] = blockIndex[i];
6347                                         blockIndex[i] = temp;
6348                                 }
6349         }
6350 #endif
6351
6352         YYIELD();
6353
6354         T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6355
6356         /* Now scan the blocks looking at the data. */
6357         startIterator = 0;
6358         endIterator = nBlocksToScan - 1;
6359         T(YAFFS_TRACE_SCAN_DEBUG,
6360           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6361
6362         /* For each block.... backwards */
6363         for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6364                         blockIterator--) {
6365                 /* Cooperative multitasking! This loop can run for so
6366                    long that watchdog timers expire. */
6367                 YYIELD();
6368
6369                 /* get the block to scan in the correct order */
6370                 blk = blockIndex[blockIterator].block;
6371
6372                 bi = yaffs_GetBlockInfo(dev, blk);
6373
6374
6375                 state = bi->blockState;
6376
6377                 deleted = 0;
6378
6379                 /* For each chunk in each block that needs scanning.... */
6380                 foundChunksInBlock = 0;
6381                 for (c = dev->nChunksPerBlock - 1;
6382                      !alloc_failed && c >= 0 &&
6383                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6384                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6385                         /* Scan backwards...
6386                          * Read the tags and decide what to do
6387                          */
6388
6389                         chunk = blk * dev->nChunksPerBlock + c;
6390
6391                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6392                                                         &tags);
6393
6394                         /* Let's have a good look at this chunk... */
6395
6396                         if (!tags.chunkUsed) {
6397                                 /* An unassigned chunk in the block.
6398                                  * If there are used chunks after this one, then
6399                                  * it is a chunk that was skipped due to failing the erased
6400                                  * check. Just skip it so that it can be deleted.
6401                                  * But, more typically, We get here when this is an unallocated
6402                                  * chunk and his means that either the block is empty or
6403                                  * this is the one being allocated from
6404                                  */
6405
6406                                 if (foundChunksInBlock) {
6407                                         /* This is a chunk that was skipped due to failing the erased check */
6408                                 } else if (c == 0) {
6409                                         /* We're looking at the first chunk in the block so the block is unused */
6410                                         state = YAFFS_BLOCK_STATE_EMPTY;
6411                                         dev->nErasedBlocks++;
6412                                 } else {
6413                                         if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6414                                             state == YAFFS_BLOCK_STATE_ALLOCATING) {
6415                                                 if (dev->sequenceNumber == bi->sequenceNumber) {
6416                                                         /* this is the block being allocated from */
6417
6418                                                         T(YAFFS_TRACE_SCAN,
6419                                                           (TSTR
6420                                                            (" Allocating from %d %d"
6421                                                             TENDSTR), blk, c));
6422
6423                                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
6424                                                         dev->allocationBlock = blk;
6425                                                         dev->allocationPage = c;
6426                                                         dev->allocationBlockFinder = blk;
6427                                                 } else {
6428                                                         /* This is a partially written block that is not
6429                                                          * the current allocation block.
6430                                                          */
6431
6432                                                          T(YAFFS_TRACE_ALWAYS,
6433                                                          (TSTR("Partially written block %d detected" TENDSTR),
6434                                                          blk));
6435                                                 }
6436                                         }
6437                                 }
6438
6439                                 dev->nFreeChunks++;
6440
6441                         } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6442                                 T(YAFFS_TRACE_SCAN,
6443                                   (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6444                                   blk, c));
6445
6446                                   dev->nFreeChunks++;
6447
6448                         } else if (tags.chunkId > 0) {
6449                                 /* chunkId > 0 so it is a data chunk... */
6450                                 unsigned int endpos;
6451                                 __u32 chunkBase =
6452                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6453
6454                                 foundChunksInBlock = 1;
6455
6456
6457                                 yaffs_SetChunkBit(dev, blk, c);
6458                                 bi->pagesInUse++;
6459
6460                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6461                                                                       tags.
6462                                                                       objectId,
6463                                                                       YAFFS_OBJECT_TYPE_FILE);
6464                                 if (!in) {
6465                                         /* Out of memory */
6466                                         alloc_failed = 1;
6467                                 }
6468
6469                                 if (in &&
6470                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
6471                                     && chunkBase <
6472                                     in->variant.fileVariant.shrinkSize) {
6473                                         /* This has not been invalidated by a resize */
6474                                         if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6475                                                                chunk, -1)) {
6476                                                 alloc_failed = 1;
6477                                         }
6478
6479                                         /* File size is calculated by looking at the data chunks if we have not
6480                                          * seen an object header yet. Stop this practice once we find an object header.
6481                                          */
6482                                         endpos =
6483                                             (tags.chunkId -
6484                                              1) * dev->nDataBytesPerChunk +
6485                                             tags.byteCount;
6486
6487                                         if (!in->valid &&       /* have not got an object header yet */
6488                                             in->variant.fileVariant.
6489                                             scannedFileSize < endpos) {
6490                                                 in->variant.fileVariant.
6491                                                     scannedFileSize = endpos;
6492                                                 in->variant.fileVariant.
6493                                                     fileSize =
6494                                                     in->variant.fileVariant.
6495                                                     scannedFileSize;
6496                                         }
6497
6498                                 } else if (in) {
6499                                         /* This chunk has been invalidated by a resize, so delete */
6500                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6501
6502                                 }
6503                         } else {
6504                                 /* chunkId == 0, so it is an ObjectHeader.
6505                                  * Thus, we read in the object header and make the object
6506                                  */
6507                                 foundChunksInBlock = 1;
6508
6509                                 yaffs_SetChunkBit(dev, blk, c);
6510                                 bi->pagesInUse++;
6511
6512                                 oh = NULL;
6513                                 in = NULL;
6514
6515                                 if (tags.extraHeaderInfoAvailable) {
6516                                         in = yaffs_FindOrCreateObjectByNumber
6517                                             (dev, tags.objectId,
6518                                              tags.extraObjectType);
6519                                         if (!in)
6520                                                 alloc_failed = 1;
6521                                 }
6522
6523                                 if (!in ||
6524                                     (!in->valid && dev->disableLazyLoad) ||
6525                                     tags.extraShadows ||
6526                                     (!in->valid &&
6527                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6528                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6529
6530                                         /* If we don't have  valid info then we need to read the chunk
6531                                          * TODO In future we can probably defer reading the chunk and
6532                                          * living with invalid data until needed.
6533                                          */
6534
6535                                         result = yaffs_ReadChunkWithTagsFromNAND(dev,
6536                                                                         chunk,
6537                                                                         chunkData,
6538                                                                         NULL);
6539
6540                                         oh = (yaffs_ObjectHeader *) chunkData;
6541
6542                                         if (dev->inbandTags) {
6543                                                 /* Fix up the header if they got corrupted by inband tags */
6544                                                 oh->shadowsObject = oh->inbandShadowsObject;
6545                                                 oh->isShrink = oh->inbandIsShrink;
6546                                         }
6547
6548                                         if (!in) {
6549                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6550                                                 if (!in)
6551                                                         alloc_failed = 1;
6552                                         }
6553
6554                                 }
6555
6556                                 if (!in) {
6557                                         /* TODO Hoosterman we have a problem! */
6558                                         T(YAFFS_TRACE_ERROR,
6559                                           (TSTR
6560                                            ("yaffs tragedy: Could not make object for object  %d at chunk %d during scan"
6561                                             TENDSTR), tags.objectId, chunk));
6562                                         continue;
6563                                 }
6564
6565                                 if (in->valid) {
6566                                         /* We have already filled this one.
6567                                          * We have a duplicate that will be discarded, but
6568                                          * we first have to suck out resize info if it is a file.
6569                                          */
6570
6571                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6572                                              ((oh &&
6573                                                oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6574                                               (tags.extraHeaderInfoAvailable  &&
6575                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6576                                                 __u32 thisSize =
6577                                                     (oh) ? oh->fileSize : tags.
6578                                                     extraFileLength;
6579                                                 __u32 parentObjectId =
6580                                                     (oh) ? oh->
6581                                                     parentObjectId : tags.
6582                                                     extraParentObjectId;
6583
6584
6585                                                 isShrink =
6586                                                     (oh) ? oh->isShrink : tags.
6587                                                     extraIsShrinkHeader;
6588
6589                                                 /* If it is deleted (unlinked at start also means deleted)
6590                                                  * we treat the file size as being zeroed at this point.
6591                                                  */
6592                                                 if (parentObjectId ==
6593                                                     YAFFS_OBJECTID_DELETED
6594                                                     || parentObjectId ==
6595                                                     YAFFS_OBJECTID_UNLINKED) {
6596                                                         thisSize = 0;
6597                                                         isShrink = 1;
6598                                                 }
6599
6600                                                 if (isShrink &&
6601                                                     in->variant.fileVariant.
6602                                                     shrinkSize > thisSize) {
6603                                                         in->variant.fileVariant.
6604                                                             shrinkSize =
6605                                                             thisSize;
6606                                                 }
6607
6608                                                 if (isShrink)
6609                                                         bi->hasShrinkHeader = 1;
6610
6611                                         }
6612                                         /* Use existing - destroy this one. */
6613                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6614
6615                                 }
6616
6617                                 if (!in->valid && in->variantType !=
6618                                     (oh ? oh->type : tags.extraObjectType))
6619                                         T(YAFFS_TRACE_ERROR, (
6620                                                 TSTR("yaffs tragedy: Bad object type, "
6621                                             TCONT("%d != %d, for object %d at chunk ")
6622                                             TCONT("%d during scan")
6623                                                 TENDSTR), oh ?
6624                                             oh->type : tags.extraObjectType,
6625                                             in->variantType, tags.objectId,
6626                                             chunk));
6627
6628                                 if (!in->valid &&
6629                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6630                                      tags.objectId ==
6631                                      YAFFS_OBJECTID_LOSTNFOUND)) {
6632                                         /* We only load some info, don't fiddle with directory structure */
6633                                         in->valid = 1;
6634
6635                                         if (oh) {
6636                                                 in->variantType = oh->type;
6637
6638                                                 in->yst_mode = oh->yst_mode;
6639 #ifdef CONFIG_YAFFS_WINCE
6640                                                 in->win_atime[0] = oh->win_atime[0];
6641                                                 in->win_ctime[0] = oh->win_ctime[0];
6642                                                 in->win_mtime[0] = oh->win_mtime[0];
6643                                                 in->win_atime[1] = oh->win_atime[1];
6644                                                 in->win_ctime[1] = oh->win_ctime[1];
6645                                                 in->win_mtime[1] = oh->win_mtime[1];
6646 #else
6647                                                 in->yst_uid = oh->yst_uid;
6648                                                 in->yst_gid = oh->yst_gid;
6649                                                 in->yst_atime = oh->yst_atime;
6650                                                 in->yst_mtime = oh->yst_mtime;
6651                                                 in->yst_ctime = oh->yst_ctime;
6652                                                 in->yst_rdev = oh->yst_rdev;
6653
6654 #endif
6655                                         } else {
6656                                                 in->variantType = tags.extraObjectType;
6657                                                 in->lazyLoaded = 1;
6658                                         }
6659
6660                                         in->hdrChunk = chunk;
6661
6662                                 } else if (!in->valid) {
6663                                         /* we need to load this info */
6664
6665                                         in->valid = 1;
6666                                         in->hdrChunk = chunk;
6667
6668                                         if (oh) {
6669                                                 in->variantType = oh->type;
6670
6671                                                 in->yst_mode = oh->yst_mode;
6672 #ifdef CONFIG_YAFFS_WINCE
6673                                                 in->win_atime[0] = oh->win_atime[0];
6674                                                 in->win_ctime[0] = oh->win_ctime[0];
6675                                                 in->win_mtime[0] = oh->win_mtime[0];
6676                                                 in->win_atime[1] = oh->win_atime[1];
6677                                                 in->win_ctime[1] = oh->win_ctime[1];
6678                                                 in->win_mtime[1] = oh->win_mtime[1];
6679 #else
6680                                                 in->yst_uid = oh->yst_uid;
6681                                                 in->yst_gid = oh->yst_gid;
6682                                                 in->yst_atime = oh->yst_atime;
6683                                                 in->yst_mtime = oh->yst_mtime;
6684                                                 in->yst_ctime = oh->yst_ctime;
6685                                                 in->yst_rdev = oh->yst_rdev;
6686 #endif
6687
6688                                                 if (oh->shadowsObject > 0)
6689                                                         yaffs_HandleShadowedObject(dev,
6690                                                                            oh->
6691                                                                            shadowsObject,
6692                                                                            1);
6693                                                         
6694
6695
6696                                                 yaffs_SetObjectName(in, oh->name);
6697                                                 parent =
6698                                                     yaffs_FindOrCreateObjectByNumber
6699                                                         (dev, oh->parentObjectId,
6700                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6701
6702                                                  fileSize = oh->fileSize;
6703                                                  isShrink = oh->isShrink;
6704                                                  equivalentObjectId = oh->equivalentObjectId;
6705
6706                                         } else {
6707                                                 in->variantType = tags.extraObjectType;
6708                                                 parent =
6709                                                     yaffs_FindOrCreateObjectByNumber
6710                                                         (dev, tags.extraParentObjectId,
6711                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6712                                                  fileSize = tags.extraFileLength;
6713                                                  isShrink = tags.extraIsShrinkHeader;
6714                                                  equivalentObjectId = tags.extraEquivalentObjectId;
6715                                                 in->lazyLoaded = 1;
6716
6717                                         }
6718                                         in->dirty = 0;
6719
6720                                         if (!parent)
6721                                                 alloc_failed = 1;
6722
6723                                         /* directory stuff...
6724                                          * hook up to parent
6725                                          */
6726
6727                                         if (parent && parent->variantType ==
6728                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6729                                                 /* Set up as a directory */
6730                                                 parent->variantType =
6731                                                         YAFFS_OBJECT_TYPE_DIRECTORY;
6732                                                 YINIT_LIST_HEAD(&parent->variant.
6733                                                         directoryVariant.
6734                                                         children);
6735                                         } else if (!parent || parent->variantType !=
6736                                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
6737                                                 /* Hoosterman, another problem....
6738                                                  * We're trying to use a non-directory as a directory
6739                                                  */
6740
6741                                                 T(YAFFS_TRACE_ERROR,
6742                                                   (TSTR
6743                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6744                                                     TENDSTR)));
6745                                                 parent = dev->lostNFoundDir;
6746                                         }
6747
6748                                         yaffs_AddObjectToDirectory(parent, in);
6749
6750                                         itsUnlinked = (parent == dev->deletedDir) ||
6751                                                       (parent == dev->unlinkedDir);
6752
6753                                         if (isShrink) {
6754                                                 /* Mark the block as having a shrinkHeader */
6755                                                 bi->hasShrinkHeader = 1;
6756                                         }
6757
6758                                         /* Note re hardlinks.
6759                                          * Since we might scan a hardlink before its equivalent object is scanned
6760                                          * we put them all in a list.
6761                                          * After scanning is complete, we should have all the objects, so we run
6762                                          * through this list and fix up all the chains.
6763                                          */
6764
6765                                         switch (in->variantType) {
6766                                         case YAFFS_OBJECT_TYPE_UNKNOWN:
6767                                                 /* Todo got a problem */
6768                                                 break;
6769                                         case YAFFS_OBJECT_TYPE_FILE:
6770
6771                                                 if (in->variant.fileVariant.
6772                                                     scannedFileSize < fileSize) {
6773                                                         /* This covers the case where the file size is greater
6774                                                          * than where the data is
6775                                                          * This will happen if the file is resized to be larger
6776                                                          * than its current data extents.
6777                                                          */
6778                                                         in->variant.fileVariant.fileSize = fileSize;
6779                                                         in->variant.fileVariant.scannedFileSize =
6780                                                             in->variant.fileVariant.fileSize;
6781                                                 }
6782
6783                                                 if (isShrink &&
6784                                                     in->variant.fileVariant.shrinkSize > fileSize) {
6785                                                         in->variant.fileVariant.shrinkSize = fileSize;
6786                                                 }
6787
6788                                                 break;
6789                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6790                                                 if (!itsUnlinked) {
6791                                                         in->variant.hardLinkVariant.equivalentObjectId =
6792                                                                 equivalentObjectId;
6793                                                         in->hardLinks.next =
6794                                                                 (struct ylist_head *) hardList;
6795                                                         hardList = in;
6796                                                 }
6797                                                 break;
6798                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6799                                                 /* Do nothing */
6800                                                 break;
6801                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6802                                                 /* Do nothing */
6803                                                 break;
6804                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6805                                                 if (oh) {
6806                                                         in->variant.symLinkVariant.alias =
6807                                                                 yaffs_CloneString(oh->alias);
6808                                                         if (!in->variant.symLinkVariant.alias)
6809                                                                 alloc_failed = 1;
6810                                                 }
6811                                                 break;
6812                                         }
6813
6814                                 }
6815
6816                         }
6817
6818                 } /* End of scanning for each chunk */
6819
6820                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6821                         /* If we got this far while scanning, then the block is fully allocated. */
6822                         state = YAFFS_BLOCK_STATE_FULL;
6823                 }
6824
6825
6826                 bi->blockState = state;
6827
6828                 /* Now let's see if it was dirty */
6829                 if (bi->pagesInUse == 0 &&
6830                     !bi->hasShrinkHeader &&
6831                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6832                         yaffs_BlockBecameDirty(dev, blk);
6833                 }
6834
6835         }
6836         
6837         yaffs_SkipRestOfBlock(dev);
6838
6839         if (altBlockIndex)
6840                 YFREE_ALT(blockIndex);
6841         else
6842                 YFREE(blockIndex);
6843
6844         /* Ok, we've done all the scanning.
6845          * Fix up the hard link chains.
6846          * We should now have scanned all the objects, now it's time to add these
6847          * hardlinks.
6848          */
6849         yaffs_HardlinkFixup(dev, hardList);
6850
6851
6852         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6853
6854         if (alloc_failed)
6855                 return YAFFS_FAIL;
6856
6857         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6858
6859         return YAFFS_OK;
6860 }
6861
6862 /*------------------------------  Directory Functions ----------------------------- */
6863
6864 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6865 {
6866         struct ylist_head *lh;
6867         yaffs_Object *listObj;
6868
6869         int count = 0;
6870
6871         if (!obj) {
6872                 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6873                 YBUG();
6874                 return;
6875         }
6876
6877         if (yaffs_SkipVerification(obj->myDev))
6878                 return;
6879
6880         if (!obj->parent) {
6881                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6882                 YBUG();
6883                 return;
6884         }
6885
6886         if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6887                 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6888                 YBUG();
6889         }
6890
6891         /* Iterate through the objects in each hash entry */
6892
6893         ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6894                 if (lh) {
6895                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6896                         yaffs_VerifyObject(listObj);
6897                         if (obj == listObj)
6898                                 count++;
6899                 }
6900          }
6901
6902         if (count != 1) {
6903                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6904                 YBUG();
6905         }
6906 }
6907
6908 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6909 {
6910         struct ylist_head *lh;
6911         yaffs_Object *listObj;
6912
6913         if (!directory) {
6914                 YBUG();
6915                 return;
6916         }
6917
6918         if (yaffs_SkipFullVerification(directory->myDev))
6919                 return;
6920
6921         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6922                 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6923                 YBUG();
6924         }
6925
6926         /* Iterate through the objects in each hash entry */
6927
6928         ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6929                 if (lh) {
6930                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6931                         if (listObj->parent != directory) {
6932                                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6933                                 YBUG();
6934                         }
6935                         yaffs_VerifyObjectInDirectory(listObj);
6936                 }
6937         }
6938 }
6939
6940 /*
6941  *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6942  * link (ie. name) is created or deleted in the directory.
6943  *
6944  * ie.
6945  *   create dir/a : update dir's mtime/ctime
6946  *   rm dir/a:   update dir's mtime/ctime
6947  *   modify dir/a: don't update dir's mtimme/ctime
6948  */
6949  
6950 static void yaffs_UpdateParent(yaffs_Object *obj)
6951 {
6952         if(!obj)
6953                 return;
6954
6955         obj->dirty = 1;
6956         obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6957
6958         yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6959 }
6960
6961 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6962 {
6963         yaffs_Device *dev = obj->myDev;
6964         yaffs_Object *parent;
6965
6966         yaffs_VerifyObjectInDirectory(obj);
6967         parent = obj->parent;
6968
6969         yaffs_VerifyDirectory(parent);
6970
6971         if (dev && dev->removeObjectCallback)
6972                 dev->removeObjectCallback(obj);
6973
6974
6975         ylist_del_init(&obj->siblings);
6976         obj->parent = NULL;
6977         
6978         yaffs_VerifyDirectory(parent);
6979 }
6980
6981 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6982                                         yaffs_Object *obj)
6983 {
6984         if (!directory) {
6985                 T(YAFFS_TRACE_ALWAYS,
6986                   (TSTR
6987                    ("tragedy: Trying to add an object to a null pointer directory"
6988                     TENDSTR)));
6989                 YBUG();
6990                 return;
6991         }
6992         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6993                 T(YAFFS_TRACE_ALWAYS,
6994                   (TSTR
6995                    ("tragedy: Trying to add an object to a non-directory"
6996                     TENDSTR)));
6997                 YBUG();
6998         }
6999
7000         if (obj->siblings.prev == NULL) {
7001                 /* Not initialised */
7002                 YBUG();
7003         }
7004
7005
7006         yaffs_VerifyDirectory(directory);
7007
7008         yaffs_RemoveObjectFromDirectory(obj);
7009
7010
7011         /* Now add it */
7012         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7013         obj->parent = directory;
7014
7015         if (directory == obj->myDev->unlinkedDir
7016                         || directory == obj->myDev->deletedDir) {
7017                 obj->unlinked = 1;
7018                 obj->myDev->nUnlinkedFiles++;
7019                 obj->renameAllowed = 0;
7020         }
7021
7022         yaffs_VerifyDirectory(directory);
7023         yaffs_VerifyObjectInDirectory(obj);
7024 }
7025
7026 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7027                                      const YCHAR *name)
7028 {
7029         int sum;
7030
7031         struct ylist_head *i;
7032         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7033
7034         yaffs_Object *l;
7035
7036         if (!name)
7037                 return NULL;
7038
7039         if (!directory) {
7040                 T(YAFFS_TRACE_ALWAYS,
7041                   (TSTR
7042                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
7043                     TENDSTR)));
7044                 YBUG();
7045                 return NULL;
7046         }
7047         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7048                 T(YAFFS_TRACE_ALWAYS,
7049                   (TSTR
7050                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7051                 YBUG();
7052         }
7053
7054         sum = yaffs_CalcNameSum(name);
7055
7056         ylist_for_each(i, &directory->variant.directoryVariant.children) {
7057                 if (i) {
7058                         l = ylist_entry(i, yaffs_Object, siblings);
7059
7060                         if (l->parent != directory)
7061                                 YBUG();
7062
7063                         yaffs_CheckObjectDetailsLoaded(l);
7064
7065                         /* Special case for lost-n-found */
7066                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7067                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7068                                         return l;
7069                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7070                                 /* LostnFound chunk called Objxxx
7071                                  * Do a real check
7072                                  */
7073                                 yaffs_GetObjectName(l, buffer,
7074                                                     YAFFS_MAX_NAME_LENGTH + 1);
7075                                 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7076                                         return l;
7077                         }
7078                 }
7079         }
7080
7081         return NULL;
7082 }
7083
7084
7085 #if 0
7086 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7087                                         int (*fn) (yaffs_Object *))
7088 {
7089         struct ylist_head *i;
7090         yaffs_Object *l;
7091
7092         if (!theDir) {
7093                 T(YAFFS_TRACE_ALWAYS,
7094                   (TSTR
7095                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
7096                     TENDSTR)));
7097                 YBUG();
7098                 return YAFFS_FAIL;
7099         }
7100         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7101                 T(YAFFS_TRACE_ALWAYS,
7102                   (TSTR
7103                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7104                 YBUG();
7105                 return YAFFS_FAIL;
7106         }
7107
7108         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7109                 if (i) {
7110                         l = ylist_entry(i, yaffs_Object, siblings);
7111                         if (l && !fn(l))
7112                                 return YAFFS_FAIL;
7113                 }
7114         }
7115
7116         return YAFFS_OK;
7117
7118 }
7119 #endif
7120
7121 /* GetEquivalentObject dereferences any hard links to get to the
7122  * actual object.
7123  */
7124
7125 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7126 {
7127         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7128                 /* We want the object id of the equivalent object, not this one */
7129                 obj = obj->variant.hardLinkVariant.equivalentObject;
7130                 yaffs_CheckObjectDetailsLoaded(obj);
7131         }
7132         return obj;
7133 }
7134
7135 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7136 {
7137         memset(name, 0, buffSize * sizeof(YCHAR));
7138
7139         yaffs_CheckObjectDetailsLoaded(obj);
7140
7141         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7142                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7143         } else if (obj->hdrChunk <= 0) {
7144                 YCHAR locName[20];
7145                 YCHAR numString[20];
7146                 YCHAR *x = &numString[19];
7147                 unsigned v = obj->objectId;
7148                 numString[19] = 0;
7149                 while (v > 0) {
7150                         x--;
7151                         *x = '0' + (v % 10);
7152                         v /= 10;
7153                 }
7154                 /* make up a name */
7155                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7156                 yaffs_strcat(locName, x);
7157                 yaffs_strncpy(name, locName, buffSize - 1);
7158
7159         }
7160 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7161         else if (obj->shortName[0])
7162                 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7163 #endif
7164         else {
7165                 int result;
7166                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7167
7168                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7169
7170                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7171
7172                 if (obj->hdrChunk > 0) {
7173                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7174                                                         obj->hdrChunk, buffer,
7175                                                         NULL);
7176                 }
7177                 yaffs_strncpy(name, oh->name, buffSize - 1);
7178                 name[buffSize-1]=0;
7179
7180                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7181         }
7182
7183         return yaffs_strnlen(name,buffSize-1);
7184 }
7185
7186 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7187 {
7188         /* Dereference any hard linking */
7189         obj = yaffs_GetEquivalentObject(obj);
7190
7191         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7192                 return obj->variant.fileVariant.fileSize;
7193         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7194                 if(!obj->variant.symLinkVariant.alias)
7195                         return 0;
7196                 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7197         } else {
7198                 /* Only a directory should drop through to here */
7199                 return obj->myDev->nDataBytesPerChunk;
7200         }
7201 }
7202
7203 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7204 {
7205         int count = 0;
7206         struct ylist_head *i;
7207
7208         if (!obj->unlinked)
7209                 count++;                /* the object itself */
7210
7211         ylist_for_each(i, &obj->hardLinks)
7212                 count++;                /* add the hard links; */
7213
7214         return count;
7215 }
7216
7217 int yaffs_GetObjectInode(yaffs_Object *obj)
7218 {
7219         obj = yaffs_GetEquivalentObject(obj);
7220
7221         return obj->objectId;
7222 }
7223
7224 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7225 {
7226         obj = yaffs_GetEquivalentObject(obj);
7227
7228         switch (obj->variantType) {
7229         case YAFFS_OBJECT_TYPE_FILE:
7230                 return DT_REG;
7231                 break;
7232         case YAFFS_OBJECT_TYPE_DIRECTORY:
7233                 return DT_DIR;
7234                 break;
7235         case YAFFS_OBJECT_TYPE_SYMLINK:
7236                 return DT_LNK;
7237                 break;
7238         case YAFFS_OBJECT_TYPE_HARDLINK:
7239                 return DT_REG;
7240                 break;
7241         case YAFFS_OBJECT_TYPE_SPECIAL:
7242                 if (S_ISFIFO(obj->yst_mode))
7243                         return DT_FIFO;
7244                 if (S_ISCHR(obj->yst_mode))
7245                         return DT_CHR;
7246                 if (S_ISBLK(obj->yst_mode))
7247                         return DT_BLK;
7248                 if (S_ISSOCK(obj->yst_mode))
7249                         return DT_SOCK;
7250         default:
7251                 return DT_REG;
7252                 break;
7253         }
7254 }
7255
7256 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7257 {
7258         obj = yaffs_GetEquivalentObject(obj);
7259         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7260                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7261         else
7262                 return yaffs_CloneString(_Y(""));
7263 }
7264
7265 #ifndef CONFIG_YAFFS_WINCE
7266
7267 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7268 {
7269         unsigned int valid = attr->ia_valid;
7270
7271         if (valid & ATTR_MODE)
7272                 obj->yst_mode = attr->ia_mode;
7273         if (valid & ATTR_UID)
7274                 obj->yst_uid = attr->ia_uid;
7275         if (valid & ATTR_GID)
7276                 obj->yst_gid = attr->ia_gid;
7277
7278         if (valid & ATTR_ATIME)
7279                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7280         if (valid & ATTR_CTIME)
7281                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7282         if (valid & ATTR_MTIME)
7283                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7284
7285         if (valid & ATTR_SIZE)
7286                 yaffs_ResizeFile(obj, attr->ia_size);
7287
7288         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7289
7290         return YAFFS_OK;
7291
7292 }
7293 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7294 {
7295         unsigned int valid = 0;
7296
7297         attr->ia_mode = obj->yst_mode;
7298         valid |= ATTR_MODE;
7299         attr->ia_uid = obj->yst_uid;
7300         valid |= ATTR_UID;
7301         attr->ia_gid = obj->yst_gid;
7302         valid |= ATTR_GID;
7303
7304         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7305         valid |= ATTR_ATIME;
7306         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7307         valid |= ATTR_CTIME;
7308         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7309         valid |= ATTR_MTIME;
7310
7311         attr->ia_size = yaffs_GetFileSize(obj);
7312         valid |= ATTR_SIZE;
7313
7314         attr->ia_valid = valid;
7315
7316         return YAFFS_OK;
7317 }
7318
7319 #endif
7320
7321 #if 0
7322 int yaffs_DumpObject(yaffs_Object *obj)
7323 {
7324         YCHAR name[257];
7325
7326         yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7327
7328         T(YAFFS_TRACE_ALWAYS,
7329           (TSTR
7330            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7331             " chunk %d type %d size %d\n"
7332             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7333            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7334            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7335
7336         return YAFFS_OK;
7337 }
7338 #endif
7339
7340 /*---------------------------- Initialisation code -------------------------------------- */
7341
7342 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7343 {
7344
7345         /* Common functions, gotta have */
7346         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7347                 return 0;
7348
7349 #ifdef CONFIG_YAFFS_YAFFS2
7350
7351         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7352         if (dev->writeChunkWithTagsToNAND &&
7353             dev->readChunkWithTagsFromNAND &&
7354             !dev->writeChunkToNAND &&
7355             !dev->readChunkFromNAND &&
7356             dev->markNANDBlockBad && dev->queryNANDBlock)
7357                 return 1;
7358 #endif
7359
7360         /* Can use the "spare" style interface for yaffs1 */
7361         if (!dev->isYaffs2 &&
7362             !dev->writeChunkWithTagsToNAND &&
7363             !dev->readChunkWithTagsFromNAND &&
7364             dev->writeChunkToNAND &&
7365             dev->readChunkFromNAND &&
7366             !dev->markNANDBlockBad && !dev->queryNANDBlock)
7367                 return 1;
7368
7369         return 0;               /* bad */
7370 }
7371
7372
7373 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7374 {
7375         /* Initialise the unlinked, deleted, root and lost and found directories */
7376
7377         dev->lostNFoundDir = dev->rootDir =  NULL;
7378         dev->unlinkedDir = dev->deletedDir = NULL;
7379
7380         dev->unlinkedDir =
7381             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7382
7383         dev->deletedDir =
7384             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7385
7386         dev->rootDir =
7387             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7388                                       YAFFS_ROOT_MODE | S_IFDIR);
7389         dev->lostNFoundDir =
7390             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7391                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7392
7393         if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7394                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7395                 return YAFFS_OK;
7396         }
7397
7398         return YAFFS_FAIL;
7399 }
7400
7401 int yaffs_GutsInitialise(yaffs_Device *dev)
7402 {
7403         int init_failed = 0;
7404         unsigned x;
7405         int bits;
7406
7407         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7408
7409         /* Check stuff that must be set */
7410
7411         if (!dev) {
7412                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7413                 return YAFFS_FAIL;
7414         }
7415
7416         dev->internalStartBlock = dev->startBlock;
7417         dev->internalEndBlock = dev->endBlock;
7418         dev->blockOffset = 0;
7419         dev->chunkOffset = 0;
7420         dev->nFreeChunks = 0;
7421
7422         dev->gcBlock = -1;
7423
7424         if (dev->startBlock == 0) {
7425                 dev->internalStartBlock = dev->startBlock + 1;
7426                 dev->internalEndBlock = dev->endBlock + 1;
7427                 dev->blockOffset = 1;
7428                 dev->chunkOffset = dev->nChunksPerBlock;
7429         }
7430
7431         /* Check geometry parameters. */
7432
7433         if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7434             (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7435             (dev->inbandTags && !dev->isYaffs2) ||
7436              dev->nChunksPerBlock < 2 ||
7437              dev->nReservedBlocks < 2 ||
7438              dev->internalStartBlock <= 0 ||
7439              dev->internalEndBlock <= 0 ||
7440              dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) {   /* otherwise it is too small */
7441                 T(YAFFS_TRACE_ALWAYS,
7442                   (TSTR
7443                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7444                     TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7445                 return YAFFS_FAIL;
7446         }
7447
7448         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7449                 T(YAFFS_TRACE_ALWAYS,
7450                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7451                 return YAFFS_FAIL;
7452         }
7453
7454         /* Sort out space for inband tags, if required */
7455         if (dev->inbandTags)
7456                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7457         else
7458                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7459
7460         /* Got the right mix of functions? */
7461         if (!yaffs_CheckDevFunctions(dev)) {
7462                 /* Function missing */
7463                 T(YAFFS_TRACE_ALWAYS,
7464                   (TSTR
7465                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7466
7467                 return YAFFS_FAIL;
7468         }
7469
7470         /* This is really a compilation check. */
7471         if (!yaffs_CheckStructures()) {
7472                 T(YAFFS_TRACE_ALWAYS,
7473                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7474                 return YAFFS_FAIL;
7475         }
7476
7477         if (dev->isMounted) {
7478                 T(YAFFS_TRACE_ALWAYS,
7479                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
7480                 return YAFFS_FAIL;
7481         }
7482
7483         /* Finished with most checks. One or two more checks happen later on too. */
7484
7485         dev->isMounted = 1;
7486
7487         /* OK now calculate a few things for the device */
7488
7489         /*
7490          *  Calculate all the chunk size manipulation numbers:
7491          */
7492         x = dev->nDataBytesPerChunk;
7493         /* We always use dev->chunkShift and dev->chunkDiv */
7494         dev->chunkShift = Shifts(x);
7495         x >>= dev->chunkShift;
7496         dev->chunkDiv = x;
7497         /* We only use chunk mask if chunkDiv is 1 */
7498         dev->chunkMask = (1<<dev->chunkShift) - 1;
7499
7500         /*
7501          * Calculate chunkGroupBits.
7502          * We need to find the next power of 2 > than internalEndBlock
7503          */
7504
7505         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7506
7507         bits = ShiftsGE(x);
7508
7509         /* Set up tnode width if wide tnodes are enabled. */
7510         if (!dev->wideTnodesDisabled) {
7511                 /* bits must be even so that we end up with 32-bit words */
7512                 if (bits & 1)
7513                         bits++;
7514                 if (bits < 16)
7515                         dev->tnodeWidth = 16;
7516                 else
7517                         dev->tnodeWidth = bits;
7518         } else
7519                 dev->tnodeWidth = 16;
7520
7521         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7522
7523         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7524          * so if the bitwidth of the
7525          * chunk range we're using is greater than 16 we need
7526          * to figure out chunk shift and chunkGroupSize
7527          */
7528
7529         if (bits <= dev->tnodeWidth)
7530                 dev->chunkGroupBits = 0;
7531         else
7532                 dev->chunkGroupBits = bits - dev->tnodeWidth;
7533
7534
7535         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7536
7537         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7538                 /* We have a problem because the soft delete won't work if
7539                  * the chunk group size > chunks per block.
7540                  * This can be remedied by using larger "virtual blocks".
7541                  */
7542                 T(YAFFS_TRACE_ALWAYS,
7543                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7544
7545                 return YAFFS_FAIL;
7546         }
7547
7548         /* OK, we've finished verifying the device, lets continue with initialisation */
7549
7550         /* More device initialisation */
7551         dev->garbageCollections = 0;
7552         dev->passiveGarbageCollections = 0;
7553         dev->currentDirtyChecker = 0;
7554         dev->bufferedBlock = -1;
7555         dev->doingBufferedBlockRewrite = 0;
7556         dev->nDeletedFiles = 0;
7557         dev->nBackgroundDeletions = 0;
7558         dev->nUnlinkedFiles = 0;
7559         dev->eccFixed = 0;
7560         dev->eccUnfixed = 0;
7561         dev->tagsEccFixed = 0;
7562         dev->tagsEccUnfixed = 0;
7563         dev->nErasureFailures = 0;
7564         dev->nErasedBlocks = 0;
7565         dev->isDoingGC = 0;
7566         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7567
7568         /* Initialise temporary buffers and caches. */
7569         if (!yaffs_InitialiseTempBuffers(dev))
7570                 init_failed = 1;
7571
7572         dev->srCache = NULL;
7573         dev->gcCleanupList = NULL;
7574
7575
7576         if (!init_failed &&
7577             dev->nShortOpCaches > 0) {
7578                 int i;
7579                 void *buf;
7580                 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7581
7582                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7583                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7584
7585                 dev->srCache =  YMALLOC(srCacheBytes);
7586
7587                 buf = (__u8 *) dev->srCache;
7588
7589                 if (dev->srCache)
7590                         memset(dev->srCache, 0, srCacheBytes);
7591
7592                 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7593                         dev->srCache[i].object = NULL;
7594                         dev->srCache[i].lastUse = 0;
7595                         dev->srCache[i].dirty = 0;
7596                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7597                 }
7598                 if (!buf)
7599                         init_failed = 1;
7600
7601                 dev->srLastUse = 0;
7602         }
7603
7604         dev->cacheHits = 0;
7605
7606         if (!init_failed) {
7607                 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7608                 if (!dev->gcCleanupList)
7609                         init_failed = 1;
7610         }
7611
7612         if (dev->isYaffs2)
7613                 dev->useHeaderFileSize = 1;
7614
7615         if (!init_failed && !yaffs_InitialiseBlocks(dev))
7616                 init_failed = 1;
7617
7618         yaffs_InitialiseTnodes(dev);
7619         yaffs_InitialiseObjects(dev);
7620
7621         if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7622                 init_failed = 1;
7623
7624
7625         if (!init_failed) {
7626                 /* Now scan the flash. */
7627                 if (dev->isYaffs2) {
7628                         if (yaffs_CheckpointRestore(dev)) {
7629                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7630                                 T(YAFFS_TRACE_ALWAYS,
7631                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7632                         } else {
7633
7634                                 /* Clean up the mess caused by an aborted checkpoint load
7635                                  * and scan backwards.
7636                                  */
7637                                 yaffs_DeinitialiseBlocks(dev);
7638                                 yaffs_DeinitialiseTnodes(dev);
7639                                 yaffs_DeinitialiseObjects(dev);
7640
7641
7642                                 dev->nErasedBlocks = 0;
7643                                 dev->nFreeChunks = 0;
7644                                 dev->allocationBlock = -1;
7645                                 dev->allocationPage = -1;
7646                                 dev->nDeletedFiles = 0;
7647                                 dev->nUnlinkedFiles = 0;
7648                                 dev->nBackgroundDeletions = 0;
7649                                 dev->oldestDirtySequence = 0;
7650
7651                                 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7652                                         init_failed = 1;
7653
7654                                 yaffs_InitialiseTnodes(dev);
7655                                 yaffs_InitialiseObjects(dev);
7656
7657                                 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7658                                         init_failed = 1;
7659
7660                                 if (!init_failed && !yaffs_ScanBackwards(dev))
7661                                         init_failed = 1;
7662                         }
7663                 } else if (!yaffs_Scan(dev))
7664                                 init_failed = 1;
7665
7666                 yaffs_StripDeletedObjects(dev);
7667                 yaffs_FixHangingObjects(dev);
7668                 if(dev->emptyLostAndFound)
7669                         yaffs_EmptyLostAndFound(dev);
7670         }
7671
7672         if (init_failed) {
7673                 /* Clean up the mess */
7674                 T(YAFFS_TRACE_TRACING,
7675                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7676
7677                 yaffs_Deinitialise(dev);
7678                 return YAFFS_FAIL;
7679         }
7680
7681         /* Zero out stats */
7682         dev->nPageReads = 0;
7683         dev->nPageWrites = 0;
7684         dev->nBlockErasures = 0;
7685         dev->nGCCopies = 0;
7686         dev->nRetriedWrites = 0;
7687
7688         dev->nRetiredBlocks = 0;
7689
7690         yaffs_VerifyFreeChunks(dev);
7691         yaffs_VerifyBlocks(dev);
7692
7693         /* Clean up any aborted checkpoint data */
7694         if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7695                 yaffs_InvalidateCheckpoint(dev);
7696
7697         T(YAFFS_TRACE_TRACING,
7698           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7699         return YAFFS_OK;
7700
7701 }
7702
7703 void yaffs_Deinitialise(yaffs_Device *dev)
7704 {
7705         if (dev->isMounted) {
7706                 int i;
7707
7708                 yaffs_DeinitialiseBlocks(dev);
7709                 yaffs_DeinitialiseTnodes(dev);
7710                 yaffs_DeinitialiseObjects(dev);
7711                 if (dev->nShortOpCaches > 0 &&
7712                     dev->srCache) {
7713
7714                         for (i = 0; i < dev->nShortOpCaches; i++) {
7715                                 if (dev->srCache[i].data)
7716                                         YFREE(dev->srCache[i].data);
7717                                 dev->srCache[i].data = NULL;
7718                         }
7719
7720                         YFREE(dev->srCache);
7721                         dev->srCache = NULL;
7722                 }
7723
7724                 YFREE(dev->gcCleanupList);
7725
7726                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7727                         YFREE(dev->tempBuffer[i].buffer);
7728
7729                 dev->isMounted = 0;
7730
7731                 if (dev->deinitialiseNAND)
7732                         dev->deinitialiseNAND(dev);
7733         }
7734 }
7735
7736 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7737 {
7738         int nFree;
7739         int b;
7740
7741         yaffs_BlockInfo *blk;
7742
7743         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7744                         b++) {
7745                 blk = yaffs_GetBlockInfo(dev, b);
7746
7747                 switch (blk->blockState) {
7748                 case YAFFS_BLOCK_STATE_EMPTY:
7749                 case YAFFS_BLOCK_STATE_ALLOCATING:
7750                 case YAFFS_BLOCK_STATE_COLLECTING:
7751                 case YAFFS_BLOCK_STATE_FULL:
7752                         nFree +=
7753                             (dev->nChunksPerBlock - blk->pagesInUse +
7754                              blk->softDeletions);
7755                         break;
7756                 default:
7757                         break;
7758                 }
7759         }
7760
7761         return nFree;
7762 }
7763
7764 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7765 {
7766         /* This is what we report to the outside world */
7767
7768         int nFree;
7769         int nDirtyCacheChunks;
7770         int blocksForCheckpoint;
7771         int i;
7772
7773 #if 1
7774         nFree = dev->nFreeChunks;
7775 #else
7776         nFree = yaffs_CountFreeChunks(dev);
7777 #endif
7778
7779         nFree += dev->nDeletedFiles;
7780
7781         /* Now count the number of dirty chunks in the cache and subtract those */
7782
7783         for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7784                 if (dev->srCache[i].dirty)
7785                         nDirtyCacheChunks++;
7786         }
7787
7788         nFree -= nDirtyCacheChunks;
7789
7790         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7791
7792         /* Now we figure out how much to reserve for the checkpoint and report that... */
7793         blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7794         if (blocksForCheckpoint < 0)
7795                 blocksForCheckpoint = 0;
7796
7797         nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7798
7799         if (nFree < 0)
7800                 nFree = 0;
7801
7802         return nFree;
7803
7804 }
7805
7806 static int yaffs_freeVerificationFailures;
7807
7808 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7809 {
7810         int counted;
7811         int difference;
7812
7813         if (yaffs_SkipVerification(dev))
7814                 return;
7815
7816         counted = yaffs_CountFreeChunks(dev);
7817
7818         difference = dev->nFreeChunks - counted;
7819
7820         if (difference) {
7821                 T(YAFFS_TRACE_ALWAYS,
7822                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7823                    dev->nFreeChunks, counted, difference));
7824                 yaffs_freeVerificationFailures++;
7825         }
7826 }
7827
7828 /*---------------------------------------- YAFFS test code ----------------------*/
7829
7830 #define yaffs_CheckStruct(structure, syze, name) \
7831         do { \
7832                 if (sizeof(structure) != syze) { \
7833                         T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7834                                 name, syze, (int) sizeof(structure))); \
7835                         return YAFFS_FAIL; \
7836                 } \
7837         } while (0)
7838
7839 static int yaffs_CheckStructures(void)
7840 {
7841 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7842 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7843 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7844 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7845 /*      yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
7846 #endif
7847 #ifndef CONFIG_YAFFS_WINCE
7848         yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
7849 #endif
7850         return YAFFS_OK;
7851 }