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