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