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