d77ee4745d79e29d1e18ceeafc57a2b591c38a66
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2010 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 #include "yportenv.h"
14 #include "yaffs_trace.h"
15
16 #include "yaffsinterface.h"
17 #include "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
20
21 #include "yaffs_tagscompat.h"
22 #ifndef CONFIG_YAFFS_USE_OWN_SORT
23 #include "yaffs_qsort.h"
24 #endif
25 #include "yaffs_nand.h"
26
27 #include "yaffs_checkptrw.h"
28
29 #include "yaffs_nand.h"
30 #include "yaffs_packedtags2.h"
31
32
33 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
34 #define YAFFS_GC_GOOD_ENOUGH 2
35 #define YAFFS_GC_PASSIVE_THRESHOLD 4
36 #define YAFFS_SMALL_HOLE_THRESHOLD 3
37
38 #include "yaffs_ecc.h"
39
40
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
44                 int erasedOk);
45 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
46                                 const __u8 *data,
47                                 const yaffs_ExtendedTags *tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
49                                 const yaffs_ExtendedTags *tags);
50
51 /* Other local prototypes */
52 static void yaffs_UpdateParent(yaffs_Object *obj);
53 static int yaffs_UnlinkObject(yaffs_Object *obj);
54 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
55
56 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
57
58 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
59                                         const __u8 *buffer,
60                                         yaffs_ExtendedTags *tags,
61                                         int useReserve);
62 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
63                                 int chunkInNAND, int inScan);
64
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66                                         yaffs_ObjectType type);
67 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
68                                 yaffs_Object *obj);
69 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
70                                 int force, int isShrink, int shadows);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
74                         int chunkOffset, int *limit);
75 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
76
77 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
78
79
80 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
81                                 int chunkInNAND);
82
83 static int yaffs_UnlinkWorker(yaffs_Object *obj);
84
85 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
86                         int chunkInObject);
87
88 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
89                                 yaffs_BlockInfo **blockUsedPtr);
90
91 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
92
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
94
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
96 #ifdef YAFFS_PARANOID
97 static int yaffs_CheckFileSanity(yaffs_Object *in);
98 #else
99 #define yaffs_CheckFileSanity(in)
100 #endif
101
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
104
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
106
107 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
108                                 yaffs_ExtendedTags *tags);
109
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
111                 unsigned pos);
112 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
113                                         yaffs_FileStructure *fStruct,
114                                         __u32 chunkId);
115
116 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize);
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 void yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1060 {
1061         int i;
1062         unsigned seq;
1063         unsigned blockNo = 0;
1064         yaffs_BlockInfo *b;
1065
1066         if(!dev->param.isYaffs2)
1067                 return;
1068
1069         /* Find the oldest dirty sequence number. */
1070         seq = dev->sequenceNumber + 1;
1071         b = dev->blockInfo;
1072         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1073                 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1074                         (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1075                         b->sequenceNumber < seq) {
1076                         seq = b->sequenceNumber;
1077                         blockNo = i;
1078                 }
1079                 b++;
1080         }
1081
1082         if(blockNo){
1083                 dev->oldestDirtySequence = seq;
1084                 dev->oldestDirtyBlock = blockNo;
1085         }
1086
1087 }
1088
1089
1090 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1091 {
1092         if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1093                 yaffs_CalcOldestDirtySequence(dev);
1094 }
1095
1096 /*
1097  * yaffs_ClearOldestDirtySequence()
1098  * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1099  * becomes invalid). If the value matches the oldest then we clear 
1100  * dev->oldestDirtySequence to force its recomputation.
1101  */
1102 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1103 {
1104
1105         if(!dev->param.isYaffs2)
1106                 return;
1107
1108         if(!bi || bi->sequenceNumber == dev->oldestDirtySequence){
1109                 dev->oldestDirtySequence = 0;
1110                 dev->oldestDirtyBlock = 0;
1111         }
1112 }
1113
1114 /*
1115  * yaffs_UpdateOldestDirtySequence()
1116  * Update the oldest dirty sequence number whenever we dirty a block.
1117  * Only do this if the oldestDirtySequence is actually being tracked.
1118  */
1119 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, unsigned blockNo, yaffs_BlockInfo *bi)
1120 {
1121         if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1122                 if(dev->oldestDirtySequence > bi->sequenceNumber){
1123                         dev->oldestDirtySequence = bi->sequenceNumber;
1124                         dev->oldestDirtyBlock = blockNo;
1125                 }
1126         }
1127 }
1128  
1129 /*
1130  * Block retiring for handling a broken block.
1131  */
1132
1133 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1134 {
1135         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1136
1137         yaffs_InvalidateCheckpoint(dev);
1138         
1139         yaffs_ClearOldestDirtySequence(dev,bi);
1140
1141         if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1142                 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1143                         T(YAFFS_TRACE_ALWAYS, (TSTR(
1144                                 "yaffs: Failed to mark bad and erase block %d"
1145                                 TENDSTR), blockInNAND));
1146                 } else {
1147                         yaffs_ExtendedTags tags;
1148                         int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1149
1150                         __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1151
1152                         memset(buffer, 0xff, dev->nDataBytesPerChunk);
1153                         yaffs_InitialiseTags(&tags);
1154                         tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1155                         if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1156                                 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1157                                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1158                                         TCONT("write bad block marker to block %d")
1159                                         TENDSTR), blockInNAND));
1160
1161                         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1162                 }
1163         }
1164
1165         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1166         bi->gcPrioritise = 0;
1167         bi->needsRetiring = 0;
1168
1169         dev->nRetiredBlocks++;
1170 }
1171
1172 /*
1173  * Functions for robustisizing TODO
1174  *
1175  */
1176
1177 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1178                                 const __u8 *data,
1179                                 const yaffs_ExtendedTags *tags)
1180 {
1181         dev=dev;
1182         chunkInNAND=chunkInNAND;
1183         data=data;
1184         tags=tags;
1185 }
1186
1187 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1188                                 const yaffs_ExtendedTags *tags)
1189 {
1190         dev=dev;
1191         chunkInNAND=chunkInNAND;
1192         tags=tags;
1193 }
1194
1195 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1196 {
1197         if (!bi->gcPrioritise) {
1198                 bi->gcPrioritise = 1;
1199                 dev->hasPendingPrioritisedGCs = 1;
1200                 bi->chunkErrorStrikes++;
1201
1202                 if (bi->chunkErrorStrikes > 3) {
1203                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1204                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1205
1206                 }
1207         }
1208 }
1209
1210 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1211                 int erasedOk)
1212 {
1213         int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1214         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1215
1216         yaffs_HandleChunkError(dev, bi);
1217
1218         if (erasedOk) {
1219                 /* Was an actual write failure, so mark the block for retirement  */
1220                 bi->needsRetiring = 1;
1221                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1222                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1223         }
1224
1225         /* Delete the chunk */
1226         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1227         yaffs_SkipRestOfBlock(dev);
1228 }
1229
1230
1231 /*---------------- Name handling functions ------------*/
1232
1233 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1234 {
1235         __u16 sum = 0;
1236         __u16 i = 1;
1237
1238         const YUCHAR *bname = (const YUCHAR *) name;
1239         if (bname) {
1240                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1241
1242 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1243                         sum += yaffs_toupper(*bname) * i;
1244 #else
1245                         sum += (*bname) * i;
1246 #endif
1247                         i++;
1248                         bname++;
1249                 }
1250         }
1251         return sum;
1252 }
1253
1254 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1255 {
1256 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1257         memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1258         if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1259                 yaffs_strcpy(obj->shortName, name);
1260         else
1261                 obj->shortName[0] = _Y('\0');
1262 #endif
1263         obj->sum = yaffs_CalcNameSum(name);
1264 }
1265
1266 /*-------------------- TNODES -------------------
1267
1268  * List of spare tnodes
1269  * The list is hooked together using the first pointer
1270  * in the tnode.
1271  */
1272
1273 /* yaffs_CreateTnodes creates a bunch more tnodes and
1274  * adds them to the tnode free list.
1275  * Don't use this function directly
1276  */
1277 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1278 {
1279         int tnodeSize;
1280         /* Calculate the tnode size in bytes for variable width tnode support.
1281          * Must be a multiple of 32-bits  */
1282         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1283
1284         if (tnodeSize < sizeof(yaffs_Tnode))
1285                 tnodeSize = sizeof(yaffs_Tnode);
1286         return tnodeSize;
1287 }
1288
1289 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1290 {
1291         int i;
1292         int tnodeSize = yaffs_CalcTnodeSize(dev);
1293         yaffs_Tnode *newTnodes;
1294         __u8 *mem;
1295         yaffs_Tnode *curr;
1296         yaffs_Tnode *next;
1297         yaffs_TnodeList *tnl;
1298
1299         if (nTnodes < 1)
1300                 return YAFFS_OK;
1301
1302
1303         /* make these things */
1304
1305         newTnodes = YMALLOC(nTnodes * tnodeSize);
1306         mem = (__u8 *)newTnodes;
1307
1308         if (!newTnodes) {
1309                 T(YAFFS_TRACE_ERROR,
1310                         (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1311                 return YAFFS_FAIL;
1312         }
1313
1314         /* Hook them into the free list */
1315 #if 0
1316         for (i = 0; i < nTnodes - 1; i++) {
1317                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1318 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1319                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1320 #endif
1321         }
1322
1323         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1324 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1325         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1326 #endif
1327         dev->freeTnodes = newTnodes;
1328 #else
1329         /* New hookup for wide tnodes */
1330         for (i = 0; i < nTnodes - 1; i++) {
1331                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1332                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1333                 curr->internal[0] = next;
1334         }
1335
1336         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1337         curr->internal[0] = dev->freeTnodes;
1338         dev->freeTnodes = (yaffs_Tnode *)mem;
1339
1340 #endif
1341
1342
1343         dev->nFreeTnodes += nTnodes;
1344         dev->nTnodesCreated += nTnodes;
1345
1346         /* Now add this bunch of tnodes to a list for freeing up.
1347          * NB If we can't add this to the management list it isn't fatal
1348          * but it just means we can't free this bunch of tnodes later.
1349          */
1350
1351         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1352         if (!tnl) {
1353                 T(YAFFS_TRACE_ERROR,
1354                   (TSTR
1355                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1356                    return YAFFS_FAIL;
1357         } else {
1358                 tnl->tnodes = newTnodes;
1359                 tnl->next = dev->allocatedTnodeList;
1360                 dev->allocatedTnodeList = tnl;
1361         }
1362
1363         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1364
1365         return YAFFS_OK;
1366 }
1367
1368 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1369
1370 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1371 {
1372         yaffs_Tnode *tn = NULL;
1373
1374 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1375         tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1376         if(tn)
1377                 dev->nTnodesCreated++;
1378 #else
1379         /* If there are none left make more */
1380         if (!dev->freeTnodes)
1381                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1382
1383         if (dev->freeTnodes) {
1384                 tn = dev->freeTnodes;
1385 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1386                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1387                         /* Hoosterman, this thing looks like it isn't in the list */
1388                         T(YAFFS_TRACE_ALWAYS,
1389                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1390                 }
1391 #endif
1392                 dev->freeTnodes = dev->freeTnodes->internal[0];
1393                 dev->nFreeTnodes--;
1394         }
1395 #endif
1396         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1397
1398         return tn;
1399 }
1400
1401 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1402 {
1403         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1404         int tnodeSize = yaffs_CalcTnodeSize(dev);
1405
1406         if (tn)
1407                 memset(tn, 0, tnodeSize);
1408
1409         return tn;
1410 }
1411
1412 /* FreeTnode frees up a tnode and puts it back on the free list */
1413 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1414 {
1415         if (tn) {
1416 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1417                 YFREE(tn);
1418                 dev->nTnodesCreated--;
1419 #else
1420 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1421                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1422                         /* Hoosterman, this thing looks like it is already in the list */
1423                         T(YAFFS_TRACE_ALWAYS,
1424                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1425                 }
1426                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1427 #endif
1428                 tn->internal[0] = dev->freeTnodes;
1429                 dev->freeTnodes = tn;
1430                 dev->nFreeTnodes++;
1431 #endif
1432         }
1433         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1434 }
1435
1436 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1437 {
1438         /* Free the list of allocated tnodes */
1439         yaffs_TnodeList *tmp;
1440
1441         while (dev->allocatedTnodeList) {
1442                 tmp = dev->allocatedTnodeList->next;
1443
1444                 YFREE(dev->allocatedTnodeList->tnodes);
1445                 YFREE(dev->allocatedTnodeList);
1446                 dev->allocatedTnodeList = tmp;
1447
1448         }
1449
1450         dev->freeTnodes = NULL;
1451         dev->nFreeTnodes = 0;
1452         dev->nTnodesCreated = 0;
1453 }
1454
1455 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1456 {
1457         dev->allocatedTnodeList = NULL;
1458         dev->freeTnodes = NULL;
1459         dev->nFreeTnodes = 0;
1460         dev->nTnodesCreated = 0;
1461 }
1462
1463
1464 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1465                 unsigned val)
1466 {
1467         __u32 *map = (__u32 *)tn;
1468         __u32 bitInMap;
1469         __u32 bitInWord;
1470         __u32 wordInMap;
1471         __u32 mask;
1472
1473         pos &= YAFFS_TNODES_LEVEL0_MASK;
1474         val >>= dev->chunkGroupBits;
1475
1476         bitInMap = pos * dev->tnodeWidth;
1477         wordInMap = bitInMap / 32;
1478         bitInWord = bitInMap & (32 - 1);
1479
1480         mask = dev->tnodeMask << bitInWord;
1481
1482         map[wordInMap] &= ~mask;
1483         map[wordInMap] |= (mask & (val << bitInWord));
1484
1485         if (dev->tnodeWidth > (32 - bitInWord)) {
1486                 bitInWord = (32 - bitInWord);
1487                 wordInMap++;;
1488                 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1489                 map[wordInMap] &= ~mask;
1490                 map[wordInMap] |= (mask & (val >> bitInWord));
1491         }
1492 }
1493
1494 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1495                 unsigned pos)
1496 {
1497         __u32 *map = (__u32 *)tn;
1498         __u32 bitInMap;
1499         __u32 bitInWord;
1500         __u32 wordInMap;
1501         __u32 val;
1502
1503         pos &= YAFFS_TNODES_LEVEL0_MASK;
1504
1505         bitInMap = pos * dev->tnodeWidth;
1506         wordInMap = bitInMap / 32;
1507         bitInWord = bitInMap & (32 - 1);
1508
1509         val = map[wordInMap] >> bitInWord;
1510
1511         if      (dev->tnodeWidth > (32 - bitInWord)) {
1512                 bitInWord = (32 - bitInWord);
1513                 wordInMap++;;
1514                 val |= (map[wordInMap] << bitInWord);
1515         }
1516
1517         val &= dev->tnodeMask;
1518         val <<= dev->chunkGroupBits;
1519
1520         return val;
1521 }
1522
1523 /* ------------------- End of individual tnode manipulation -----------------*/
1524
1525 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1526  * The look up tree is represented by the top tnode and the number of topLevel
1527  * in the tree. 0 means only the level 0 tnode is in the tree.
1528  */
1529
1530 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1531 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1532                                         yaffs_FileStructure *fStruct,
1533                                         __u32 chunkId)
1534 {
1535         yaffs_Tnode *tn = fStruct->top;
1536         __u32 i;
1537         int requiredTallness;
1538         int level = fStruct->topLevel;
1539
1540         dev=dev;
1541
1542         /* Check sane level and chunk Id */
1543         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1544                 return NULL;
1545
1546         if (chunkId > YAFFS_MAX_CHUNK_ID)
1547                 return NULL;
1548
1549         /* First check we're tall enough (ie enough topLevel) */
1550
1551         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1552         requiredTallness = 0;
1553         while (i) {
1554                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1555                 requiredTallness++;
1556         }
1557
1558         if (requiredTallness > fStruct->topLevel)
1559                 return NULL; /* Not tall enough, so we can't find it */
1560
1561         /* Traverse down to level 0 */
1562         while (level > 0 && tn) {
1563                 tn = tn->internal[(chunkId >>
1564                         (YAFFS_TNODES_LEVEL0_BITS +
1565                                 (level - 1) *
1566                                 YAFFS_TNODES_INTERNAL_BITS)) &
1567                         YAFFS_TNODES_INTERNAL_MASK];
1568                 level--;
1569         }
1570
1571         return tn;
1572 }
1573
1574 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1575  * This happens in two steps:
1576  *  1. If the tree isn't tall enough, then make it taller.
1577  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1578  *
1579  * Used when modifying the tree.
1580  *
1581  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1582  *  be plugged into the ttree.
1583  */
1584
1585 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1586                                         yaffs_FileStructure *fStruct,
1587                                         __u32 chunkId,
1588                                         yaffs_Tnode *passedTn)
1589 {
1590         int requiredTallness;
1591         int i;
1592         int l;
1593         yaffs_Tnode *tn;
1594
1595         __u32 x;
1596
1597
1598         /* Check sane level and page Id */
1599         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1600                 return NULL;
1601
1602         if (chunkId > YAFFS_MAX_CHUNK_ID)
1603                 return NULL;
1604
1605         /* First check we're tall enough (ie enough topLevel) */
1606
1607         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1608         requiredTallness = 0;
1609         while (x) {
1610                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1611                 requiredTallness++;
1612         }
1613
1614
1615         if (requiredTallness > fStruct->topLevel) {
1616                 /* Not tall enough, gotta make the tree taller */
1617                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1618
1619                         tn = yaffs_GetTnode(dev);
1620
1621                         if (tn) {
1622                                 tn->internal[0] = fStruct->top;
1623                                 fStruct->top = tn;
1624                                 fStruct->topLevel++;
1625                         } else {
1626                                 T(YAFFS_TRACE_ERROR,
1627                                         (TSTR("yaffs: no more tnodes" TENDSTR)));
1628                                 return NULL;
1629                         }
1630                 }
1631         }
1632
1633         /* Traverse down to level 0, adding anything we need */
1634
1635         l = fStruct->topLevel;
1636         tn = fStruct->top;
1637
1638         if (l > 0) {
1639                 while (l > 0 && tn) {
1640                         x = (chunkId >>
1641                              (YAFFS_TNODES_LEVEL0_BITS +
1642                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1643                             YAFFS_TNODES_INTERNAL_MASK;
1644
1645
1646                         if ((l > 1) && !tn->internal[x]) {
1647                                 /* Add missing non-level-zero tnode */
1648                                 tn->internal[x] = yaffs_GetTnode(dev);
1649                                 if(!tn->internal[x])
1650                                         return NULL;
1651                         } else if (l == 1) {
1652                                 /* Looking from level 1 at level 0 */
1653                                 if (passedTn) {
1654                                         /* If we already have one, then release it.*/
1655                                         if (tn->internal[x])
1656                                                 yaffs_FreeTnode(dev, tn->internal[x]);
1657                                         tn->internal[x] = passedTn;
1658
1659                                 } else if (!tn->internal[x]) {
1660                                         /* Don't have one, none passed in */
1661                                         tn->internal[x] = yaffs_GetTnode(dev);
1662                                         if(!tn->internal[x])
1663                                                 return NULL;
1664                                 }
1665                         }
1666
1667                         tn = tn->internal[x];
1668                         l--;
1669                 }
1670         } else {
1671                 /* top is level 0 */
1672                 if (passedTn) {
1673                         memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1674                         yaffs_FreeTnode(dev, passedTn);
1675                 }
1676         }
1677
1678         return tn;
1679 }
1680
1681 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1682                                 yaffs_ExtendedTags *tags, int objectId,
1683                                 int chunkInInode)
1684 {
1685         int j;
1686
1687         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1688                 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1689                                 theChunk % dev->param.nChunksPerBlock)) {
1690                         
1691                         if(dev->chunkGroupSize == 1)
1692                                 return theChunk;
1693                         else {
1694                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1695                                                                 tags);
1696                                 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1697                                         /* found it; */
1698                                         return theChunk;
1699                                 }
1700                         }
1701                 }
1702                 theChunk++;
1703         }
1704         return -1;
1705 }
1706
1707
1708 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1709  * chunks and tnodes in the file
1710  * Returns 1 if the tree was deleted.
1711  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1712  */
1713
1714 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1715                               int chunkOffset, int *limit)
1716 {
1717         int i;
1718         int chunkInInode;
1719         int theChunk;
1720         yaffs_ExtendedTags tags;
1721         int foundChunk;
1722         yaffs_Device *dev = in->myDev;
1723
1724         int allDone = 1;
1725
1726         if (tn) {
1727                 if (level > 0) {
1728                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1729                              i--) {
1730                                 if (tn->internal[i]) {
1731                                         if (limit && (*limit) < 0) {
1732                                                 allDone = 0;
1733                                         } else {
1734                                                 allDone =
1735                                                         yaffs_DeleteWorker(in,
1736                                                                 tn->
1737                                                                 internal
1738                                                                 [i],
1739                                                                 level -
1740                                                                 1,
1741                                                                 (chunkOffset
1742                                                                         <<
1743                                                                         YAFFS_TNODES_INTERNAL_BITS)
1744                                                                 + i,
1745                                                                 limit);
1746                                         }
1747                                         if (allDone) {
1748                                                 yaffs_FreeTnode(dev,
1749                                                                 tn->
1750                                                                 internal[i]);
1751                                                 tn->internal[i] = NULL;
1752                                         }
1753                                 }
1754                         }
1755                         return (allDone) ? 1 : 0;
1756                 } else if (level == 0) {
1757                         int hitLimit = 0;
1758
1759                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1760                                         i--) {
1761                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1762                                 if (theChunk) {
1763
1764                                         chunkInInode = (chunkOffset <<
1765                                                 YAFFS_TNODES_LEVEL0_BITS) + i;
1766
1767                                         foundChunk =
1768                                                 yaffs_FindChunkInGroup(dev,
1769                                                                 theChunk,
1770                                                                 &tags,
1771                                                                 in->objectId,
1772                                                                 chunkInInode);
1773
1774                                         if (foundChunk > 0) {
1775                                                 yaffs_DeleteChunk(dev,
1776                                                                   foundChunk, 1,
1777                                                                   __LINE__);
1778                                                 in->nDataChunks--;
1779                                                 if (limit) {
1780                                                         *limit = *limit - 1;
1781                                                         if (*limit <= 0)
1782                                                                 hitLimit = 1;
1783                                                 }
1784
1785                                         }
1786
1787                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1788                                 }
1789
1790                         }
1791                         return (i < 0) ? 1 : 0;
1792
1793                 }
1794
1795         }
1796
1797         return 1;
1798
1799 }
1800
1801 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1802 {
1803         yaffs_BlockInfo *theBlock;
1804         unsigned blockNo;
1805
1806         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1807
1808         blockNo =  chunk / dev->param.nChunksPerBlock;
1809         theBlock = yaffs_GetBlockInfo(dev, blockNo);
1810         if (theBlock) {
1811                 theBlock->softDeletions++;
1812                 dev->nFreeChunks++;
1813                 yaffs_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1814         }
1815 }
1816
1817 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1818  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1819  * of the tnode.
1820  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1821  */
1822
1823 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1824                                   __u32 level, int chunkOffset)
1825 {
1826         int i;
1827         int theChunk;
1828         int allDone = 1;
1829         yaffs_Device *dev = in->myDev;
1830
1831         if (tn) {
1832                 if (level > 0) {
1833
1834                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1835                              i--) {
1836                                 if (tn->internal[i]) {
1837                                         allDone =
1838                                             yaffs_SoftDeleteWorker(in,
1839                                                                    tn->
1840                                                                    internal[i],
1841                                                                    level - 1,
1842                                                                    (chunkOffset
1843                                                                     <<
1844                                                                     YAFFS_TNODES_INTERNAL_BITS)
1845                                                                    + i);
1846                                         if (allDone) {
1847                                                 yaffs_FreeTnode(dev,
1848                                                                 tn->
1849                                                                 internal[i]);
1850                                                 tn->internal[i] = NULL;
1851                                         } else {
1852                                                 /* Hoosterman... how could this happen? */
1853                                         }
1854                                 }
1855                         }
1856                         return (allDone) ? 1 : 0;
1857                 } else if (level == 0) {
1858
1859                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1860                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1861                                 if (theChunk) {
1862                                         /* Note this does not find the real chunk, only the chunk group.
1863                                          * We make an assumption that a chunk group is not larger than
1864                                          * a block.
1865                                          */
1866                                         yaffs_SoftDeleteChunk(dev, theChunk);
1867                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1868                                 }
1869
1870                         }
1871                         return 1;
1872
1873                 }
1874
1875         }
1876
1877         return 1;
1878
1879 }
1880
1881 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1882 {
1883         if (obj->deleted &&
1884             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1885                 if (obj->nDataChunks <= 0) {
1886                         /* Empty file with no duplicate object headers, just delete it immediately */
1887                         yaffs_FreeTnode(obj->myDev,
1888                                         obj->variant.fileVariant.top);
1889                         obj->variant.fileVariant.top = NULL;
1890                         T(YAFFS_TRACE_TRACING,
1891                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1892                            obj->objectId));
1893                         yaffs_DoGenericObjectDeletion(obj);
1894                 } else {
1895                         yaffs_SoftDeleteWorker(obj,
1896                                                obj->variant.fileVariant.top,
1897                                                obj->variant.fileVariant.
1898                                                topLevel, 0);
1899                         obj->softDeleted = 1;
1900                 }
1901         }
1902 }
1903
1904 /* Pruning removes any part of the file structure tree that is beyond the
1905  * bounds of the file (ie that does not point to chunks).
1906  *
1907  * A file should only get pruned when its size is reduced.
1908  *
1909  * Before pruning, the chunks must be pulled from the tree and the
1910  * level 0 tnode entries must be zeroed out.
1911  * Could also use this for file deletion, but that's probably better handled
1912  * by a special case.
1913  *
1914  * This function is recursive. For levels > 0 the function is called again on
1915  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1916  * If there is no data in a subtree then it is pruned.
1917  */
1918
1919 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1920                                 __u32 level, int del0)
1921 {
1922         int i;
1923         int hasData;
1924
1925         if (tn) {
1926                 hasData = 0;
1927
1928                 if(level > 0){
1929                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1930                                 if (tn->internal[i]) {
1931                                         tn->internal[i] =
1932                                                 yaffs_PruneWorker(dev, tn->internal[i],
1933                                                         level - 1,
1934                                                         (i == 0) ? del0 : 1);
1935                                 }
1936
1937                                 if (tn->internal[i])
1938                                         hasData++;
1939                         }
1940                 } else {
1941                         int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1942                         __u32 *map = (__u32 *)tn;
1943
1944                         for(i = 0; !hasData && i < tnodeSize_u32; i++){
1945                                 if(map[i])
1946                                         hasData++;
1947                         }
1948                 }
1949
1950                 if (hasData == 0 && del0) {
1951                         /* Free and return NULL */
1952
1953                         yaffs_FreeTnode(dev, tn);
1954                         tn = NULL;
1955                 }
1956
1957         }
1958
1959         return tn;
1960
1961 }
1962
1963 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1964                                 yaffs_FileStructure *fStruct)
1965 {
1966         int i;
1967         int hasData;
1968         int done = 0;
1969         yaffs_Tnode *tn;
1970
1971         if (fStruct->topLevel > 0) {
1972                 fStruct->top =
1973                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1974
1975                 /* Now we have a tree with all the non-zero branches NULL but the height
1976                  * is the same as it was.
1977                  * Let's see if we can trim internal tnodes to shorten the tree.
1978                  * We can do this if only the 0th element in the tnode is in use
1979                  * (ie all the non-zero are NULL)
1980                  */
1981
1982                 while (fStruct->topLevel && !done) {
1983                         tn = fStruct->top;
1984
1985                         hasData = 0;
1986                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1987                                 if (tn->internal[i])
1988                                         hasData++;
1989                         }
1990
1991                         if (!hasData) {
1992                                 fStruct->top = tn->internal[0];
1993                                 fStruct->topLevel--;
1994                                 yaffs_FreeTnode(dev, tn);
1995                         } else {
1996                                 done = 1;
1997                         }
1998                 }
1999         }
2000
2001         return YAFFS_OK;
2002 }
2003
2004 /*-------------------- End of File Structure functions.-------------------*/
2005
2006 /* yaffs_CreateFreeObjects creates a bunch more objects and
2007  * adds them to the object free list.
2008  */
2009 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2010 {
2011         int i;
2012         yaffs_Object *newObjects;
2013         yaffs_ObjectList *list;
2014
2015         if (nObjects < 1)
2016                 return YAFFS_OK;
2017
2018         /* make these things */
2019         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2020         list = YMALLOC(sizeof(yaffs_ObjectList));
2021
2022         if (!newObjects || !list) {
2023                 if (newObjects){
2024                         YFREE(newObjects);
2025                         newObjects = NULL;
2026                 }
2027                 if (list){
2028                         YFREE(list);
2029                         list = NULL;
2030                 }
2031                 T(YAFFS_TRACE_ALLOCATE,
2032                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2033                 return YAFFS_FAIL;
2034         }
2035
2036         /* Hook them into the free list */
2037         for (i = 0; i < nObjects - 1; i++) {
2038                 newObjects[i].siblings.next =
2039                                 (struct ylist_head *)(&newObjects[i + 1]);
2040         }
2041
2042         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2043         dev->freeObjects = newObjects;
2044         dev->nFreeObjects += nObjects;
2045         dev->nObjectsCreated += nObjects;
2046
2047         /* Now add this bunch of Objects to a list for freeing up. */
2048
2049         list->objects = newObjects;
2050         list->next = dev->allocatedObjectList;
2051         dev->allocatedObjectList = list;
2052
2053         return YAFFS_OK;
2054 }
2055
2056
2057 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2058 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2059 {
2060         yaffs_Object *tn = NULL;
2061
2062 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2063         tn = YMALLOC(sizeof(yaffs_Object));
2064         if(tn)
2065                 dev->nObjectsCreated++;
2066 #else
2067         /* If there are none left make more */
2068         if (!dev->freeObjects)
2069                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2070
2071         if (dev->freeObjects) {
2072                 tn = dev->freeObjects;
2073                 dev->freeObjects =
2074                         (yaffs_Object *) (dev->freeObjects->siblings.next);
2075                 dev->nFreeObjects--;
2076         }
2077 #endif
2078         if (tn) {
2079                 /* Now sweeten it up... */
2080
2081                 memset(tn, 0, sizeof(yaffs_Object));
2082                 tn->beingCreated = 1;
2083
2084                 tn->myDev = dev;
2085                 tn->hdrChunk = 0;
2086                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2087                 YINIT_LIST_HEAD(&(tn->hardLinks));
2088                 YINIT_LIST_HEAD(&(tn->hashLink));
2089                 YINIT_LIST_HEAD(&tn->siblings);
2090
2091
2092                 /* Now make the directory sane */
2093                 if (dev->rootDir) {
2094                         tn->parent = dev->rootDir;
2095                         ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2096                 }
2097
2098                 /* Add it to the lost and found directory.
2099                  * NB Can't put root or lostNFound in lostNFound so
2100                  * check if lostNFound exists first
2101                  */
2102                 if (dev->lostNFoundDir)
2103                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2104
2105                 tn->beingCreated = 0;
2106         }
2107
2108         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2109
2110         return tn;
2111 }
2112
2113 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2114                                                __u32 mode)
2115 {
2116
2117         yaffs_Object *obj =
2118             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2119         if (obj) {
2120                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
2121                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2122                 obj->unlinkAllowed = 0; /* ... or unlink it */
2123                 obj->deleted = 0;
2124                 obj->unlinked = 0;
2125                 obj->yst_mode = mode;
2126                 obj->myDev = dev;
2127                 obj->hdrChunk = 0;      /* Not a valid chunk. */
2128         }
2129
2130         return obj;
2131
2132 }
2133
2134 static void yaffs_UnhashObject(yaffs_Object *tn)
2135 {
2136         int bucket;
2137         yaffs_Device *dev = tn->myDev;
2138
2139         /* If it is still linked into the bucket list, free from the list */
2140         if (!ylist_empty(&tn->hashLink)) {
2141                 ylist_del_init(&tn->hashLink);
2142                 bucket = yaffs_HashFunction(tn->objectId);
2143                 dev->objectBucket[bucket].count--;
2144         }
2145 }
2146
2147 /*  FreeObject frees up a Object and puts it back on the free list */
2148 static void yaffs_FreeObject(yaffs_Object *tn)
2149 {
2150         yaffs_Device *dev = tn->myDev;
2151
2152         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2153
2154         if (!tn)
2155                 YBUG();
2156         if (tn->parent)
2157                 YBUG();
2158         if (!ylist_empty(&tn->siblings))
2159                 YBUG();
2160
2161
2162         if (tn->myInode) {
2163                 /* We're still hooked up to a cached inode.
2164                  * Don't delete now, but mark for later deletion
2165                  */
2166                 tn->deferedFree = 1;
2167                 return;
2168         }
2169
2170         yaffs_UnhashObject(tn);
2171
2172 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2173         YFREE(tn);
2174         dev->nObjectsCreated--;
2175         tn = NULL;
2176 #else
2177         /* Link into the free list. */
2178         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2179         dev->freeObjects = tn;
2180         dev->nFreeObjects++;
2181 #endif
2182         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2183 }
2184
2185
2186 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2187 {
2188         if (obj->deferedFree)
2189                 yaffs_FreeObject(obj);
2190 }
2191
2192
2193 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2194 {
2195         /* Free the list of allocated Objects */
2196
2197         yaffs_ObjectList *tmp;
2198
2199         while (dev->allocatedObjectList) {
2200                 tmp = dev->allocatedObjectList->next;
2201                 YFREE(dev->allocatedObjectList->objects);
2202                 YFREE(dev->allocatedObjectList);
2203
2204                 dev->allocatedObjectList = tmp;
2205         }
2206
2207         dev->freeObjects = NULL;
2208         dev->nFreeObjects = 0;
2209         dev->nObjectsCreated = 0;
2210 }
2211
2212 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2213 {
2214         int i;
2215
2216         dev->allocatedObjectList = NULL;
2217         dev->freeObjects = NULL;
2218         dev->nFreeObjects = 0;
2219
2220         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2221                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2222                 dev->objectBucket[i].count = 0;
2223         }
2224 }
2225
2226 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2227 {
2228         int i;
2229         int l = 999;
2230         int lowest = 999999;
2231
2232
2233         /* Search for the shortest list or one that
2234          * isn't too long.
2235          */
2236
2237         for (i = 0; i < 10 && lowest > 4; i++) {
2238                 dev->bucketFinder++;
2239                 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2240                 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2241                         lowest = dev->objectBucket[dev->bucketFinder].count;
2242                         l = dev->bucketFinder;
2243                 }
2244
2245         }
2246
2247         return l;
2248 }
2249
2250 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2251 {
2252         int bucket = yaffs_FindNiceObjectBucket(dev);
2253
2254         /* Now find an object value that has not already been taken
2255          * by scanning the list.
2256          */
2257
2258         int found = 0;
2259         struct ylist_head *i;
2260
2261         __u32 n = (__u32) bucket;
2262
2263         /* yaffs_CheckObjectHashSanity();  */
2264
2265         while (!found) {
2266                 found = 1;
2267                 n += YAFFS_NOBJECT_BUCKETS;
2268                 if (1 || dev->objectBucket[bucket].count > 0) {
2269                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2270                                 /* If there is already one in the list */
2271                                 if (i && ylist_entry(i, yaffs_Object,
2272                                                 hashLink)->objectId == n) {
2273                                         found = 0;
2274                                 }
2275                         }
2276                 }
2277         }
2278
2279         return n;
2280 }
2281
2282 static void yaffs_HashObject(yaffs_Object *in)
2283 {
2284         int bucket = yaffs_HashFunction(in->objectId);
2285         yaffs_Device *dev = in->myDev;
2286
2287         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2288         dev->objectBucket[bucket].count++;
2289 }
2290
2291 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2292 {
2293         int bucket = yaffs_HashFunction(number);
2294         struct ylist_head *i;
2295         yaffs_Object *in;
2296
2297         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2298                 /* Look if it is in the list */
2299                 if (i) {
2300                         in = ylist_entry(i, yaffs_Object, hashLink);
2301                         if (in->objectId == number) {
2302
2303                                 /* Don't tell the VFS about this one if it is defered free */
2304                                 if (in->deferedFree)
2305                                         return NULL;
2306
2307                                 return in;
2308                         }
2309                 }
2310         }
2311
2312         return NULL;
2313 }
2314
2315 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2316                                     yaffs_ObjectType type)
2317 {
2318         yaffs_Object *theObject=NULL;
2319         yaffs_Tnode *tn = NULL;
2320
2321         if (number < 0)
2322                 number = yaffs_CreateNewObjectNumber(dev);
2323
2324         if (type == YAFFS_OBJECT_TYPE_FILE) {
2325                 tn = yaffs_GetTnode(dev);
2326                 if (!tn)
2327                         return NULL;
2328         }
2329
2330         theObject = yaffs_AllocateEmptyObject(dev);
2331         if (!theObject){
2332                 if(tn)
2333                         yaffs_FreeTnode(dev,tn);
2334                 return NULL;
2335         }
2336
2337
2338         if (theObject) {
2339                 theObject->fake = 0;
2340                 theObject->renameAllowed = 1;
2341                 theObject->unlinkAllowed = 1;
2342                 theObject->objectId = number;
2343                 yaffs_HashObject(theObject);
2344                 theObject->variantType = type;
2345 #ifdef CONFIG_YAFFS_WINCE
2346                 yfsd_WinFileTimeNow(theObject->win_atime);
2347                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2348                     theObject->win_atime[0];
2349                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2350                     theObject->win_atime[1];
2351
2352 #else
2353
2354                 theObject->yst_atime = theObject->yst_mtime =
2355                     theObject->yst_ctime = Y_CURRENT_TIME;
2356 #endif
2357                 switch (type) {
2358                 case YAFFS_OBJECT_TYPE_FILE:
2359                         theObject->variant.fileVariant.fileSize = 0;
2360                         theObject->variant.fileVariant.scannedFileSize = 0;
2361                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2362                         theObject->variant.fileVariant.topLevel = 0;
2363                         theObject->variant.fileVariant.top = tn;
2364                         break;
2365                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2366                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2367                                         children);
2368                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2369                                         dirty);
2370                         break;
2371                 case YAFFS_OBJECT_TYPE_SYMLINK:
2372                 case YAFFS_OBJECT_TYPE_HARDLINK:
2373                 case YAFFS_OBJECT_TYPE_SPECIAL:
2374                         /* No action required */
2375                         break;
2376                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2377                         /* todo this should not happen */
2378                         break;
2379                 }
2380         }
2381
2382         return theObject;
2383 }
2384
2385 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2386                                                       int number,
2387                                                       yaffs_ObjectType type)
2388 {
2389         yaffs_Object *theObject = NULL;
2390
2391         if (number > 0)
2392                 theObject = yaffs_FindObjectByNumber(dev, number);
2393
2394         if (!theObject)
2395                 theObject = yaffs_CreateNewObject(dev, number, type);
2396
2397         return theObject;
2398
2399 }
2400
2401
2402 static YCHAR *yaffs_CloneString(const YCHAR *str)
2403 {
2404         YCHAR *newStr = NULL;
2405         int len;
2406
2407         if (!str)
2408                 str = _Y("");
2409
2410         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2411         newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2412         if (newStr){
2413                 yaffs_strncpy(newStr, str,len);
2414                 newStr[len] = 0;
2415         }
2416         return newStr;
2417
2418 }
2419
2420 /*
2421  * Mknod (create) a new object.
2422  * equivalentObject only has meaning for a hard link;
2423  * aliasString only has meaning for a symlink.
2424  * rdev only has meaning for devices (a subset of special objects)
2425  */
2426
2427 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2428                                        yaffs_Object *parent,
2429                                        const YCHAR *name,
2430                                        __u32 mode,
2431                                        __u32 uid,
2432                                        __u32 gid,
2433                                        yaffs_Object *equivalentObject,
2434                                        const YCHAR *aliasString, __u32 rdev)
2435 {
2436         yaffs_Object *in;
2437         YCHAR *str = NULL;
2438
2439         yaffs_Device *dev = parent->myDev;
2440
2441         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2442         if (yaffs_FindObjectByName(parent, name))
2443                 return NULL;
2444
2445         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2446                 str = yaffs_CloneString(aliasString);
2447                 if (!str)
2448                         return NULL;
2449         }
2450
2451         in = yaffs_CreateNewObject(dev, -1, type);
2452
2453         if (!in){
2454                 if(str)
2455                         YFREE(str);
2456                 return NULL;
2457         }
2458
2459
2460
2461
2462
2463         if (in) {
2464                 in->hdrChunk = 0;
2465                 in->valid = 1;
2466                 in->variantType = type;
2467
2468                 in->yst_mode = mode;
2469
2470 #ifdef CONFIG_YAFFS_WINCE
2471                 yfsd_WinFileTimeNow(in->win_atime);
2472                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2473                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2474
2475 #else
2476                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2477
2478                 in->yst_rdev = rdev;
2479                 in->yst_uid = uid;
2480                 in->yst_gid = gid;
2481 #endif
2482                 in->nDataChunks = 0;
2483
2484                 yaffs_SetObjectName(in, name);
2485                 in->dirty = 1;
2486
2487                 yaffs_AddObjectToDirectory(parent, in);
2488
2489                 in->myDev = parent->myDev;
2490
2491                 switch (type) {
2492                 case YAFFS_OBJECT_TYPE_SYMLINK:
2493                         in->variant.symLinkVariant.alias = str;
2494                         break;
2495                 case YAFFS_OBJECT_TYPE_HARDLINK:
2496                         in->variant.hardLinkVariant.equivalentObject =
2497                                 equivalentObject;
2498                         in->variant.hardLinkVariant.equivalentObjectId =
2499                                 equivalentObject->objectId;
2500                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2501                         break;
2502                 case YAFFS_OBJECT_TYPE_FILE:
2503                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2504                 case YAFFS_OBJECT_TYPE_SPECIAL:
2505                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2506                         /* do nothing */
2507                         break;
2508                 }
2509
2510                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2511                         /* Could not create the object header, fail the creation */
2512                         yaffs_DeleteObject(in);
2513                         in = NULL;
2514                 }
2515
2516                 yaffs_UpdateParent(parent);
2517         }
2518
2519         return in;
2520 }
2521
2522 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2523                         __u32 mode, __u32 uid, __u32 gid)
2524 {
2525         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2526                                 uid, gid, NULL, NULL, 0);
2527 }
2528
2529 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2530                                 __u32 mode, __u32 uid, __u32 gid)
2531 {
2532         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2533                                  mode, uid, gid, NULL, NULL, 0);
2534 }
2535
2536 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2537                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2538 {
2539         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2540                                  uid, gid, NULL, NULL, rdev);
2541 }
2542
2543 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2544                                 __u32 mode, __u32 uid, __u32 gid,
2545                                 const YCHAR *alias)
2546 {
2547         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2548                                 uid, gid, NULL, alias, 0);
2549 }
2550
2551 /* yaffs_Link returns the object id of the equivalent object.*/
2552 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2553                         yaffs_Object *equivalentObject)
2554 {
2555         /* Get the real object in case we were fed a hard link as an equivalent object */
2556         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2557
2558         if (yaffs_MknodObject
2559             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2560              equivalentObject, NULL, 0)) {
2561                 return equivalentObject;
2562         } else {
2563                 return NULL;
2564         }
2565
2566 }
2567
2568 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2569                                 const YCHAR *newName, int force, int shadows)
2570 {
2571         int unlinkOp;
2572         int deleteOp;
2573
2574         yaffs_Object *existingTarget;
2575
2576         if (newDir == NULL)
2577                 newDir = obj->parent;   /* use the old directory */
2578
2579         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2580                 T(YAFFS_TRACE_ALWAYS,
2581                   (TSTR
2582                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2583                     TENDSTR)));
2584                 YBUG();
2585         }
2586
2587         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2588         if (obj->myDev->param.isYaffs2)
2589                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2590         else
2591                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2592                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2593
2594         deleteOp = (newDir == obj->myDev->deletedDir);
2595
2596         existingTarget = yaffs_FindObjectByName(newDir, newName);
2597
2598         /* If the object is a file going into the unlinked directory,
2599          *   then it is OK to just stuff it in since duplicate names are allowed.
2600          *   else only proceed if the new name does not exist and if we're putting
2601          *   it into a directory.
2602          */
2603         if ((unlinkOp ||
2604              deleteOp ||
2605              force ||
2606              (shadows > 0) ||
2607              !existingTarget) &&
2608             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2609                 yaffs_SetObjectName(obj, newName);
2610                 obj->dirty = 1;
2611
2612                 yaffs_AddObjectToDirectory(newDir, obj);
2613
2614                 if (unlinkOp)
2615                         obj->unlinked = 1;
2616
2617                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2618                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2619                         return YAFFS_OK;
2620         }
2621
2622         return YAFFS_FAIL;
2623 }
2624
2625 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2626                 yaffs_Object *newDir, const YCHAR *newName)
2627 {
2628         yaffs_Object *obj = NULL;
2629         yaffs_Object *existingTarget = NULL;
2630         int force = 0;
2631         int result;
2632         yaffs_Device *dev;
2633
2634
2635         if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2636                 YBUG();
2637         if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2638                 YBUG();
2639
2640         dev = oldDir->myDev;
2641
2642 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2643         /* Special case for case insemsitive systems (eg. WinCE).
2644          * While look-up is case insensitive, the name isn't.
2645          * Therefore we might want to change x.txt to X.txt
2646         */
2647         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2648                 force = 1;
2649 #endif
2650
2651         if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2652                 /* ENAMETOOLONG */
2653                 return YAFFS_FAIL;
2654
2655         obj = yaffs_FindObjectByName(oldDir, oldName);
2656
2657         if (obj && obj->renameAllowed) {
2658
2659                 /* Now do the handling for an existing target, if there is one */
2660
2661                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2662                 if (existingTarget &&
2663                         existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2664                         !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2665                         /* There is a target that is a non-empty directory, so we fail */
2666                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2667                 } else if (existingTarget && existingTarget != obj) {
2668                         /* Nuke the target first, using shadowing,
2669                          * but only if it isn't the same object.
2670                          *
2671                          * Note we must disable gc otherwise it can mess up the shadowing.
2672                          *
2673                          */
2674                         dev->gcDisable=1;
2675                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2676                                                 existingTarget->objectId);
2677                         existingTarget->isShadowed = 1;
2678                         yaffs_UnlinkObject(existingTarget);
2679                         dev->gcDisable=0;
2680                 }
2681
2682                 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2683
2684                 yaffs_UpdateParent(oldDir);
2685                 if(newDir != oldDir)
2686                         yaffs_UpdateParent(newDir);
2687                 
2688                 return result;
2689         }
2690         return YAFFS_FAIL;
2691 }
2692
2693 /*------------------------- Block Management and Page Allocation ----------------*/
2694
2695 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2696 {
2697         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2698
2699         dev->blockInfo = NULL;
2700         dev->chunkBits = NULL;
2701
2702         dev->allocationBlock = -1;      /* force it to get a new one */
2703
2704         /* If the first allocation strategy fails, thry the alternate one */
2705         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2706         if (!dev->blockInfo) {
2707                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2708                 dev->blockInfoAlt = 1;
2709         } else
2710                 dev->blockInfoAlt = 0;
2711
2712         if (dev->blockInfo) {
2713                 /* Set up dynamic blockinfo stuff. */
2714                 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2715                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2716                 if (!dev->chunkBits) {
2717                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2718                         dev->chunkBitsAlt = 1;
2719                 } else
2720                         dev->chunkBitsAlt = 0;
2721         }
2722
2723         if (dev->blockInfo && dev->chunkBits) {
2724                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2725                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2726                 return YAFFS_OK;
2727         }
2728
2729         return YAFFS_FAIL;
2730 }
2731
2732 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2733 {
2734         if (dev->blockInfoAlt && dev->blockInfo)
2735                 YFREE_ALT(dev->blockInfo);
2736         else if (dev->blockInfo)
2737                 YFREE(dev->blockInfo);
2738
2739         dev->blockInfoAlt = 0;
2740
2741         dev->blockInfo = NULL;
2742
2743         if (dev->chunkBitsAlt && dev->chunkBits)
2744                 YFREE_ALT(dev->chunkBits);
2745         else if (dev->chunkBits)
2746                 YFREE(dev->chunkBits);
2747         dev->chunkBitsAlt = 0;
2748         dev->chunkBits = NULL;
2749 }
2750
2751 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2752                                         yaffs_BlockInfo *bi)
2753 {
2754
2755         if (!dev->param.isYaffs2)
2756                 return 1;       /* disqualification only applies to yaffs2. */
2757
2758         if (!bi->hasShrinkHeader)
2759                 return 1;       /* can gc */
2760
2761         yaffs_FindOldestDirtySequence(dev);
2762
2763         /* Can't do gc of this block if there are any blocks older than this one that have
2764          * discarded pages.
2765          */
2766         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2767 }
2768
2769 /*
2770  * yaffs_FindRefreshBlock()
2771  * periodically finds the oldest full block by sequence number for refreshing.
2772  * Only for yaffs2.
2773  */
2774 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2775 {
2776         __u32 b ;
2777
2778         __u32 oldest = 0;
2779         __u32 oldestSequence = 0;
2780
2781         yaffs_BlockInfo *bi;
2782
2783         /*
2784          * If refresh period < 10 then refreshing is disabled.
2785          */
2786         if(dev->param.refreshPeriod < 10 ||
2787                 !dev->param.isYaffs2)
2788                 return oldest;
2789
2790         /*
2791          * Fix broken values.
2792          */
2793         if(dev->refreshSkip > dev->param.refreshPeriod)
2794                 dev->refreshSkip = dev->param.refreshPeriod;
2795
2796         if(dev->refreshSkip > 0)
2797                 return oldest;
2798
2799         /*
2800          * Refresh skip is now zero.
2801          * We'll do a refresh this time around....
2802          * Update the refresh skip and find the oldest block.
2803          */
2804         dev->refreshSkip = dev->param.refreshPeriod;
2805         dev->refreshCount++;
2806         bi = dev->blockInfo;
2807         for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2808
2809                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2810
2811                         if(oldest < 1 ||
2812                                 bi->sequenceNumber < oldestSequence){
2813                                 oldest = b;
2814                                 oldestSequence = bi->sequenceNumber;
2815                         }
2816                 }
2817                 bi++;
2818         }
2819
2820         if (oldest > 0) {
2821                 T(YAFFS_TRACE_GC,
2822                   (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2823                    dev->refreshCount, oldest, oldestSequence));
2824         }
2825
2826         return oldest;
2827 }
2828
2829
2830 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2831 {
2832         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2833
2834         int erasedOk = 0;
2835
2836         /* If the block is still healthy erase it and mark as clean.
2837          * If the block has had a data failure, then retire it.
2838          */
2839
2840         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2841                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2842                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2843
2844         yaffs_ClearOldestDirtySequence(dev,bi);
2845
2846         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2847
2848         /* If this is the block being garbage collected then stop gc'ing this block */
2849         if(blockNo == dev->gcBlock)
2850                 dev->gcBlock = 0;
2851
2852         /* If this block is currently the best candidate for gc then drop as a candidate */
2853         if(blockNo == dev->gcDirtiest){
2854                 dev->gcDirtiest = 0;
2855                 dev->gcPagesInUse = 0;
2856         }
2857
2858         if (!bi->needsRetiring) {
2859                 yaffs_InvalidateCheckpoint(dev);
2860                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2861                 if (!erasedOk) {
2862                         dev->nErasureFailures++;
2863                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2864                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2865                 }
2866         }
2867
2868         if (erasedOk &&
2869             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2870                 int i;
2871                 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2872                         if (!yaffs_CheckChunkErased
2873                             (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2874                                 T(YAFFS_TRACE_ERROR,
2875                                   (TSTR
2876                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2877                                     TENDSTR), blockNo, i));
2878                         }
2879                 }
2880         }
2881
2882         if (erasedOk) {
2883                 /* Clean it up... */
2884                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2885                 bi->sequenceNumber = 0;
2886                 dev->nErasedBlocks++;
2887                 bi->pagesInUse = 0;
2888                 bi->softDeletions = 0;
2889                 bi->hasShrinkHeader = 0;
2890                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2891                 bi->gcPrioritise = 0;
2892                 yaffs_ClearChunkBits(dev, blockNo);
2893
2894                 T(YAFFS_TRACE_ERASE,
2895                   (TSTR("Erased block %d" TENDSTR), blockNo));
2896         } else {
2897                 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2898
2899                 yaffs_RetireBlock(dev, blockNo);
2900                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2901                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2902         }
2903 }
2904
2905 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2906 {
2907         int i;
2908
2909         yaffs_BlockInfo *bi;
2910
2911         if (dev->nErasedBlocks < 1) {
2912                 /* Hoosterman we've got a problem.
2913                  * Can't get space to gc
2914                  */
2915                 T(YAFFS_TRACE_ERROR,
2916                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2917
2918                 return -1;
2919         }
2920
2921         /* Find an empty block. */
2922
2923         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2924                 dev->allocationBlockFinder++;
2925                 if (dev->allocationBlockFinder < dev->internalStartBlock
2926                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2927                         dev->allocationBlockFinder = dev->internalStartBlock;
2928                 }
2929
2930                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2931
2932                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2933                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2934                         dev->sequenceNumber++;
2935                         bi->sequenceNumber = dev->sequenceNumber;
2936                         dev->nErasedBlocks--;
2937                         T(YAFFS_TRACE_ALLOCATE,
2938                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2939                            dev->allocationBlockFinder, dev->sequenceNumber,
2940                            dev->nErasedBlocks));
2941                         return dev->allocationBlockFinder;
2942                 }
2943         }
2944
2945         T(YAFFS_TRACE_ALWAYS,
2946           (TSTR
2947            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2948             TENDSTR), dev->nErasedBlocks));
2949
2950         return -1;
2951 }
2952
2953
2954
2955 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2956 {
2957         if (!dev->nCheckpointBlocksRequired &&
2958            dev->param.isYaffs2) {
2959                 /* Not a valid value so recalculate */
2960                 int nBytes = 0;
2961                 int nBlocks;
2962                 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2963                 int tnodeSize = yaffs_CalcTnodeSize(dev);
2964
2965                 nBytes += sizeof(yaffs_CheckpointValidity);
2966                 nBytes += sizeof(yaffs_CheckpointDevice);
2967                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2968                 nBytes += devBlocks * dev->chunkBitmapStride;
2969                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2970                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2971                 nBytes += sizeof(yaffs_CheckpointValidity);
2972                 nBytes += sizeof(__u32); /* checksum*/
2973
2974                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2975
2976                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
2977
2978                 dev->nCheckpointBlocksRequired = nBlocks;
2979         }
2980
2981         return dev->nCheckpointBlocksRequired;
2982 }
2983
2984 /*
2985  * Check if there's space to allocate...
2986  * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2987  */
2988 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
2989 {
2990         int reservedChunks;
2991         int reservedBlocks = dev->param.nReservedBlocks;
2992         int checkpointBlocks;
2993
2994         if (dev->param.isYaffs2) {
2995                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) -
2996                                     dev->blocksInCheckpoint;
2997                 if (checkpointBlocks < 0)
2998                         checkpointBlocks = 0;
2999         } else {
3000                 checkpointBlocks = 0;
3001         }
3002
3003         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3004
3005         return (dev->nFreeChunks > (reservedChunks + nChunks));
3006 }
3007
3008 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3009                 yaffs_BlockInfo **blockUsedPtr)
3010 {
3011         int retVal;
3012         yaffs_BlockInfo *bi;
3013
3014         if (dev->allocationBlock < 0) {
3015                 /* Get next block to allocate off */
3016                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3017                 dev->allocationPage = 0;
3018         }
3019
3020         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
3021                 /* Not enough space to allocate unless we're allowed to use the reserve. */
3022                 return -1;
3023         }
3024
3025         if (dev->nErasedBlocks < dev->param.nReservedBlocks
3026                         && dev->allocationPage == 0) {
3027                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3028         }
3029
3030         /* Next page please.... */
3031         if (dev->allocationBlock >= 0) {
3032                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3033
3034                 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3035                         dev->allocationPage;
3036                 bi->pagesInUse++;
3037                 yaffs_SetChunkBit(dev, dev->allocationBlock,
3038                                 dev->allocationPage);
3039
3040                 dev->allocationPage++;
3041
3042                 dev->nFreeChunks--;
3043
3044                 /* If the block is full set the state to full */
3045                 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3046                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3047                         dev->allocationBlock = -1;
3048                 }
3049
3050                 if (blockUsedPtr)
3051                         *blockUsedPtr = bi;
3052
3053                 return retVal;
3054         }
3055
3056         T(YAFFS_TRACE_ERROR,
3057                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3058
3059         return -1;
3060 }
3061
3062 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3063 {
3064         int n;
3065
3066         n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3067
3068         if (dev->allocationBlock > 0)
3069                 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3070
3071         return n;
3072
3073 }
3074
3075 /*
3076  * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3077  * if we don't want to write to it.
3078  */
3079 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3080 {
3081         if(dev->allocationBlock > 0){
3082                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3083                 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3084                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3085                         dev->allocationBlock = -1;
3086                 }
3087         }
3088 }
3089
3090
3091 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3092                 int wholeBlock)
3093 {
3094         int oldChunk;
3095         int newChunk;
3096         int markNAND;
3097         int retVal = YAFFS_OK;
3098         int cleanups = 0;
3099         int i;
3100         int isCheckpointBlock;
3101         int matchingChunk;
3102         int maxCopies;
3103
3104         int chunksBefore = yaffs_GetErasedChunks(dev);
3105         int chunksAfter;
3106
3107         yaffs_ExtendedTags tags;
3108
3109         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3110
3111         yaffs_Object *object;
3112
3113         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3114
3115
3116         T(YAFFS_TRACE_TRACING,
3117                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3118                          block,
3119                          bi->pagesInUse,
3120                          bi->hasShrinkHeader,
3121                          wholeBlock));
3122
3123         /*yaffs_VerifyFreeChunks(dev); */
3124
3125         if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3126                 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3127         
3128         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3129
3130         dev->gcDisable = 1;
3131
3132         if (isCheckpointBlock ||
3133                         !yaffs_StillSomeChunkBits(dev, block)) {
3134                 T(YAFFS_TRACE_TRACING,
3135                                 (TSTR
3136                                  ("Collecting block %d that has no chunks in use" TENDSTR),
3137                                  block));
3138                 yaffs_BlockBecameDirty(dev, block);
3139         } else {
3140
3141                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3142
3143                 yaffs_VerifyBlock(dev, bi, block);
3144
3145                 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
3146                 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3147
3148                 for (/* init already done */;
3149                      retVal == YAFFS_OK &&
3150                      dev->gcChunk < dev->param.nChunksPerBlock &&
3151                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3152                      maxCopies > 0;
3153                      dev->gcChunk++, oldChunk++) {
3154                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3155
3156                                 /* This page is in use and might need to be copied off */
3157
3158                                 maxCopies--;
3159
3160                                 markNAND = 1;
3161
3162                                 yaffs_InitialiseTags(&tags);
3163
3164                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3165                                                                 buffer, &tags);
3166
3167                                 object =
3168                                     yaffs_FindObjectByNumber(dev,
3169                                                              tags.objectId);
3170
3171                                 T(YAFFS_TRACE_GC_DETAIL,
3172                                   (TSTR
3173                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3174                                    dev->gcChunk, tags.objectId, tags.chunkId,
3175                                    tags.byteCount));
3176
3177                                 if (object && !yaffs_SkipVerification(dev)) {
3178                                         if (tags.chunkId == 0)
3179                                                 matchingChunk = object->hdrChunk;
3180                                         else if (object->softDeleted)
3181                                                 matchingChunk = oldChunk; /* Defeat the test */
3182                                         else
3183                                                 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3184
3185                                         if (oldChunk != matchingChunk)
3186                                                 T(YAFFS_TRACE_ERROR,
3187                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3188                                                   oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3189
3190                                 }
3191
3192                                 if (!object) {
3193                                         T(YAFFS_TRACE_ERROR,
3194                                           (TSTR
3195                                            ("page %d in gc has no object: %d %d %d "
3196                                             TENDSTR), oldChunk,
3197                                             tags.objectId, tags.chunkId, tags.byteCount));
3198                                 }
3199
3200                                 if (object &&
3201                                     object->deleted &&
3202                                     object->softDeleted &&
3203                                     tags.chunkId != 0) {
3204                                         /* Data chunk in a soft deleted file, throw it away
3205                                          * It's a soft deleted data chunk,
3206                                          * No need to copy this, just forget about it and
3207                                          * fix up the object.
3208                                          */
3209                                          
3210                                         /* Free chunks already includes softdeleted chunks.
3211                                          * How ever this chunk is going to soon be really deleted
3212                                          * which will increment free chunks.
3213                                          * We have to decrement free chunks so this works out properly.
3214                                          */
3215                                         dev->nFreeChunks--;
3216
3217                                         object->nDataChunks--;
3218
3219                                         if (object->nDataChunks <= 0) {
3220                                                 /* remeber to clean up the object */
3221                                                 dev->gcCleanupList[cleanups] =
3222                                                     tags.objectId;
3223                                                 cleanups++;
3224                                         }
3225                                         markNAND = 0;
3226                                 } else if (0) {
3227                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
3228                                         /* Deleted object header with no data chunks.
3229                                          * Can be discarded and the file deleted.
3230                                          */
3231                                         object->hdrChunk = 0;
3232                                         yaffs_FreeTnode(object->myDev,
3233                                                         object->variant.
3234                                                         fileVariant.top);
3235                                         object->variant.fileVariant.top = NULL;
3236                                         yaffs_DoGenericObjectDeletion(object);
3237
3238                                 } else if (object) {
3239                                         /* It's either a data chunk in a live file or
3240                                          * an ObjectHeader, so we're interested in it.
3241                                          * NB Need to keep the ObjectHeaders of deleted files
3242                                          * until the whole file has been deleted off
3243                                          */
3244                                         tags.serialNumber++;
3245
3246                                         dev->nGCCopies++;
3247
3248                                         if (tags.chunkId == 0) {
3249                                                 /* It is an object Id,
3250                                                  * We need to nuke the shrinkheader flags first
3251                                                  * Also need to clean up shadowing.
3252                                                  * We no longer want the shrinkHeader flag since its work is done
3253                                                  * and if it is left in place it will mess up scanning.
3254                                                  */
3255
3256                                                 yaffs_ObjectHeader *oh;
3257                                                 oh = (yaffs_ObjectHeader *)buffer;
3258
3259                                                 oh->isShrink = 0;
3260                                                 tags.extraIsShrinkHeader = 0;
3261
3262                                                 oh->shadowsObject = 0;
3263                                                 oh->inbandShadowsObject = 0;
3264                                                 tags.extraShadows = 0;
3265
3266                                                 /* Update file size */
3267                                                 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3268                                                         oh->fileSize = object->variant.fileVariant.fileSize;
3269                                                         tags.extraFileLength = oh->fileSize;
3270                                                 }
3271
3272                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3273                                                 newChunk =
3274                                                     yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3275                                         } else
3276                                                 newChunk =
3277                                                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3278
3279                                         if (newChunk < 0) {
3280                                                 retVal = YAFFS_FAIL;
3281                                         } else {
3282
3283                                                 /* Ok, now fix up the Tnodes etc. */
3284
3285                                                 if (tags.chunkId == 0) {
3286                                                         /* It's a header */
3287                                                         object->hdrChunk =  newChunk;
3288                                                         object->serial =   tags.serialNumber;
3289                                                 } else {
3290                                                         /* It's a data chunk */
3291                                                         int ok;
3292                                                         ok = yaffs_PutChunkIntoFile
3293                                                             (object,
3294                                                              tags.chunkId,
3295                                                              newChunk, 0);
3296                                                 }
3297                                         }
3298                                 }
3299
3300                                 if (retVal == YAFFS_OK)
3301                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3302
3303                         }
3304                 }
3305
3306                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3307
3308
3309                 /* Do any required cleanups */
3310                 for (i = 0; i < cleanups; i++) {
3311                         /* Time to delete the file too */
3312                         object =
3313                             yaffs_FindObjectByNumber(dev,
3314                                                      dev->gcCleanupList[i]);
3315                         if (object) {
3316                                 yaffs_FreeTnode(dev,
3317                                                 object->variant.fileVariant.
3318                                                 top);
3319                                 object->variant.fileVariant.top = NULL;
3320                                 T(YAFFS_TRACE_GC,
3321                                   (TSTR
3322                                    ("yaffs: About to finally delete object %d"
3323                                     TENDSTR), object->objectId));
3324                                 yaffs_DoGenericObjectDeletion(object);
3325                                 object->myDev->nDeletedFiles--;
3326                         }
3327
3328                 }
3329
3330         }
3331
3332         yaffs_VerifyCollectedBlock(dev, bi, block);
3333
3334
3335
3336         if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3337                 /*
3338                  * The gc did not complete. Set block state back to FULL
3339                  * because checkpointing does not restore gc.
3340                  */
3341                 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3342         } else {
3343                 /* The gc completed. */
3344                 chunksAfter = yaffs_GetErasedChunks(dev);
3345                 if (chunksBefore >= chunksAfter) {
3346                         T(YAFFS_TRACE_GC,
3347                           (TSTR
3348                            ("gc did not increase free chunks before %d after %d"
3349                             TENDSTR), chunksBefore, chunksAfter));
3350                 }
3351                 dev->gcBlock = 0;
3352                 dev->gcChunk = 0;
3353         }
3354
3355         dev->gcDisable = 0;
3356
3357         return retVal;
3358 }
3359
3360 /*
3361  * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
3362  * for garbage collection.