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