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