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