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