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