Dynamically update the oldest dirty sequence number so that it does not have to be...
[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.114 2010-03-07 22:07:03 charles Exp $";
16
17 #include "yportenv.h"
18 #include "yaffs_trace.h"
19
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
24
25 #include "yaffs_tagscompat.h"
26 #ifndef CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
28 #endif
29 #include "yaffs_nand.h"
30
31 #include "yaffs_checkptrw.h"
32
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
35
36
37 #define YAFFS_PASSIVE_GC_CHUNKS 2
38
39 #include "yaffs_ecc.h"
40
41
42 /* Robustification (if it ever comes about...) */
43 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
44 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
45                 int erasedOk);
46 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
47                                 const __u8 *data,
48                                 const yaffs_ExtendedTags *tags);
49 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
50                                 const yaffs_ExtendedTags *tags);
51
52 /* Other local prototypes */
53 static void yaffs_UpdateParent(yaffs_Object *obj);
54 static int yaffs_UnlinkObject(yaffs_Object *obj);
55 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
56
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
58
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
60                                         const __u8 *buffer,
61                                         yaffs_ExtendedTags *tags,
62                                         int useReserve);
63 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
64                                 int chunkInNAND, int inScan);
65
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
67                                         yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
69                                 yaffs_Object *obj);
70 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
71                                 int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
75                         int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
77
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
79
80
81 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
82                                 int chunkInNAND);
83
84 static int yaffs_UnlinkWorker(yaffs_Object *obj);
85
86 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
87                         int chunkInObject);
88
89 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
90                                 yaffs_BlockInfo **blockUsedPtr);
91
92 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
93
94 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
95
96 static void yaffs_VerifyDirectory(yaffs_Object *directory);
97 #ifdef YAFFS_PARANOID
98 static int yaffs_CheckFileSanity(yaffs_Object *in);
99 #else
100 #define yaffs_CheckFileSanity(in)
101 #endif
102
103 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
104 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
105
106 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
107
108 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
109                                 yaffs_ExtendedTags *tags);
110
111 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
112                 unsigned pos);
113 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
114                                         yaffs_FileStructure *fStruct,
115                                         __u32 chunkId);
116
117 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
118 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
119                                         int chunkInNAND,
120                                         const __u8 *data,
121                                         yaffs_ExtendedTags *tags);
122
123 /* Function to calculate chunk and offset */
124
125 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
126                 __u32 *offsetOut)
127 {
128         int chunk;
129         __u32 offset;
130
131         chunk  = (__u32)(addr >> dev->chunkShift);
132
133         if (dev->chunkDiv == 1) {
134                 /* easy power of 2 case */
135                 offset = (__u32)(addr & dev->chunkMask);
136         } else {
137                 /* Non power-of-2 case */
138
139                 loff_t chunkBase;
140
141                 chunk /= dev->chunkDiv;
142
143                 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144                 offset = (__u32)(addr - chunkBase);
145         }
146
147         *chunkOut = chunk;
148         *offsetOut = offset;
149 }
150
151 /* Function to return the number of shifts for a power of 2 greater than or
152  * equal to the given number
153  * Note we don't try to cater for all possible numbers and this does not have to
154  * be hellishly efficient.
155  */
156
157 static __u32 ShiftsGE(__u32 x)
158 {
159         int extraBits;
160         int nShifts;
161
162         nShifts = extraBits = 0;
163
164         while (x > 1) {
165                 if (x & 1)
166                         extraBits++;
167                 x >>= 1;
168                 nShifts++;
169         }
170
171         if (extraBits)
172                 nShifts++;
173
174         return nShifts;
175 }
176
177 /* Function to return the number of shifts to get a 1 in bit 0
178  */
179
180 static __u32 Shifts(__u32 x)
181 {
182         int nShifts;
183
184         nShifts =  0;
185
186         if (!x)
187                 return 0;
188
189         while (!(x&1)) {
190                 x >>= 1;
191                 nShifts++;
192         }
193
194         return nShifts;
195 }
196
197
198
199 /*
200  * Temporary buffer manipulations.
201  */
202
203 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
204 {
205         int i;
206         __u8 *buf = (__u8 *)1;
207
208         memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
209
210         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
211                 dev->tempBuffer[i].line = 0;    /* not in use */
212                 dev->tempBuffer[i].buffer = buf =
213                     YMALLOC_DMA(dev->param.totalBytesPerChunk);
214         }
215
216         return buf ? YAFFS_OK : YAFFS_FAIL;
217 }
218
219 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
220 {
221         int i, j;
222
223         dev->tempInUse++;
224         if (dev->tempInUse > dev->maxTemp)
225                 dev->maxTemp = dev->tempInUse;
226
227         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
228                 if (dev->tempBuffer[i].line == 0) {
229                         dev->tempBuffer[i].line = lineNo;
230                         if ((i + 1) > dev->maxTemp) {
231                                 dev->maxTemp = i + 1;
232                                 for (j = 0; j <= i; j++)
233                                         dev->tempBuffer[j].maxLine =
234                                             dev->tempBuffer[j].line;
235                         }
236
237                         return dev->tempBuffer[i].buffer;
238                 }
239         }
240
241         T(YAFFS_TRACE_BUFFERS,
242           (TSTR("Out of temp buffers at line %d, other held by lines:"),
243            lineNo));
244         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
245                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
246
247         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
248
249         /*
250          * If we got here then we have to allocate an unmanaged one
251          * This is not good.
252          */
253
254         dev->unmanagedTempAllocations++;
255         return YMALLOC(dev->nDataBytesPerChunk);
256
257 }
258
259 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
260                                     int lineNo)
261 {
262         int i;
263
264         dev->tempInUse--;
265
266         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
267                 if (dev->tempBuffer[i].buffer == buffer) {
268                         dev->tempBuffer[i].line = 0;
269                         return;
270                 }
271         }
272
273         if (buffer) {
274                 /* assume it is an unmanaged one. */
275                 T(YAFFS_TRACE_BUFFERS,
276                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
277                    lineNo));
278                 YFREE(buffer);
279                 dev->unmanagedTempDeallocations++;
280         }
281
282 }
283
284 /*
285  * Determine if we have a managed buffer.
286  */
287 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
288 {
289         int i;
290
291         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
292                 if (dev->tempBuffer[i].buffer == buffer)
293                         return 1;
294         }
295
296         for (i = 0; i < dev->param.nShortOpCaches; i++) {
297                 if (dev->srCache[i].data == buffer)
298                         return 1;
299         }
300
301         if (buffer == dev->checkpointBuffer)
302                 return 1;
303
304         T(YAFFS_TRACE_ALWAYS,
305                 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
306         return 0;
307 }
308
309
310
311 /*
312  * Chunk bitmap manipulations
313  */
314
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
316 {
317         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
318                 T(YAFFS_TRACE_ERROR,
319                         (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
320                         blk));
321                 YBUG();
322         }
323         return dev->chunkBits +
324                 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
325 }
326
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
328 {
329         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330                         chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
331                 T(YAFFS_TRACE_ERROR,
332                 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
333                         blk, chunk));
334                 YBUG();
335         }
336 }
337
338 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
339 {
340         __u8 *blkBits = yaffs_BlockBits(dev, blk);
341
342         memset(blkBits, 0, dev->chunkBitmapStride);
343 }
344
345 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
346 {
347         __u8 *blkBits = yaffs_BlockBits(dev, blk);
348
349         yaffs_VerifyChunkBitId(dev, blk, chunk);
350
351         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
352 }
353
354 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
355 {
356         __u8 *blkBits = yaffs_BlockBits(dev, blk);
357
358         yaffs_VerifyChunkBitId(dev, blk, chunk);
359
360         blkBits[chunk / 8] |= (1 << (chunk & 7));
361 }
362
363 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
364 {
365         __u8 *blkBits = yaffs_BlockBits(dev, blk);
366         yaffs_VerifyChunkBitId(dev, blk, chunk);
367
368         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
369 }
370
371 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
372 {
373         __u8 *blkBits = yaffs_BlockBits(dev, blk);
374         int i;
375         for (i = 0; i < dev->chunkBitmapStride; i++) {
376                 if (*blkBits)
377                         return 1;
378                 blkBits++;
379         }
380         return 0;
381 }
382
383 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
384 {
385         __u8 *blkBits = yaffs_BlockBits(dev, blk);
386         int i;
387         int n = 0;
388         for (i = 0; i < dev->chunkBitmapStride; i++) {
389                 __u8 x = *blkBits;
390                 while (x) {
391                         if (x & 1)
392                                 n++;
393                         x >>= 1;
394                 }
395
396                 blkBits++;
397         }
398         return n;
399 }
400
401 /*
402  * Verification code
403  */
404
405 static int yaffs_SkipVerification(yaffs_Device *dev)
406 {
407         dev=dev;
408         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
409 }
410
411 static int yaffs_SkipFullVerification(yaffs_Device *dev)
412 {
413         dev=dev;
414         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
415 }
416
417 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
418 {
419         dev=dev;
420         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
421 }
422
423 static const char *blockStateName[] = {
424 "Unknown",
425 "Needs scanning",
426 "Scanning",
427 "Empty",
428 "Allocating",
429 "Full",
430 "Dirty",
431 "Checkpoint",
432 "Collecting",
433 "Dead"
434 };
435
436 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
437 {
438         int actuallyUsed;
439         int inUse;
440
441         if (yaffs_SkipVerification(dev))
442                 return;
443
444         /* Report illegal runtime states */
445         if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
446                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
447
448         switch (bi->blockState) {
449         case YAFFS_BLOCK_STATE_UNKNOWN:
450         case YAFFS_BLOCK_STATE_SCANNING:
451         case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
452                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
453                 n, blockStateName[bi->blockState]));
454         }
455
456         /* Check pages in use and soft deletions are legal */
457
458         actuallyUsed = bi->pagesInUse - bi->softDeletions;
459
460         if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
461            bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
462            actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
463                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
464                 n, bi->pagesInUse, bi->softDeletions));
465
466
467         /* Check chunk bitmap legal */
468         inUse = yaffs_CountChunkBits(dev, n);
469         if (inUse != bi->pagesInUse)
470                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
471                         n, bi->pagesInUse, inUse));
472
473         /* Check that the sequence number is valid.
474          * Ten million is legal, but is very unlikely
475          */
476         if (dev->param.isYaffs2 &&
477            (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
478            (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
479                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
480                 n, bi->sequenceNumber));
481 }
482
483 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
484                 int n)
485 {
486         yaffs_VerifyBlock(dev, bi, n);
487
488         /* After collection the block should be in the erased state */
489         /* This will need to change if we do partial gc */
490
491         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
492                         bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
493                 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
494                         n, bi->blockState));
495         }
496 }
497
498 static void yaffs_VerifyBlocks(yaffs_Device *dev)
499 {
500         int i;
501         int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
502         int nIllegalBlockStates = 0;
503
504         if (yaffs_SkipVerification(dev))
505                 return;
506
507         memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
508
509         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
510                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
511                 yaffs_VerifyBlock(dev, bi, i);
512
513                 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
514                         nBlocksPerState[bi->blockState]++;
515                 else
516                         nIllegalBlockStates++;
517         }
518
519         T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
520         T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
521
522         T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
523         if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524                 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
525
526         for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527                 T(YAFFS_TRACE_VERIFY,
528                   (TSTR("%s %d blocks"TENDSTR),
529                   blockStateName[i], nBlocksPerState[i]));
530
531         if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532                 T(YAFFS_TRACE_VERIFY,
533                  (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534                  dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
535
536         if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537                 T(YAFFS_TRACE_VERIFY,
538                  (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539                  dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
540
541         if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542                 T(YAFFS_TRACE_VERIFY,
543                  (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544                  nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
545
546         T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
547
548 }
549
550 /*
551  * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552  * case those tests will not be performed.
553  */
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
555 {
556         if (obj && yaffs_SkipVerification(obj->myDev))
557                 return;
558
559         if (!(tags && obj && oh)) {
560                 T(YAFFS_TRACE_VERIFY,
561                                 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
562                                 tags, obj, oh));
563                 return;
564         }
565
566         if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567                         oh->type > YAFFS_OBJECT_TYPE_MAX)
568                 T(YAFFS_TRACE_VERIFY,
569                         (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570                         tags->objectId, oh->type));
571
572         if (tags->objectId != obj->objectId)
573                 T(YAFFS_TRACE_VERIFY,
574                         (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575                         tags->objectId, obj->objectId));
576
577
578         /*
579          * Check that the object's parent ids match if parentCheck requested.
580          *
581          * Tests do not apply to the root object.
582          */
583
584         if (parentCheck && tags->objectId > 1 && !obj->parent)
585                 T(YAFFS_TRACE_VERIFY,
586                         (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587                         tags->objectId, oh->parentObjectId));
588
589         if (parentCheck && obj->parent &&
590                         oh->parentObjectId != obj->parent->objectId &&
591                         (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
592                         obj->parent->objectId != YAFFS_OBJECTID_DELETED))
593                 T(YAFFS_TRACE_VERIFY,
594                         (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
595                         tags->objectId, oh->parentObjectId, obj->parent->objectId));
596
597         if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
598                 T(YAFFS_TRACE_VERIFY,
599                         (TSTR("Obj %d header name is NULL"TENDSTR),
600                         obj->objectId));
601
602         if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
603                 T(YAFFS_TRACE_VERIFY,
604                         (TSTR("Obj %d header name is 0xFF"TENDSTR),
605                         obj->objectId));
606 }
607
608
609
610 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
611                                         __u32 level, int chunkOffset)
612 {
613         int i;
614         yaffs_Device *dev = obj->myDev;
615         int ok = 1;
616
617         if (tn) {
618                 if (level > 0) {
619
620                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
621                                 if (tn->internal[i]) {
622                                         ok = yaffs_VerifyTnodeWorker(obj,
623                                                         tn->internal[i],
624                                                         level - 1,
625                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
626                                 }
627                         }
628                 } else if (level == 0) {
629                         yaffs_ExtendedTags tags;
630                         __u32 objectId = obj->objectId;
631
632                         chunkOffset <<=  YAFFS_TNODES_LEVEL0_BITS;
633
634                         for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
635                                 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
636
637                                 if (theChunk > 0) {
638                                         /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
639                                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
640                                         if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
641                                                 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
642                                                         objectId, chunkOffset, theChunk,
643                                                         tags.objectId, tags.chunkId));
644                                         }
645                                 }
646                                 chunkOffset++;
647                         }
648                 }
649         }
650
651         return ok;
652
653 }
654
655
656 static void yaffs_VerifyFile(yaffs_Object *obj)
657 {
658         int requiredTallness;
659         int actualTallness;
660         __u32 lastChunk;
661         __u32 x;
662         __u32 i;
663         yaffs_Device *dev;
664         yaffs_ExtendedTags tags;
665         yaffs_Tnode *tn;
666         __u32 objectId;
667
668         if (!obj)
669                 return;
670
671         if (yaffs_SkipVerification(obj->myDev))
672                 return;
673
674         dev = obj->myDev;
675         objectId = obj->objectId;
676
677         /* Check file size is consistent with tnode depth */
678         lastChunk =  obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679         x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680         requiredTallness = 0;
681         while (x > 0) {
682                 x >>= YAFFS_TNODES_INTERNAL_BITS;
683                 requiredTallness++;
684         }
685
686         actualTallness = obj->variant.fileVariant.topLevel;
687
688         /* Check that the chunks in the tnode tree are all correct.
689          * We do this by scanning through the tnode tree and
690          * checking the tags for every chunk match.
691          */
692
693         if (yaffs_SkipNANDVerification(dev))
694                 return;
695
696         for (i = 1; i <= lastChunk; i++) {
697                 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
698
699                 if (tn) {
700                         __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
701                         if (theChunk > 0) {
702                                 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
703                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
704                                 if (tags.objectId != objectId || tags.chunkId != i) {
705                                         T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
706                                                 objectId, i, theChunk,
707                                                 tags.objectId, tags.chunkId));
708                                 }
709                         }
710                 }
711         }
712 }
713
714
715 static void yaffs_VerifyHardLink(yaffs_Object *obj)
716 {
717         if (obj && yaffs_SkipVerification(obj->myDev))
718                 return;
719
720         /* Verify sane equivalent object */
721 }
722
723 static void yaffs_VerifySymlink(yaffs_Object *obj)
724 {
725         if (obj && yaffs_SkipVerification(obj->myDev))
726                 return;
727
728         /* Verify symlink string */
729 }
730
731 static void yaffs_VerifySpecial(yaffs_Object *obj)
732 {
733         if (obj && yaffs_SkipVerification(obj->myDev))
734                 return;
735 }
736
737 static void yaffs_VerifyObject(yaffs_Object *obj)
738 {
739         yaffs_Device *dev;
740
741         __u32 chunkMin;
742         __u32 chunkMax;
743
744         __u32 chunkIdOk;
745         __u32 chunkInRange;
746         __u32 chunkShouldNotBeDeleted;
747         __u32 chunkValid;
748
749         if (!obj)
750                 return;
751
752         if (obj->beingCreated)
753                 return;
754
755         dev = obj->myDev;
756
757         if (yaffs_SkipVerification(dev))
758                 return;
759
760         /* Check sane object header chunk */
761
762         chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
763         chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
764
765         chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
766         chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
767         chunkValid = chunkInRange &&
768                         yaffs_CheckChunkBit(dev,
769                                         obj->hdrChunk / dev->param.nChunksPerBlock,
770                                         obj->hdrChunk % dev->param.nChunksPerBlock);
771         chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
772
773         if (!obj->fake &&
774                         (!chunkIdOk || chunkShouldNotBeDeleted)) {
775                 T(YAFFS_TRACE_VERIFY,
776                         (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
777                         obj->objectId, obj->hdrChunk,
778                         chunkIdOk ? "" : ",out of range",
779                         chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
780         }
781
782         if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
783                 yaffs_ExtendedTags tags;
784                 yaffs_ObjectHeader *oh;
785                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
786
787                 oh = (yaffs_ObjectHeader *)buffer;
788
789                 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
790                                 &tags);
791
792                 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
793
794                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
795         }
796
797         /* Verify it has a parent */
798         if (obj && !obj->fake &&
799                         (!obj->parent || obj->parent->myDev != dev)) {
800                 T(YAFFS_TRACE_VERIFY,
801                         (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
802                         obj->objectId, obj->parent));
803         }
804
805         /* Verify parent is a directory */
806         if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
807                 T(YAFFS_TRACE_VERIFY,
808                         (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
809                         obj->objectId, obj->parent->variantType));
810         }
811
812         switch (obj->variantType) {
813         case YAFFS_OBJECT_TYPE_FILE:
814                 yaffs_VerifyFile(obj);
815                 break;
816         case YAFFS_OBJECT_TYPE_SYMLINK:
817                 yaffs_VerifySymlink(obj);
818                 break;
819         case YAFFS_OBJECT_TYPE_DIRECTORY:
820                 yaffs_VerifyDirectory(obj);
821                 break;
822         case YAFFS_OBJECT_TYPE_HARDLINK:
823                 yaffs_VerifyHardLink(obj);
824                 break;
825         case YAFFS_OBJECT_TYPE_SPECIAL:
826                 yaffs_VerifySpecial(obj);
827                 break;
828         case YAFFS_OBJECT_TYPE_UNKNOWN:
829         default:
830                 T(YAFFS_TRACE_VERIFY,
831                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
832                 obj->objectId, obj->variantType));
833                 break;
834         }
835 }
836
837 static void yaffs_VerifyObjects(yaffs_Device *dev)
838 {
839         yaffs_Object *obj;
840         int i;
841         struct ylist_head *lh;
842
843         if (yaffs_SkipVerification(dev))
844                 return;
845
846         /* Iterate through the objects in each hash entry */
847
848         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
849                 ylist_for_each(lh, &dev->objectBucket[i].list) {
850                         if (lh) {
851                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
852                                 yaffs_VerifyObject(obj);
853                         }
854                 }
855         }
856 }
857
858
859 /*
860  *  Simple hash function. Needs to have a reasonable spread
861  */
862
863 static Y_INLINE int yaffs_HashFunction(int n)
864 {
865         n = abs(n);
866         return n % YAFFS_NOBJECT_BUCKETS;
867 }
868
869 /*
870  * Access functions to useful fake objects.
871  * Note that root might have a presence in NAND if permissions are set.
872  */
873
874 yaffs_Object *yaffs_Root(yaffs_Device *dev)
875 {
876         return dev->rootDir;
877 }
878
879 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
880 {
881         return dev->lostNFoundDir;
882 }
883
884
885 /*
886  *  Erased NAND checking functions
887  */
888
889 int yaffs_CheckFF(__u8 *buffer, int nBytes)
890 {
891         /* Horrible, slow implementation */
892         while (nBytes--) {
893                 if (*buffer != 0xFF)
894                         return 0;
895                 buffer++;
896         }
897         return 1;
898 }
899
900 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
901                                 int chunkInNAND)
902 {
903         int retval = YAFFS_OK;
904         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
905         yaffs_ExtendedTags tags;
906         int result;
907
908         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
909
910         if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
911                 retval = YAFFS_FAIL;
912
913         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
914                 T(YAFFS_TRACE_NANDACCESS,
915                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
916                 retval = YAFFS_FAIL;
917         }
918
919         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
920
921         return retval;
922
923 }
924
925
926 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
927                                         int chunkInNAND,
928                                         const __u8 *data,
929                                         yaffs_ExtendedTags *tags)
930 {
931         int retval = YAFFS_OK;
932         yaffs_ExtendedTags tempTags;
933         __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
934         int result;
935         
936         result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
937         if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
938                 tempTags.objectId != tags->objectId ||
939                 tempTags.chunkId  != tags->chunkId ||
940                 tempTags.byteCount != tags->byteCount)
941                 retval = YAFFS_FAIL;
942
943         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
944
945         return retval;
946 }
947
948 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
949                                         const __u8 *data,
950                                         yaffs_ExtendedTags *tags,
951                                         int useReserve)
952 {
953         int attempts = 0;
954         int writeOk = 0;
955         int chunk;
956
957         yaffs_InvalidateCheckpoint(dev);
958
959         do {
960                 yaffs_BlockInfo *bi = 0;
961                 int erasedOk = 0;
962
963                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
964                 if (chunk < 0) {
965                         /* no space */
966                         break;
967                 }
968
969                 /* First check this chunk is erased, if it needs
970                  * checking.  The checking policy (unless forced
971                  * always on) is as follows:
972                  *
973                  * Check the first page we try to write in a block.
974                  * If the check passes then we don't need to check any
975                  * more.        If the check fails, we check again...
976                  * If the block has been erased, we don't need to check.
977                  *
978                  * However, if the block has been prioritised for gc,
979                  * then we think there might be something odd about
980                  * this block and stop using it.
981                  *
982                  * Rationale: We should only ever see chunks that have
983                  * not been erased if there was a partially written
984                  * chunk due to power loss.  This checking policy should
985                  * catch that case with very few checks and thus save a
986                  * lot of checks that are most likely not needed.
987                  *
988                  * Mods to the above
989                  * If an erase check fails or the write fails we skip the 
990                  * rest of the block.
991                  */
992
993                 /* let's give it a try */
994                 attempts++;
995
996 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
997                 bi->skipErasedCheck = 0;
998 #endif
999                 if (!bi->skipErasedCheck) {
1000                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
1001                         if (erasedOk != YAFFS_OK) {
1002                                 T(YAFFS_TRACE_ERROR,
1003                                 (TSTR("**>> yaffs chunk %d was not erased"
1004                                 TENDSTR), chunk));
1005
1006                                 /* If not erased, delete this one,
1007                                  * skip rest of block and
1008                                  * try another chunk */
1009                                  yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1010                                  yaffs_SkipRestOfBlock(dev);
1011                                 continue;
1012                         }
1013                 }
1014
1015                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1016                                 data, tags);
1017
1018                 if(!bi->skipErasedCheck)
1019                         writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1020
1021                 if (writeOk != YAFFS_OK) {
1022                         /* Clean up aborted write, skip to next block and
1023                          * try another chunk */
1024                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1025                         continue;
1026                 }
1027
1028                 bi->skipErasedCheck = 1;
1029
1030                 /* Copy the data into the robustification buffer */
1031                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1032
1033         } while (writeOk != YAFFS_OK &&
1034                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1035
1036         if (!writeOk)
1037                 chunk = -1;
1038
1039         if (attempts > 1) {
1040                 T(YAFFS_TRACE_ERROR,
1041                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1042                         attempts));
1043
1044                 dev->nRetriedWrites += (attempts - 1);
1045         }
1046
1047         return chunk;
1048 }
1049
1050
1051 /*
1052  * Oldest Dirty Sequence Number handling.
1053  */
1054  
1055 /* yaffs_CalcOldestDirtySequence()
1056  * yaffs_FindOldestDirtySequence()
1057  * Calculate the oldest dirty sequence number if we don't know it.
1058  */
1059 static int yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1060 {
1061         int i;
1062         __u32 seq;
1063         yaffs_BlockInfo *b = 0;
1064
1065         
1066         /* Find the oldest dirty sequence number. */
1067         seq = dev->sequenceNumber;
1068         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1069                 b = yaffs_GetBlockInfo(dev, i);
1070                 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1071                     (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1072                     b->sequenceNumber < seq) 
1073                                 seq = b->sequenceNumber;
1074         }
1075         return seq;
1076 }
1077
1078
1079 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1080 {
1081         if(!dev->oldestDirtySequence)
1082                 dev->oldestDirtySequence = 
1083                         yaffs_CalcOldestDirtySequence(dev);
1084
1085 #if 0
1086         if(!yaffs_SkipVerification(dev) &&
1087                 dev->oldestDirtySequence != yaffs_CalcOldestDirtySequence(dev))
1088                 YBUG();
1089
1090 #endif
1091 }
1092
1093 /*
1094  * yaffs_ClearOldestDirtySequence()
1095  * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1096  * becomes invalid). If the value matches the oldest then we clear 
1097  * dev->oldestDirtySequence to force its recomputation.
1098  */
1099 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1100 {
1101
1102         if(!bi || bi->sequenceNumber == dev->oldestDirtySequence)
1103                 dev->oldestDirtySequence = 0;
1104 }
1105
1106 /*
1107  * yaffs_UpdateOldestDirtySequence()
1108  * Update the oldest dirty sequence number whenever we dirty a block.
1109  * Only do this if the oldestDirtySequence is actually being tracked.
1110  */
1111 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1112 {
1113         if(dev->oldestDirtySequence){
1114                 if(dev->oldestDirtySequence > bi->sequenceNumber)
1115                         dev->oldestDirtySequence = bi->sequenceNumber;
1116         }
1117 }
1118  
1119 /*
1120  * Block retiring for handling a broken block.
1121  */
1122
1123 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1124 {
1125         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1126
1127         yaffs_InvalidateCheckpoint(dev);
1128         
1129         yaffs_ClearOldestDirtySequence(dev,bi);
1130
1131         if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1132                 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1133                         T(YAFFS_TRACE_ALWAYS, (TSTR(
1134                                 "yaffs: Failed to mark bad and erase block %d"
1135                                 TENDSTR), blockInNAND));
1136                 } else {
1137                         yaffs_ExtendedTags tags;
1138                         int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1139
1140                         __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1141
1142                         memset(buffer, 0xff, dev->nDataBytesPerChunk);
1143                         yaffs_InitialiseTags(&tags);
1144                         tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1145                         if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1146                                 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1147                                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1148                                         TCONT("write bad block marker to block %d")
1149                                         TENDSTR), blockInNAND));
1150
1151                         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1152                 }
1153         }
1154
1155         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1156         bi->gcPrioritise = 0;
1157         bi->needsRetiring = 0;
1158
1159         dev->nRetiredBlocks++;
1160 }
1161
1162 /*
1163  * Functions for robustisizing TODO
1164  *
1165  */
1166
1167 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1168                                 const __u8 *data,
1169                                 const yaffs_ExtendedTags *tags)
1170 {
1171         dev=dev;
1172         chunkInNAND=chunkInNAND;
1173         data=data;
1174         tags=tags;
1175 }
1176
1177 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1178                                 const yaffs_ExtendedTags *tags)
1179 {
1180         dev=dev;
1181         chunkInNAND=chunkInNAND;
1182         tags=tags;
1183 }
1184
1185 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1186 {
1187         if (!bi->gcPrioritise) {
1188                 bi->gcPrioritise = 1;
1189                 dev->hasPendingPrioritisedGCs = 1;
1190                 bi->chunkErrorStrikes++;
1191
1192                 if (bi->chunkErrorStrikes > 3) {
1193                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1194                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1195
1196                 }
1197         }
1198 }
1199
1200 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1201                 int erasedOk)
1202 {
1203         int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1204         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1205
1206         yaffs_HandleChunkError(dev, bi);
1207
1208         if (erasedOk) {
1209                 /* Was an actual write failure, so mark the block for retirement  */
1210                 bi->needsRetiring = 1;
1211                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1212                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1213         }
1214
1215         /* Delete the chunk */
1216         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1217         yaffs_SkipRestOfBlock(dev);
1218 }
1219
1220
1221 /*---------------- Name handling functions ------------*/
1222
1223 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1224 {
1225         __u16 sum = 0;
1226         __u16 i = 1;
1227
1228         const YUCHAR *bname = (const YUCHAR *) name;
1229         if (bname) {
1230                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1231
1232 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1233                         sum += yaffs_toupper(*bname) * i;
1234 #else
1235                         sum += (*bname) * i;
1236 #endif
1237                         i++;
1238                         bname++;
1239                 }
1240         }
1241         return sum;
1242 }
1243
1244 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1245 {
1246 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1247         memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1248         if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1249                 yaffs_strcpy(obj->shortName, name);
1250         else
1251                 obj->shortName[0] = _Y('\0');
1252 #endif
1253         obj->sum = yaffs_CalcNameSum(name);
1254 }
1255
1256 /*-------------------- TNODES -------------------
1257
1258  * List of spare tnodes
1259  * The list is hooked together using the first pointer
1260  * in the tnode.
1261  */
1262
1263 /* yaffs_CreateTnodes creates a bunch more tnodes and
1264  * adds them to the tnode free list.
1265  * Don't use this function directly
1266  */
1267 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1268 {
1269         int tnodeSize;
1270         /* Calculate the tnode size in bytes for variable width tnode support.
1271          * Must be a multiple of 32-bits  */
1272         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1273
1274         if (tnodeSize < sizeof(yaffs_Tnode))
1275                 tnodeSize = sizeof(yaffs_Tnode);
1276         return tnodeSize;
1277 }
1278
1279 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1280 {
1281         int i;
1282         int tnodeSize = yaffs_CalcTnodeSize(dev);
1283         yaffs_Tnode *newTnodes;
1284         __u8 *mem;
1285         yaffs_Tnode *curr;
1286         yaffs_Tnode *next;
1287         yaffs_TnodeList *tnl;
1288
1289         if (nTnodes < 1)
1290                 return YAFFS_OK;
1291
1292
1293         /* make these things */
1294
1295         newTnodes = YMALLOC(nTnodes * tnodeSize);
1296         mem = (__u8 *)newTnodes;
1297
1298         if (!newTnodes) {
1299                 T(YAFFS_TRACE_ERROR,
1300                         (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1301                 return YAFFS_FAIL;
1302         }
1303
1304         /* Hook them into the free list */
1305 #if 0
1306         for (i = 0; i < nTnodes - 1; i++) {
1307                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1308 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1309                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1310 #endif
1311         }
1312
1313         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1314 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1315         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1316 #endif
1317         dev->freeTnodes = newTnodes;
1318 #else
1319         /* New hookup for wide tnodes */
1320         for (i = 0; i < nTnodes - 1; i++) {
1321                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1322                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1323                 curr->internal[0] = next;
1324         }
1325
1326         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1327         curr->internal[0] = dev->freeTnodes;
1328         dev->freeTnodes = (yaffs_Tnode *)mem;
1329
1330 #endif
1331
1332
1333         dev->nFreeTnodes += nTnodes;
1334         dev->nTnodesCreated += nTnodes;
1335
1336         /* Now add this bunch of tnodes to a list for freeing up.
1337          * NB If we can't add this to the management list it isn't fatal
1338          * but it just means we can't free this bunch of tnodes later.
1339          */
1340
1341         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1342         if (!tnl) {
1343                 T(YAFFS_TRACE_ERROR,
1344                   (TSTR
1345                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1346                    return YAFFS_FAIL;
1347         } else {
1348                 tnl->tnodes = newTnodes;
1349                 tnl->next = dev->allocatedTnodeList;
1350                 dev->allocatedTnodeList = tnl;
1351         }
1352
1353         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1354
1355         return YAFFS_OK;
1356 }
1357
1358 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1359
1360 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1361 {
1362         yaffs_Tnode *tn = NULL;
1363
1364 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1365         tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1366         if(tn)
1367                 dev->nTnodesCreated++;
1368 #else
1369         /* If there are none left make more */
1370         if (!dev->freeTnodes)
1371                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1372
1373         if (dev->freeTnodes) {
1374                 tn = dev->freeTnodes;
1375 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1376                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1377                         /* Hoosterman, this thing looks like it isn't in the list */
1378                         T(YAFFS_TRACE_ALWAYS,
1379                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1380                 }
1381 #endif
1382                 dev->freeTnodes = dev->freeTnodes->internal[0];
1383                 dev->nFreeTnodes--;
1384         }
1385 #endif
1386         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1387
1388         return tn;
1389 }
1390
1391 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1392 {
1393         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1394         int tnodeSize = yaffs_CalcTnodeSize(dev);
1395
1396         if (tn)
1397                 memset(tn, 0, tnodeSize);
1398
1399         return tn;
1400 }
1401
1402 /* FreeTnode frees up a tnode and puts it back on the free list */
1403 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1404 {
1405         if (tn) {
1406 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1407                 YFREE(tn);
1408                 dev->nTnodesCreated--;
1409 #else
1410 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1411                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1412                         /* Hoosterman, this thing looks like it is already in the list */
1413                         T(YAFFS_TRACE_ALWAYS,
1414                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1415                 }
1416                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1417 #endif
1418                 tn->internal[0] = dev->freeTnodes;
1419                 dev->freeTnodes = tn;
1420                 dev->nFreeTnodes++;
1421 #endif
1422         }
1423         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1424 }
1425
1426 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1427 {
1428         /* Free the list of allocated tnodes */
1429         yaffs_TnodeList *tmp;
1430
1431         while (dev->allocatedTnodeList) {
1432                 tmp = dev->allocatedTnodeList->next;
1433
1434                 YFREE(dev->allocatedTnodeList->tnodes);
1435                 YFREE(dev->allocatedTnodeList);
1436                 dev->allocatedTnodeList = tmp;
1437
1438         }
1439
1440         dev->freeTnodes = NULL;
1441         dev->nFreeTnodes = 0;
1442         dev->nTnodesCreated = 0;
1443 }
1444
1445 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1446 {
1447         dev->allocatedTnodeList = NULL;
1448         dev->freeTnodes = NULL;
1449         dev->nFreeTnodes = 0;
1450         dev->nTnodesCreated = 0;
1451 }
1452
1453
1454 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1455                 unsigned val)
1456 {
1457         __u32 *map = (__u32 *)tn;
1458         __u32 bitInMap;
1459         __u32 bitInWord;
1460         __u32 wordInMap;
1461         __u32 mask;
1462
1463         pos &= YAFFS_TNODES_LEVEL0_MASK;
1464         val >>= dev->chunkGroupBits;
1465
1466         bitInMap = pos * dev->tnodeWidth;
1467         wordInMap = bitInMap / 32;
1468         bitInWord = bitInMap & (32 - 1);
1469
1470         mask = dev->tnodeMask << bitInWord;
1471
1472         map[wordInMap] &= ~mask;
1473         map[wordInMap] |= (mask & (val << bitInWord));
1474
1475         if (dev->tnodeWidth > (32 - bitInWord)) {
1476                 bitInWord = (32 - bitInWord);
1477                 wordInMap++;;
1478                 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1479                 map[wordInMap] &= ~mask;
1480                 map[wordInMap] |= (mask & (val >> bitInWord));
1481         }
1482 }
1483
1484 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1485                 unsigned pos)
1486 {
1487         __u32 *map = (__u32 *)tn;
1488         __u32 bitInMap;
1489         __u32 bitInWord;
1490         __u32 wordInMap;
1491         __u32 val;
1492
1493         pos &= YAFFS_TNODES_LEVEL0_MASK;
1494
1495         bitInMap = pos * dev->tnodeWidth;
1496         wordInMap = bitInMap / 32;
1497         bitInWord = bitInMap & (32 - 1);
1498
1499         val = map[wordInMap] >> bitInWord;
1500
1501         if      (dev->tnodeWidth > (32 - bitInWord)) {
1502                 bitInWord = (32 - bitInWord);
1503                 wordInMap++;;
1504                 val |= (map[wordInMap] << bitInWord);
1505         }
1506
1507         val &= dev->tnodeMask;
1508         val <<= dev->chunkGroupBits;
1509
1510         return val;
1511 }
1512
1513 /* ------------------- End of individual tnode manipulation -----------------*/
1514
1515 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1516  * The look up tree is represented by the top tnode and the number of topLevel
1517  * in the tree. 0 means only the level 0 tnode is in the tree.
1518  */
1519
1520 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1521 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1522                                         yaffs_FileStructure *fStruct,
1523                                         __u32 chunkId)
1524 {
1525         yaffs_Tnode *tn = fStruct->top;
1526         __u32 i;
1527         int requiredTallness;
1528         int level = fStruct->topLevel;
1529
1530         dev=dev;
1531
1532         /* Check sane level and chunk Id */
1533         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1534                 return NULL;
1535
1536         if (chunkId > YAFFS_MAX_CHUNK_ID)
1537                 return NULL;
1538
1539         /* First check we're tall enough (ie enough topLevel) */
1540
1541         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1542         requiredTallness = 0;
1543         while (i) {
1544                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1545                 requiredTallness++;
1546         }
1547
1548         if (requiredTallness > fStruct->topLevel)
1549                 return NULL; /* Not tall enough, so we can't find it */
1550
1551         /* Traverse down to level 0 */
1552         while (level > 0 && tn) {
1553                 tn = tn->internal[(chunkId >>
1554                         (YAFFS_TNODES_LEVEL0_BITS +
1555                                 (level - 1) *
1556                                 YAFFS_TNODES_INTERNAL_BITS)) &
1557                         YAFFS_TNODES_INTERNAL_MASK];
1558                 level--;
1559         }
1560
1561         return tn;
1562 }
1563
1564 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1565  * This happens in two steps:
1566  *  1. If the tree isn't tall enough, then make it taller.
1567  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1568  *
1569  * Used when modifying the tree.
1570  *
1571  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1572  *  be plugged into the ttree.
1573  */
1574
1575 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1576                                         yaffs_FileStructure *fStruct,
1577                                         __u32 chunkId,
1578                                         yaffs_Tnode *passedTn)
1579 {
1580         int requiredTallness;
1581         int i;
1582         int l;
1583         yaffs_Tnode *tn;
1584
1585         __u32 x;
1586
1587
1588         /* Check sane level and page Id */
1589         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1590                 return NULL;
1591
1592         if (chunkId > YAFFS_MAX_CHUNK_ID)
1593                 return NULL;
1594
1595         /* First check we're tall enough (ie enough topLevel) */
1596
1597         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1598         requiredTallness = 0;
1599         while (x) {
1600                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1601                 requiredTallness++;
1602         }
1603
1604
1605         if (requiredTallness > fStruct->topLevel) {
1606                 /* Not tall enough, gotta make the tree taller */
1607                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1608
1609                         tn = yaffs_GetTnode(dev);
1610
1611                         if (tn) {
1612                                 tn->internal[0] = fStruct->top;
1613                                 fStruct->top = tn;
1614                                 fStruct->topLevel++;
1615                         } else {
1616                                 T(YAFFS_TRACE_ERROR,
1617                                         (TSTR("yaffs: no more tnodes" TENDSTR)));
1618                                 return NULL;
1619                         }
1620                 }
1621         }
1622
1623         /* Traverse down to level 0, adding anything we need */
1624
1625         l = fStruct->topLevel;
1626         tn = fStruct->top;
1627
1628         if (l > 0) {
1629                 while (l > 0 && tn) {
1630                         x = (chunkId >>
1631                              (YAFFS_TNODES_LEVEL0_BITS +
1632                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1633                             YAFFS_TNODES_INTERNAL_MASK;
1634
1635
1636                         if ((l > 1) && !tn->internal[x]) {
1637                                 /* Add missing non-level-zero tnode */
1638                                 tn->internal[x] = yaffs_GetTnode(dev);
1639                                 if(!tn->internal[x])
1640                                         return NULL;
1641                         } else if (l == 1) {
1642                                 /* Looking from level 1 at level 0 */
1643                                 if (passedTn) {
1644                                         /* If we already have one, then release it.*/
1645                                         if (tn->internal[x])
1646                                                 yaffs_FreeTnode(dev, tn->internal[x]);
1647                                         tn->internal[x] = passedTn;
1648
1649                                 } else if (!tn->internal[x]) {
1650                                         /* Don't have one, none passed in */
1651                                         tn->internal[x] = yaffs_GetTnode(dev);
1652                                         if(!tn->internal[x])
1653                                                 return NULL;
1654                                 }
1655                         }
1656
1657                         tn = tn->internal[x];
1658                         l--;
1659                 }
1660         } else {
1661                 /* top is level 0 */
1662                 if (passedTn) {
1663                         memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1664                         yaffs_FreeTnode(dev, passedTn);
1665                 }
1666         }
1667
1668         return tn;
1669 }
1670
1671 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1672                                 yaffs_ExtendedTags *tags, int objectId,
1673                                 int chunkInInode)
1674 {
1675         int j;
1676
1677         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1678                 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1679                                 theChunk % dev->param.nChunksPerBlock)) {
1680                         
1681                         if(dev->chunkGroupSize == 1)
1682                                 return theChunk;
1683                         else {
1684                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1685                                                                 tags);
1686                                 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1687                                         /* found it; */
1688                                         return theChunk;
1689                                 }
1690                         }
1691                 }
1692                 theChunk++;
1693         }
1694         return -1;
1695 }
1696
1697
1698 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1699  * chunks and tnodes in the file
1700  * Returns 1 if the tree was deleted.
1701  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1702  */
1703
1704 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1705                               int chunkOffset, int *limit)
1706 {
1707         int i;
1708         int chunkInInode;
1709         int theChunk;
1710         yaffs_ExtendedTags tags;
1711         int foundChunk;
1712         yaffs_Device *dev = in->myDev;
1713
1714         int allDone = 1;
1715
1716         if (tn) {
1717                 if (level > 0) {
1718                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1719                              i--) {
1720                                 if (tn->internal[i]) {
1721                                         if (limit && (*limit) < 0) {
1722                                                 allDone = 0;
1723                                         } else {
1724                                                 allDone =
1725                                                         yaffs_DeleteWorker(in,
1726                                                                 tn->
1727                                                                 internal
1728                                                                 [i],
1729                                                                 level -
1730                                                                 1,
1731                                                                 (chunkOffset
1732                                                                         <<
1733                                                                         YAFFS_TNODES_INTERNAL_BITS)
1734                                                                 + i,
1735                                                                 limit);
1736                                         }
1737                                         if (allDone) {
1738                                                 yaffs_FreeTnode(dev,
1739                                                                 tn->
1740                                                                 internal[i]);
1741                                                 tn->internal[i] = NULL;
1742                                         }
1743                                 }
1744                         }
1745                         return (allDone) ? 1 : 0;
1746                 } else if (level == 0) {
1747                         int hitLimit = 0;
1748
1749                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1750                                         i--) {
1751                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1752                                 if (theChunk) {
1753
1754                                         chunkInInode = (chunkOffset <<
1755                                                 YAFFS_TNODES_LEVEL0_BITS) + i;
1756
1757                                         foundChunk =
1758                                                 yaffs_FindChunkInGroup(dev,
1759                                                                 theChunk,
1760                                                                 &tags,
1761                                                                 in->objectId,
1762                                                                 chunkInInode);
1763
1764                                         if (foundChunk > 0) {
1765                                                 yaffs_DeleteChunk(dev,
1766                                                                   foundChunk, 1,
1767                                                                   __LINE__);
1768                                                 in->nDataChunks--;
1769                                                 if (limit) {
1770                                                         *limit = *limit - 1;
1771                                                         if (*limit <= 0)
1772                                                                 hitLimit = 1;
1773                                                 }
1774
1775                                         }
1776
1777                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1778                                 }
1779
1780                         }
1781                         return (i < 0) ? 1 : 0;
1782
1783                 }
1784
1785         }
1786
1787         return 1;
1788
1789 }
1790
1791 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1792 {
1793         yaffs_BlockInfo *theBlock;
1794
1795         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1796
1797         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->param.nChunksPerBlock);
1798         if (theBlock) {
1799                 theBlock->softDeletions++;
1800                 dev->nFreeChunks++;
1801         }
1802 }
1803
1804 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1805  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1806  * of the tnode.
1807  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1808  */
1809
1810 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1811                                   __u32 level, int chunkOffset)
1812 {
1813         int i;
1814         int theChunk;
1815         int allDone = 1;
1816         yaffs_Device *dev = in->myDev;
1817
1818         if (tn) {
1819                 if (level > 0) {
1820
1821                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1822                              i--) {
1823                                 if (tn->internal[i]) {
1824                                         allDone =
1825                                             yaffs_SoftDeleteWorker(in,
1826                                                                    tn->
1827                                                                    internal[i],
1828                                                                    level - 1,
1829                                                                    (chunkOffset
1830                                                                     <<
1831                                                                     YAFFS_TNODES_INTERNAL_BITS)
1832                                                                    + i);
1833                                         if (allDone) {
1834                                                 yaffs_FreeTnode(dev,
1835                                                                 tn->
1836                                                                 internal[i]);
1837                                                 tn->internal[i] = NULL;
1838                                         } else {
1839                                                 /* Hoosterman... how could this happen? */
1840                                         }
1841                                 }
1842                         }
1843                         return (allDone) ? 1 : 0;
1844                 } else if (level == 0) {
1845
1846                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1847                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1848                                 if (theChunk) {
1849                                         /* Note this does not find the real chunk, only the chunk group.
1850                                          * We make an assumption that a chunk group is not larger than
1851                                          * a block.
1852                                          */
1853                                         yaffs_SoftDeleteChunk(dev, theChunk);
1854                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1855                                 }
1856
1857                         }
1858                         return 1;
1859
1860                 }
1861
1862         }
1863
1864         return 1;
1865
1866 }
1867
1868 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1869 {
1870         if (obj->deleted &&
1871             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1872                 if (obj->nDataChunks <= 0) {
1873                         /* Empty file with no duplicate object headers, just delete it immediately */
1874                         yaffs_FreeTnode(obj->myDev,
1875                                         obj->variant.fileVariant.top);
1876                         obj->variant.fileVariant.top = NULL;
1877                         T(YAFFS_TRACE_TRACING,
1878                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1879                            obj->objectId));
1880                         yaffs_DoGenericObjectDeletion(obj);
1881                 } else {
1882                         yaffs_SoftDeleteWorker(obj,
1883                                                obj->variant.fileVariant.top,
1884                                                obj->variant.fileVariant.
1885                                                topLevel, 0);
1886                         obj->softDeleted = 1;
1887                 }
1888         }
1889 }
1890
1891 /* Pruning removes any part of the file structure tree that is beyond the
1892  * bounds of the file (ie that does not point to chunks).
1893  *
1894  * A file should only get pruned when its size is reduced.
1895  *
1896  * Before pruning, the chunks must be pulled from the tree and the
1897  * level 0 tnode entries must be zeroed out.
1898  * Could also use this for file deletion, but that's probably better handled
1899  * by a special case.
1900  *
1901  * This function is recursive. For levels > 0 the function is called again on
1902  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1903  * If there is no data in a subtree then it is pruned.
1904  */
1905
1906 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1907                                 __u32 level, int del0)
1908 {
1909         int i;
1910         int hasData;
1911
1912         if (tn) {
1913                 hasData = 0;
1914
1915                 if(level > 0){
1916                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1917                                 if (tn->internal[i]) {
1918                                         tn->internal[i] =
1919                                                 yaffs_PruneWorker(dev, tn->internal[i],
1920                                                         level - 1,
1921                                                         (i == 0) ? del0 : 1);
1922                                 }
1923
1924                                 if (tn->internal[i])
1925                                         hasData++;
1926                         }
1927                 } else {
1928                         int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1929                         __u32 *map = (__u32 *)tn;
1930
1931                         for(i = 0; !hasData && i < tnodeSize_u32; i++){
1932                                 if(map[i])
1933                                         hasData++;
1934                         }
1935                 }
1936
1937                 if (hasData == 0 && del0) {
1938                         /* Free and return NULL */
1939
1940                         yaffs_FreeTnode(dev, tn);
1941                         tn = NULL;
1942                 }
1943
1944         }
1945
1946         return tn;
1947
1948 }
1949
1950 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1951                                 yaffs_FileStructure *fStruct)
1952 {
1953         int i;
1954         int hasData;
1955         int done = 0;
1956         yaffs_Tnode *tn;
1957
1958         if (fStruct->topLevel > 0) {
1959                 fStruct->top =
1960                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1961
1962                 /* Now we have a tree with all the non-zero branches NULL but the height
1963                  * is the same as it was.
1964                  * Let's see if we can trim internal tnodes to shorten the tree.
1965                  * We can do this if only the 0th element in the tnode is in use
1966                  * (ie all the non-zero are NULL)
1967                  */
1968
1969                 while (fStruct->topLevel && !done) {
1970                         tn = fStruct->top;
1971
1972                         hasData = 0;
1973                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1974                                 if (tn->internal[i])
1975                                         hasData++;
1976                         }
1977
1978                         if (!hasData) {
1979                                 fStruct->top = tn->internal[0];
1980                                 fStruct->topLevel--;
1981                                 yaffs_FreeTnode(dev, tn);
1982                         } else {
1983                                 done = 1;
1984                         }
1985                 }
1986         }
1987
1988         return YAFFS_OK;
1989 }
1990
1991 /*-------------------- End of File Structure functions.-------------------*/
1992
1993 /* yaffs_CreateFreeObjects creates a bunch more objects and
1994  * adds them to the object free list.
1995  */
1996 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1997 {
1998         int i;
1999         yaffs_Object *newObjects;
2000         yaffs_ObjectList *list;
2001
2002         if (nObjects < 1)
2003                 return YAFFS_OK;
2004
2005         /* make these things */
2006         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2007         list = YMALLOC(sizeof(yaffs_ObjectList));
2008
2009         if (!newObjects || !list) {
2010                 if (newObjects){
2011                         YFREE(newObjects);
2012                         newObjects = NULL;
2013                 }
2014                 if (list){
2015                         YFREE(list);
2016                         list = NULL;
2017                 }
2018                 T(YAFFS_TRACE_ALLOCATE,
2019                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2020                 return YAFFS_FAIL;
2021         }
2022
2023         /* Hook them into the free list */
2024         for (i = 0; i < nObjects - 1; i++) {
2025                 newObjects[i].siblings.next =
2026                                 (struct ylist_head *)(&newObjects[i + 1]);
2027         }
2028
2029         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2030         dev->freeObjects = newObjects;
2031         dev->nFreeObjects += nObjects;
2032         dev->nObjectsCreated += nObjects;
2033
2034         /* Now add this bunch of Objects to a list for freeing up. */
2035
2036         list->objects = newObjects;
2037         list->next = dev->allocatedObjectList;
2038         dev->allocatedObjectList = list;
2039
2040         return YAFFS_OK;
2041 }
2042
2043
2044 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2045 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2046 {
2047         yaffs_Object *tn = NULL;
2048
2049 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2050         tn = YMALLOC(sizeof(yaffs_Object));
2051         if(tn)
2052                 dev->nObjectsCreated++;
2053 #else
2054         /* If there are none left make more */
2055         if (!dev->freeObjects)
2056                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2057
2058         if (dev->freeObjects) {
2059                 tn = dev->freeObjects;
2060                 dev->freeObjects =
2061                         (yaffs_Object *) (dev->freeObjects->siblings.next);
2062                 dev->nFreeObjects--;
2063         }
2064 #endif
2065         if (tn) {
2066                 /* Now sweeten it up... */
2067
2068                 memset(tn, 0, sizeof(yaffs_Object));
2069                 tn->beingCreated = 1;
2070
2071                 tn->myDev = dev;
2072                 tn->hdrChunk = 0;
2073                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2074                 YINIT_LIST_HEAD(&(tn->hardLinks));
2075                 YINIT_LIST_HEAD(&(tn->hashLink));
2076                 YINIT_LIST_HEAD(&tn->siblings);
2077
2078
2079                 /* Now make the directory sane */
2080                 if (dev->rootDir) {
2081                         tn->parent = dev->rootDir;
2082                         ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2083                 }
2084
2085                 /* Add it to the lost and found directory.
2086                  * NB Can't put root or lostNFound in lostNFound so
2087                  * check if lostNFound exists first
2088                  */
2089                 if (dev->lostNFoundDir)
2090                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2091
2092                 tn->beingCreated = 0;
2093         }
2094
2095         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2096
2097         return tn;
2098 }
2099
2100 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2101                                                __u32 mode)
2102 {
2103
2104         yaffs_Object *obj =
2105             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2106         if (obj) {
2107                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
2108                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2109                 obj->unlinkAllowed = 0; /* ... or unlink it */
2110                 obj->deleted = 0;
2111                 obj->unlinked = 0;
2112                 obj->yst_mode = mode;
2113                 obj->myDev = dev;
2114                 obj->hdrChunk = 0;      /* Not a valid chunk. */
2115         }
2116
2117         return obj;
2118
2119 }
2120
2121 static void yaffs_UnhashObject(yaffs_Object *tn)
2122 {
2123         int bucket;
2124         yaffs_Device *dev = tn->myDev;
2125
2126         /* If it is still linked into the bucket list, free from the list */
2127         if (!ylist_empty(&tn->hashLink)) {
2128                 ylist_del_init(&tn->hashLink);
2129                 bucket = yaffs_HashFunction(tn->objectId);
2130                 dev->objectBucket[bucket].count--;
2131         }
2132 }
2133
2134 /*  FreeObject frees up a Object and puts it back on the free list */
2135 static void yaffs_FreeObject(yaffs_Object *tn)
2136 {
2137         yaffs_Device *dev = tn->myDev;
2138
2139         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2140
2141         if (!tn)
2142                 YBUG();
2143         if (tn->parent)
2144                 YBUG();
2145         if (!ylist_empty(&tn->siblings))
2146                 YBUG();
2147
2148
2149         if (tn->myInode) {
2150                 /* We're still hooked up to a cached inode.
2151                  * Don't delete now, but mark for later deletion
2152                  */
2153                 tn->deferedFree = 1;
2154                 return;
2155         }
2156
2157         yaffs_UnhashObject(tn);
2158
2159 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2160         YFREE(tn);
2161         dev->nObjectsCreated--;
2162         tn = NULL;
2163 #else
2164         /* Link into the free list. */
2165         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2166         dev->freeObjects = tn;
2167         dev->nFreeObjects++;
2168 #endif
2169         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2170 }
2171
2172
2173 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2174 {
2175         if (obj->deferedFree)
2176                 yaffs_FreeObject(obj);
2177 }
2178
2179
2180 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2181 {
2182         /* Free the list of allocated Objects */
2183
2184         yaffs_ObjectList *tmp;
2185
2186         while (dev->allocatedObjectList) {
2187                 tmp = dev->allocatedObjectList->next;
2188                 YFREE(dev->allocatedObjectList->objects);
2189                 YFREE(dev->allocatedObjectList);
2190
2191                 dev->allocatedObjectList = tmp;
2192         }
2193
2194         dev->freeObjects = NULL;
2195         dev->nFreeObjects = 0;
2196         dev->nObjectsCreated = 0;
2197 }
2198
2199 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2200 {
2201         int i;
2202
2203         dev->allocatedObjectList = NULL;
2204         dev->freeObjects = NULL;
2205         dev->nFreeObjects = 0;
2206
2207         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2208                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2209                 dev->objectBucket[i].count = 0;
2210         }
2211 }
2212
2213 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2214 {
2215         int i;
2216         int l = 999;
2217         int lowest = 999999;
2218
2219
2220         /* Search for the shortest list or one that
2221          * isn't too long.
2222          */
2223
2224         for (i = 0; i < 10 && lowest > 4; i++) {
2225                 dev->bucketFinder++;
2226                 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2227                 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2228                         lowest = dev->objectBucket[dev->bucketFinder].count;
2229                         l = dev->bucketFinder;
2230                 }
2231
2232         }
2233
2234         return l;
2235 }
2236
2237 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2238 {
2239         int bucket = yaffs_FindNiceObjectBucket(dev);
2240
2241         /* Now find an object value that has not already been taken
2242          * by scanning the list.
2243          */
2244
2245         int found = 0;
2246         struct ylist_head *i;
2247
2248         __u32 n = (__u32) bucket;
2249
2250         /* yaffs_CheckObjectHashSanity();  */
2251
2252         while (!found) {
2253                 found = 1;
2254                 n += YAFFS_NOBJECT_BUCKETS;
2255                 if (1 || dev->objectBucket[bucket].count > 0) {
2256                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2257                                 /* If there is already one in the list */
2258                                 if (i && ylist_entry(i, yaffs_Object,
2259                                                 hashLink)->objectId == n) {
2260                                         found = 0;
2261                                 }
2262                         }
2263                 }
2264         }
2265
2266         return n;
2267 }
2268
2269 static void yaffs_HashObject(yaffs_Object *in)
2270 {
2271         int bucket = yaffs_HashFunction(in->objectId);
2272         yaffs_Device *dev = in->myDev;
2273
2274         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2275         dev->objectBucket[bucket].count++;
2276 }
2277
2278 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2279 {
2280         int bucket = yaffs_HashFunction(number);
2281         struct ylist_head *i;
2282         yaffs_Object *in;
2283
2284         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2285                 /* Look if it is in the list */
2286                 if (i) {
2287                         in = ylist_entry(i, yaffs_Object, hashLink);
2288                         if (in->objectId == number) {
2289
2290                                 /* Don't tell the VFS about this one if it is defered free */
2291                                 if (in->deferedFree)
2292                                         return NULL;
2293
2294                                 return in;
2295                         }
2296                 }
2297         }
2298
2299         return NULL;
2300 }
2301
2302 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2303                                     yaffs_ObjectType type)
2304 {
2305         yaffs_Object *theObject=NULL;
2306         yaffs_Tnode *tn = NULL;
2307
2308         if (number < 0)
2309                 number = yaffs_CreateNewObjectNumber(dev);
2310
2311         if (type == YAFFS_OBJECT_TYPE_FILE) {
2312                 tn = yaffs_GetTnode(dev);
2313                 if (!tn)
2314                         return NULL;
2315         }
2316
2317         theObject = yaffs_AllocateEmptyObject(dev);
2318         if (!theObject){
2319                 if(tn)
2320                         yaffs_FreeTnode(dev,tn);
2321                 return NULL;
2322         }
2323
2324
2325         if (theObject) {
2326                 theObject->fake = 0;
2327                 theObject->renameAllowed = 1;
2328                 theObject->unlinkAllowed = 1;
2329                 theObject->objectId = number;
2330                 yaffs_HashObject(theObject);
2331                 theObject->variantType = type;
2332 #ifdef CONFIG_YAFFS_WINCE
2333                 yfsd_WinFileTimeNow(theObject->win_atime);
2334                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2335                     theObject->win_atime[0];
2336                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2337                     theObject->win_atime[1];
2338
2339 #else
2340
2341                 theObject->yst_atime = theObject->yst_mtime =
2342                     theObject->yst_ctime = Y_CURRENT_TIME;
2343 #endif
2344                 switch (type) {
2345                 case YAFFS_OBJECT_TYPE_FILE:
2346                         theObject->variant.fileVariant.fileSize = 0;
2347                         theObject->variant.fileVariant.scannedFileSize = 0;
2348                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2349                         theObject->variant.fileVariant.topLevel = 0;
2350                         theObject->variant.fileVariant.top = tn;
2351                         break;
2352                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2353                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2354                                         children);
2355                         break;
2356                 case YAFFS_OBJECT_TYPE_SYMLINK:
2357                 case YAFFS_OBJECT_TYPE_HARDLINK:
2358                 case YAFFS_OBJECT_TYPE_SPECIAL:
2359                         /* No action required */
2360                         break;
2361                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2362                         /* todo this should not happen */
2363                         break;
2364                 }
2365         }
2366
2367         return theObject;
2368 }
2369
2370 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2371                                                       int number,
2372                                                       yaffs_ObjectType type)
2373 {
2374         yaffs_Object *theObject = NULL;
2375
2376         if (number > 0)
2377                 theObject = yaffs_FindObjectByNumber(dev, number);
2378
2379         if (!theObject)
2380                 theObject = yaffs_CreateNewObject(dev, number, type);
2381
2382         return theObject;
2383
2384 }
2385
2386
2387 static YCHAR *yaffs_CloneString(const YCHAR *str)
2388 {
2389         YCHAR *newStr = NULL;
2390         int len;
2391
2392         if (!str)
2393                 str = _Y("");
2394
2395         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2396         newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2397         if (newStr){
2398                 yaffs_strncpy(newStr, str,len);
2399                 newStr[len] = 0;
2400         }
2401         return newStr;
2402
2403 }
2404
2405 /*
2406  * Mknod (create) a new object.
2407  * equivalentObject only has meaning for a hard link;
2408  * aliasString only has meaning for a symlink.
2409  * rdev only has meaning for devices (a subset of special objects)
2410  */
2411
2412 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2413                                        yaffs_Object *parent,
2414                                        const YCHAR *name,
2415                                        __u32 mode,
2416                                        __u32 uid,
2417                                        __u32 gid,
2418                                        yaffs_Object *equivalentObject,
2419                                        const YCHAR *aliasString, __u32 rdev)
2420 {
2421         yaffs_Object *in;
2422         YCHAR *str = NULL;
2423
2424         yaffs_Device *dev = parent->myDev;
2425
2426         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2427         if (yaffs_FindObjectByName(parent, name))
2428                 return NULL;
2429
2430         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2431                 str = yaffs_CloneString(aliasString);
2432                 if (!str)
2433                         return NULL;
2434         }
2435
2436         in = yaffs_CreateNewObject(dev, -1, type);
2437
2438         if (!in){
2439                 if(str)
2440                         YFREE(str);
2441                 return NULL;
2442         }
2443
2444
2445
2446
2447
2448         if (in) {
2449                 in->hdrChunk = 0;
2450                 in->valid = 1;
2451                 in->variantType = type;
2452
2453                 in->yst_mode = mode;
2454
2455 #ifdef CONFIG_YAFFS_WINCE
2456                 yfsd_WinFileTimeNow(in->win_atime);
2457                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2458                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2459
2460 #else
2461                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2462
2463                 in->yst_rdev = rdev;
2464                 in->yst_uid = uid;
2465                 in->yst_gid = gid;
2466 #endif
2467                 in->nDataChunks = 0;
2468
2469                 yaffs_SetObjectName(in, name);
2470                 in->dirty = 1;
2471
2472                 yaffs_AddObjectToDirectory(parent, in);
2473
2474                 in->myDev = parent->myDev;
2475
2476                 switch (type) {
2477                 case YAFFS_OBJECT_TYPE_SYMLINK:
2478                         in->variant.symLinkVariant.alias = str;
2479                         break;
2480                 case YAFFS_OBJECT_TYPE_HARDLINK:
2481                         in->variant.hardLinkVariant.equivalentObject =
2482                                 equivalentObject;
2483                         in->variant.hardLinkVariant.equivalentObjectId =
2484                                 equivalentObject->objectId;
2485                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2486                         break;
2487                 case YAFFS_OBJECT_TYPE_FILE:
2488                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2489                 case YAFFS_OBJECT_TYPE_SPECIAL:
2490                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2491                         /* do nothing */
2492                         break;
2493                 }
2494
2495                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2496                         /* Could not create the object header, fail the creation */
2497                         yaffs_DeleteObject(in);
2498                         in = NULL;
2499                 }
2500
2501                 yaffs_UpdateParent(parent);
2502         }
2503
2504         return in;
2505 }
2506
2507 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2508                         __u32 mode, __u32 uid, __u32 gid)
2509 {
2510         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2511                                 uid, gid, NULL, NULL, 0);
2512 }
2513
2514 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2515                                 __u32 mode, __u32 uid, __u32 gid)
2516 {
2517         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2518                                  mode, uid, gid, NULL, NULL, 0);
2519 }
2520
2521 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2522                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2523 {
2524         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2525                                  uid, gid, NULL, NULL, rdev);
2526 }
2527
2528 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2529                                 __u32 mode, __u32 uid, __u32 gid,
2530                                 const YCHAR *alias)
2531 {
2532         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2533                                 uid, gid, NULL, alias, 0);
2534 }
2535
2536 /* yaffs_Link returns the object id of the equivalent object.*/
2537 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2538                         yaffs_Object *equivalentObject)
2539 {
2540         /* Get the real object in case we were fed a hard link as an equivalent object */
2541         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2542
2543         if (yaffs_MknodObject
2544             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2545              equivalentObject, NULL, 0)) {
2546                 return equivalentObject;
2547         } else {
2548                 return NULL;
2549         }
2550
2551 }
2552
2553 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2554                                 const YCHAR *newName, int force, int shadows)
2555 {
2556         int unlinkOp;
2557         int deleteOp;
2558
2559         yaffs_Object *existingTarget;
2560
2561         if (newDir == NULL)
2562                 newDir = obj->parent;   /* use the old directory */
2563
2564         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2565                 T(YAFFS_TRACE_ALWAYS,
2566                   (TSTR
2567                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2568                     TENDSTR)));
2569                 YBUG();
2570         }
2571
2572         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2573         if (obj->myDev->param.isYaffs2)
2574                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2575         else
2576                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2577                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2578
2579         deleteOp = (newDir == obj->myDev->deletedDir);
2580
2581         existingTarget = yaffs_FindObjectByName(newDir, newName);
2582
2583         /* If the object is a file going into the unlinked directory,
2584          *   then it is OK to just stuff it in since duplicate names are allowed.
2585          *   else only proceed if the new name does not exist and if we're putting
2586          *   it into a directory.
2587          */
2588         if ((unlinkOp ||
2589              deleteOp ||
2590              force ||
2591              (shadows > 0) ||
2592              !existingTarget) &&
2593             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2594                 yaffs_SetObjectName(obj, newName);
2595                 obj->dirty = 1;
2596
2597                 yaffs_AddObjectToDirectory(newDir, obj);
2598
2599                 if (unlinkOp)
2600                         obj->unlinked = 1;
2601
2602                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2603                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2604                         return YAFFS_OK;
2605         }
2606
2607         return YAFFS_FAIL;
2608 }
2609
2610 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2611                 yaffs_Object *newDir, const YCHAR *newName)
2612 {
2613         yaffs_Object *obj = NULL;
2614         yaffs_Object *existingTarget = NULL;
2615         int force = 0;
2616         int result;
2617         yaffs_Device *dev;
2618
2619
2620         if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2621                 YBUG();
2622         if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2623                 YBUG();
2624
2625         dev = oldDir->myDev;
2626
2627 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2628         /* Special case for case insemsitive systems (eg. WinCE).
2629          * While look-up is case insensitive, the name isn't.
2630          * Therefore we might want to change x.txt to X.txt
2631         */
2632         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2633                 force = 1;
2634 #endif
2635
2636         if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2637                 /* ENAMETOOLONG */
2638                 return YAFFS_FAIL;
2639
2640         obj = yaffs_FindObjectByName(oldDir, oldName);
2641
2642         if (obj && obj->renameAllowed) {
2643
2644                 /* Now do the handling for an existing target, if there is one */
2645
2646                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2647                 if (existingTarget &&
2648                         existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2649                         !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2650                         /* There is a target that is a non-empty directory, so we fail */
2651                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2652                 } else if (existingTarget && existingTarget != obj) {
2653                         /* Nuke the target first, using shadowing,
2654                          * but only if it isn't the same object.
2655                          *
2656                          * Note we must disable gc otherwise it can mess up the shadowing.
2657                          *
2658                          */
2659                         dev->isDoingGC=1;
2660                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2661                                                 existingTarget->objectId);
2662                         existingTarget->isShadowed = 1;
2663                         yaffs_UnlinkObject(existingTarget);
2664                         dev->isDoingGC=0;
2665                 }
2666
2667                 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2668
2669                 yaffs_UpdateParent(oldDir);
2670                 if(newDir != oldDir)
2671                         yaffs_UpdateParent(newDir);
2672                 
2673                 return result;
2674         }
2675         return YAFFS_FAIL;
2676 }
2677
2678 /*------------------------- Block Management and Page Allocation ----------------*/
2679
2680 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2681 {
2682         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2683
2684         dev->blockInfo = NULL;
2685         dev->chunkBits = NULL;
2686
2687         dev->allocationBlock = -1;      /* force it to get a new one */
2688
2689         /* If the first allocation strategy fails, thry the alternate one */
2690         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2691         if (!dev->blockInfo) {
2692                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2693                 dev->blockInfoAlt = 1;
2694         } else
2695                 dev->blockInfoAlt = 0;
2696
2697         if (dev->blockInfo) {
2698                 /* Set up dynamic blockinfo stuff. */
2699                 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2700                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2701                 if (!dev->chunkBits) {
2702                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2703                         dev->chunkBitsAlt = 1;
2704                 } else
2705                         dev->chunkBitsAlt = 0;
2706         }
2707
2708         if (dev->blockInfo && dev->chunkBits) {
2709                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2710                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2711                 return YAFFS_OK;
2712         }
2713
2714         return YAFFS_FAIL;
2715 }
2716
2717 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2718 {
2719         if (dev->blockInfoAlt && dev->blockInfo)
2720                 YFREE_ALT(dev->blockInfo);
2721         else if (dev->blockInfo)
2722                 YFREE(dev->blockInfo);
2723
2724         dev->blockInfoAlt = 0;
2725
2726         dev->blockInfo = NULL;
2727
2728         if (dev->chunkBitsAlt && dev->chunkBits)
2729                 YFREE_ALT(dev->chunkBits);
2730         else if (dev->chunkBits)
2731                 YFREE(dev->chunkBits);
2732         dev->chunkBitsAlt = 0;
2733         dev->chunkBits = NULL;
2734 }
2735
2736 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2737                                         yaffs_BlockInfo *bi)
2738 {
2739
2740         if (!dev->param.isYaffs2)
2741                 return 1;       /* disqualification only applies to yaffs2. */
2742
2743         if (!bi->hasShrinkHeader)
2744                 return 1;       /* can gc */
2745
2746         yaffs_FindOldestDirtySequence(dev);
2747
2748         /* Can't do gc of this block if there are any blocks older than this one that have
2749          * discarded pages.
2750          */
2751         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2752 }
2753
2754 /*
2755  * yaffs_FindRefreshBlock()
2756  * periodically finds the oldest full block by sequence number for refreshing.
2757  * Only for yaffs2.
2758  */
2759 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2760 {
2761         __u32 b ;
2762
2763         __u32 oldest = 0;
2764         __u32 oldestSequence = 0;
2765
2766         yaffs_BlockInfo *bi;
2767
2768         /*
2769          * If refresh period < 10 then refreshing is disabled.
2770          */
2771         if(dev->param.refreshPeriod < 10 ||
2772                 !dev->param.isYaffs2)
2773                 return oldest;
2774
2775         /*
2776          * Fix broken values.
2777          */
2778         if(dev->refreshSkip > dev->param.refreshPeriod)
2779                 dev->refreshSkip = dev->param.refreshPeriod;
2780
2781         if(dev->refreshSkip > 0){
2782                 dev->refreshSkip--;
2783                 return oldest;
2784         }
2785
2786         /*
2787          * Refresh skip is now zero.
2788          * We'll do a refresh this time around....
2789          * Update the refresh skip and find the oldest block.
2790          */
2791         dev->refreshSkip = dev->param.refreshPeriod;
2792         dev->refreshCount++;
2793
2794         for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2795
2796                 bi = yaffs_GetBlockInfo(dev, b);
2797                 
2798
2799                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2800
2801                         if(oldest < 1 ||
2802                                 bi->sequenceNumber < oldestSequence){
2803                                 oldest = b;
2804                                 oldestSequence = bi->sequenceNumber;
2805                         }
2806                 }
2807         }
2808
2809         if (oldest > 0) {
2810                 T(YAFFS_TRACE_GC,
2811                   (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2812                    dev->refreshCount, oldest, oldestSequence));
2813         }
2814
2815         return oldest;
2816 }
2817
2818 /*
2819  * FindDiretiestBlock is used to select the dirtiest block (or close enough)
2820  * for garbage collection.
2821  */
2822
2823 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2824                                         int aggressive)
2825 {
2826         int b = dev->currentDirtyChecker;
2827
2828         int i;
2829         int iterations;
2830         int dirtiest = -1;
2831         int pagesInUse = 0;
2832         int prioritised = 0;
2833         yaffs_BlockInfo *bi;
2834         int pendingPrioritisedExist = 0;
2835
2836         /* First let's see if we need to grab a prioritised block */
2837         if (dev->hasPendingPrioritisedGCs) {
2838                 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2839
2840                         bi = yaffs_GetBlockInfo(dev, i);
2841                         /* yaffs_VerifyBlock(dev,bi,i); */
2842
2843                         if (bi->gcPrioritise) {
2844                                 pendingPrioritisedExist = 1;
2845                                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2846                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2847                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2848                                         dirtiest = i;
2849                                         prioritised = 1;
2850                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2851                                 }
2852                         }
2853                 }
2854
2855                 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2856                         dev->hasPendingPrioritisedGCs = 0;
2857         }
2858
2859         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2860          * search harder.
2861          * else (we're doing a leasurely gc), then we only bother to do this if the
2862          * block has only a few pages in use.
2863          */
2864
2865         dev->nonAggressiveSkip--;
2866
2867         if (!aggressive && (dev->nonAggressiveSkip > 0))
2868                 return -1;
2869
2870         if (!prioritised)
2871                 pagesInUse =
2872                         (aggressive) ? dev->param.nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2873
2874         if (aggressive)
2875                 iterations =
2876                     dev->internalEndBlock - dev->internalStartBlock + 1;
2877         else {
2878                 iterations =
2879                     dev->internalEndBlock - dev->internalStartBlock + 1;
2880                 iterations = iterations / 16;
2881                 if (iterations > 200)
2882                         iterations = 200;
2883         }
2884
2885         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2886                 b++;
2887                 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2888                         b = dev->internalStartBlock;
2889
2890                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2891                         T(YAFFS_TRACE_ERROR,
2892                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2893                         YBUG();
2894                 }
2895
2896                 bi = yaffs_GetBlockInfo(dev, b);
2897
2898                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2899                         (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2900                                 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2901                         dirtiest = b;
2902                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2903                 }
2904         }
2905
2906         dev->currentDirtyChecker = b;
2907
2908         if (dirtiest > 0) {
2909                 T(YAFFS_TRACE_GC,
2910                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2911                    dev->param.nChunksPerBlock - pagesInUse, prioritised));
2912         }
2913
2914         if (dirtiest > 0)
2915                 dev->nonAggressiveSkip = 4;
2916
2917         return dirtiest;
2918 }
2919
2920 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2921 {
2922         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2923
2924         int erasedOk = 0;
2925
2926         /* If the block is still healthy erase it and mark as clean.
2927          * If the block has had a data failure, then retire it.
2928          */
2929
2930         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2931                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2932                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2933
2934         yaffs_ClearOldestDirtySequence(dev,bi);
2935
2936         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2937
2938         if (!bi->needsRetiring) {
2939                 yaffs_InvalidateCheckpoint(dev);
2940                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2941                 if (!erasedOk) {
2942                         dev->nErasureFailures++;
2943                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2944                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2945                 }
2946         }
2947
2948         if (erasedOk &&
2949             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2950                 int i;
2951                 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2952                         if (!yaffs_CheckChunkErased
2953                             (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2954                                 T(YAFFS_TRACE_ERROR,
2955                                   (TSTR
2956                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2957                                     TENDSTR), blockNo, i));
2958                         }
2959                 }
2960         }
2961
2962         if (erasedOk) {
2963                 /* Clean it up... */
2964                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2965                 bi->sequenceNumber = 0;
2966                 dev->nErasedBlocks++;
2967                 bi->pagesInUse = 0;
2968                 bi->softDeletions = 0;
2969                 bi->hasShrinkHeader = 0;
2970                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2971                 bi->gcPrioritise = 0;
2972                 yaffs_ClearChunkBits(dev, blockNo);
2973
2974                 T(YAFFS_TRACE_ERASE,
2975                   (TSTR("Erased block %d" TENDSTR), blockNo));
2976         } else {
2977                 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2978
2979                 yaffs_RetireBlock(dev, blockNo);
2980                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2981                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2982         }
2983 }
2984
2985 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2986 {
2987         int i;
2988
2989         yaffs_BlockInfo *bi;
2990
2991         if (dev->nErasedBlocks < 1) {
2992                 /* Hoosterman we've got a problem.
2993                  * Can't get space to gc
2994                  */
2995                 T(YAFFS_TRACE_ERROR,
2996                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2997
2998                 return -1;
2999         }
3000
3001         /* Find an empty block. */
3002
3003         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
3004                 dev->allocationBlockFinder++;
3005                 if (dev->allocationBlockFinder < dev->internalStartBlock
3006                     || dev->allocationBlockFinder > dev->internalEndBlock) {
3007                         dev->allocationBlockFinder = dev->internalStartBlock;
3008                 }
3009
3010                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
3011
3012                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
3013                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
3014                         dev->sequenceNumber++;
3015                         bi->sequenceNumber = dev->sequenceNumber;
3016                         dev->nErasedBlocks--;
3017                         T(YAFFS_TRACE_ALLOCATE,
3018                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
3019                            dev->allocationBlockFinder, dev->sequenceNumber,
3020                            dev->nErasedBlocks));
3021                         return dev->allocationBlockFinder;
3022                 }
3023         }
3024
3025         T(YAFFS_TRACE_ALWAYS,
3026           (TSTR
3027            ("yaffs tragedy: no more erased blocks, but there should have been %d"
3028             TENDSTR), dev->nErasedBlocks));
3029
3030         return -1;
3031 }
3032
3033
3034
3035 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
3036 {
3037         if (!dev->nCheckpointBlocksRequired &&
3038            dev->param.isYaffs2) {
3039                 /* Not a valid value so recalculate */
3040                 int nBytes = 0;
3041                 int nBlocks;
3042                 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
3043                 int tnodeSize = yaffs_CalcTnodeSize(dev);
3044
3045                 nBytes += sizeof(yaffs_CheckpointValidity);
3046                 nBytes += sizeof(yaffs_CheckpointDevice);
3047                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
3048                 nBytes += devBlocks * dev->chunkBitmapStride;
3049                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
3050                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
3051                 nBytes += sizeof(yaffs_CheckpointValidity);
3052                 nBytes += sizeof(__u32); /* checksum*/
3053
3054                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
3055
3056                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
3057
3058                 dev->nCheckpointBlocksRequired = nBlocks;
3059         }
3060
3061         return dev->nCheckpointBlocksRequired;
3062 }
3063
3064 /*
3065  * Check if there's space to allocate...
3066  * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3067  */
3068 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
3069 {
3070         int reservedChunks;
3071         int reservedBlocks = dev->param.nReservedBlocks;
3072         int checkpointBlocks;
3073
3074         if (dev->param.isYaffs2) {
3075                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) -
3076                                     dev->blocksInCheckpoint;
3077                 if (checkpointBlocks < 0)
3078                         checkpointBlocks = 0;
3079         } else {
3080                 checkpointBlocks = 0;
3081         }
3082
3083         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3084
3085         return (dev->nFreeChunks > reservedChunks);
3086 }
3087
3088 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3089                 yaffs_BlockInfo **blockUsedPtr)
3090 {
3091         int retVal;
3092         yaffs_BlockInfo *bi;
3093
3094         if (dev->allocationBlock < 0) {
3095                 /* Get next block to allocate off */
3096                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3097                 dev->allocationPage = 0;
3098         }
3099
3100         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
3101                 /* Not enough space to allocate unless we're allowed to use the reserve. */
3102                 return -1;
3103         }
3104
3105         if (dev->nErasedBlocks < dev->param.nReservedBlocks
3106                         && dev->allocationPage == 0) {
3107                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3108         }
3109
3110         /* Next page please.... */
3111         if (dev->allocationBlock >= 0) {
3112                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3113
3114                 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3115                         dev->allocationPage;
3116                 bi->pagesInUse++;
3117                 yaffs_SetChunkBit(dev, dev->allocationBlock,
3118                                 dev->allocationPage);
3119
3120                 dev->allocationPage++;
3121
3122                 dev->nFreeChunks--;
3123
3124                 /* If the block is full set the state to full */
3125                 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3126                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3127                         dev->allocationBlock = -1;
3128                 }
3129
3130                 if (blockUsedPtr)
3131                         *blockUsedPtr = bi;
3132
3133                 return retVal;
3134         }
3135
3136         T(YAFFS_TRACE_ERROR,
3137                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3138
3139         return -1;
3140 }
3141
3142 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3143 {
3144         int n;
3145
3146         n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3147
3148         if (dev->allocationBlock > 0)
3149                 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3150
3151         return n;
3152
3153 }
3154
3155 /*
3156  * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3157  * if we don't want to write to it.
3158  */
3159 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3160 {
3161         if(dev->allocationBlock > 0){
3162                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3163                 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3164                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3165                         dev->allocationBlock = -1;
3166                 }
3167         }
3168 }
3169
3170
3171 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3172                 int wholeBlock)
3173 {
3174         int oldChunk;
3175         int newChunk;
3176         int markNAND;
3177         int retVal = YAFFS_OK;
3178         int cleanups = 0;
3179         int i;
3180         int isCheckpointBlock;
3181         int matchingChunk;
3182         int maxCopies;
3183
3184         int chunksBefore = yaffs_GetErasedChunks(dev);
3185         int chunksAfter;
3186
3187         yaffs_ExtendedTags tags;
3188
3189         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3190
3191         yaffs_Object *object;
3192
3193         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3194
3195
3196         T(YAFFS_TRACE_TRACING,
3197                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3198                          block,
3199                          bi->pagesInUse,
3200                          bi->hasShrinkHeader,
3201                          wholeBlock));
3202
3203         /*yaffs_VerifyFreeChunks(dev); */
3204
3205         if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3206                 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3207         
3208         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3209
3210         /* Take off the number of soft deleted entries because
3211          * they're going to get really deleted during GC.
3212          */
3213         if(dev->gcChunk == 0) /* first time through for this block */
3214                 dev->nFreeChunks -= bi->softDeletions;
3215
3216         dev->isDoingGC = 1;
3217
3218         if (isCheckpointBlock ||
3219                         !yaffs_StillSomeChunkBits(dev, block)) {
3220                 T(YAFFS_TRACE_TRACING,
3221                                 (TSTR
3222                                  ("Collecting block %d that has no chunks in use" TENDSTR),
3223                                  block));
3224                 yaffs_BlockBecameDirty(dev, block);
3225         } else {
3226
3227                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3228
3229                 yaffs_VerifyBlock(dev, bi, block);
3230
3231                 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 10;
3232                 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3233
3234                 for (/* init already done */;
3235                      retVal == YAFFS_OK &&
3236                      dev->gcChunk < dev->param.nChunksPerBlock &&
3237                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3238                      maxCopies > 0;
3239                      dev->gcChunk++, oldChunk++) {
3240                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3241
3242                                 /* This page is in use and might need to be copied off */
3243
3244                                 maxCopies--;
3245
3246                                 markNAND = 1;
3247
3248                                 yaffs_InitialiseTags(&tags);
3249
3250                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3251                                                                 buffer, &tags);
3252
3253                                 object =
3254                                     yaffs_FindObjectByNumber(dev,
3255                                                              tags.objectId);
3256
3257                                 T(YAFFS_TRACE_GC_DETAIL,
3258                                   (TSTR
3259                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3260                                    dev->gcChunk, tags.objectId, tags.chunkId,
3261                                    tags.byteCount));
3262
3263                                 if (object && !yaffs_SkipVerification(dev)) {
3264                                         if (tags.chunkId == 0)
3265                                                 matchingChunk = object->hdrChunk;
3266                                         else if (object->softDeleted)
3267                                                 matchingChunk = oldChunk; /* Defeat the test */
3268                                         else
3269                                                 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3270
3271                                         if (oldChunk != matchingChunk)
3272                                                 T(YAFFS_TRACE_ERROR,
3273                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3274                                                   oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3275
3276                                 }
3277
3278                                 if (!object) {
3279                                         T(YAFFS_TRACE_ERROR,
3280                                           (TSTR
3281                                            ("page %d in gc has no object: %d %d %d "
3282                                             TENDSTR), oldChunk,
3283                                             tags.objectId, tags.chunkId, tags.byteCount));
3284                                 }
3285
3286                                 if (object &&
3287                                     object->deleted &&
3288                                     object->softDeleted &&
3289                                     tags.chunkId != 0) {
3290                                         /* Data chunk in a soft deleted file, throw it away
3291                                          * It's a soft deleted data chunk,
3292                                          * No need to copy this, just forget about it and
3293                                          * fix up the object.
3294                                          */
3295
3296                                         object->nDataChunks--;
3297
3298                                         if (object->nDataChunks <= 0) {
3299                                                 /* remeber to clean up the object */
3300                                                 dev->gcCleanupList[cleanups] =
3301                                                     tags.objectId;
3302                                                 cleanups++;
3303                                         }
3304                                         markNAND = 0;
3305                                 } else if (0) {
3306                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
3307                                         /* Deleted object header with no data chunks.
3308                                          * Can be discarded and the file deleted.
3309                                          */
3310                                         object->hdrChunk = 0;
3311                                         yaffs_FreeTnode(object->myDev,
3312                                                         object->variant.
3313                                                         fileVariant.top);
3314                                         object->variant.fileVariant.top = NULL;
3315                                         yaffs_DoGenericObjectDeletion(object);
3316
3317                                 } else if (object) {
3318                                         /* It's either a data chunk in a live file or
3319                                          * an ObjectHeader, so we're interested in it.
3320                                          * NB Need to keep the ObjectHeaders of deleted files
3321                                          * until the whole file has been deleted off
3322                                          */
3323                                         tags.serialNumber++;
3324
3325                                         dev->nGCCopies++;
3326
3327                                         if (tags.chunkId == 0) {
3328                                                 /* It is an object Id,
3329                                                  * We need to nuke the shrinkheader flags first
3330                                                  * Also need to clean up shadowing.
3331                                                  * We no longer want the shrinkHeader flag since its work is done
3332                                                  * and if it is left in place it will mess up scanning.
3333                                                  */
3334
3335                                                 yaffs_ObjectHeader *oh;
3336                                                 oh = (yaffs_ObjectHeader *)buffer;
3337                                                 oh->isShrink = 0;
3338                                                 tags.extraIsShrinkHeader = 0;
3339                                                 oh->shadowsObject = 0;
3340                                                 oh->inbandShadowsObject = 0;
3341                                                 if(object->variantType == YAFFS_OBJECT_TYPE_FILE)
3342                                                         oh->fileSize = object->variant.fileVariant.fileSize;
3343                                                 tags.extraShadows = 0;
3344
3345                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3346                                                 newChunk =
3347                                                     yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3348                                         } else
3349                                                 newChunk =
3350                                                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3351
3352                                         if (newChunk < 0) {
3353                                                 retVal = YAFFS_FAIL;
3354                                         } else {
3355
3356                                                 /* Ok, now fix up the Tnodes etc. */
3357
3358                                                 if (tags.chunkId == 0) {
3359                                                         /* It's a header */
3360                                                         object->hdrChunk =  newChunk;
3361                                                         object->serial =   tags.serialNumber;
3362                                                 } else {
3363                                                         /* It's a data chunk */
3364                                                         int ok;
3365                                                         ok = yaffs_PutChunkIntoFile
3366                                                             (object,
3367                                                              tags.chunkId,
3368                                                              newChunk, 0);