Handle unfixed ecc errors better when scanning
[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.72 2009-01-16 00:44:45 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 chunkIsLive;
756         
757         if(!obj)
758                 return;
759         
760         dev = obj->myDev;
761         
762         if(yaffs_SkipVerification(dev))
763                 return;
764                 
765         /* Check sane object header chunk */
766
767         chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
768         chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
769
770         chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
771         chunkIsLive = chunkIdOk &&
772                         yaffs_CheckChunkBit(dev,
773                                             obj->hdrChunk / dev->nChunksPerBlock,
774                                             obj->hdrChunk % dev->nChunksPerBlock);
775         if(!obj->fake &&
776             (!chunkIdOk || !chunkIsLive)) {
777            T(YAFFS_TRACE_VERIFY,
778            (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
779            obj->objectId,obj->hdrChunk,
780            chunkIdOk ? "" : ",out of range",
781            chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
782         }
783         
784         if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
785                 yaffs_ExtendedTags tags;
786                 yaffs_ObjectHeader *oh;
787                 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
788                 
789                 oh = (yaffs_ObjectHeader *)buffer;
790
791                 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
792
793                 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
794                 
795                 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
796         }
797         
798         /* Verify it has a parent */
799         if(obj && !obj->fake &&
800            (!obj->parent || obj->parent->myDev != dev)){
801            T(YAFFS_TRACE_VERIFY,
802            (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
803            obj->objectId,obj->parent));    
804         }
805         
806         /* Verify parent is a directory */
807         if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
808            T(YAFFS_TRACE_VERIFY,
809            (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
810            obj->objectId,obj->parent->variantType));       
811         }
812         
813         switch(obj->variantType){
814         case YAFFS_OBJECT_TYPE_FILE:
815                 yaffs_VerifyFile(obj);
816                 break;
817         case YAFFS_OBJECT_TYPE_SYMLINK:
818                 yaffs_VerifySymlink(obj);
819                 break;
820         case YAFFS_OBJECT_TYPE_DIRECTORY:
821                 yaffs_VerifyDirectory(obj);
822                 break;
823         case YAFFS_OBJECT_TYPE_HARDLINK:
824                 yaffs_VerifyHardLink(obj);
825                 break;
826         case YAFFS_OBJECT_TYPE_SPECIAL:
827                 yaffs_VerifySpecial(obj);
828                 break;
829         case YAFFS_OBJECT_TYPE_UNKNOWN:
830         default:
831                 T(YAFFS_TRACE_VERIFY,
832                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
833                 obj->objectId,obj->variantType));          
834                 break;
835         }
836         
837         
838 }
839
840 static void yaffs_VerifyObjects(yaffs_Device *dev)
841 {
842         yaffs_Object *obj;
843         int i;
844         struct ylist_head *lh;
845
846         if(yaffs_SkipVerification(dev))
847                 return;
848         
849         /* Iterate through the objects in each hash entry */
850          
851          for(i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++){
852                 ylist_for_each(lh, &dev->objectBucket[i].list) {
853                         if (lh) {
854                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
855                                 yaffs_VerifyObject(obj);
856                         }
857                 }
858          }
859
860 }
861
862
863 /*
864  *  Simple hash function. Needs to have a reasonable spread
865  */
866  
867 static Y_INLINE int yaffs_HashFunction(int n)
868 {
869         n = abs(n);
870         return (n % YAFFS_NOBJECT_BUCKETS);
871 }
872
873 /*
874  * Access functions to useful fake objects.
875  * Note that root might have a presence in NAND if permissions are set.
876  */
877  
878 yaffs_Object *yaffs_Root(yaffs_Device * dev)
879 {
880         return dev->rootDir;
881 }
882
883 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
884 {
885         return dev->lostNFoundDir;
886 }
887
888
889 /*
890  *  Erased NAND checking functions
891  */
892  
893 int yaffs_CheckFF(__u8 * buffer, int nBytes)
894 {
895         /* Horrible, slow implementation */
896         while (nBytes--) {
897                 if (*buffer != 0xFF)
898                         return 0;
899                 buffer++;
900         }
901         return 1;
902 }
903
904 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
905                                   int chunkInNAND)
906 {
907
908         int retval = YAFFS_OK;
909         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
910         yaffs_ExtendedTags tags;
911         int result;
912
913         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
914         
915         if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
916                 retval = YAFFS_FAIL;
917                 
918
919         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
920                 T(YAFFS_TRACE_NANDACCESS,
921                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
922                 retval = YAFFS_FAIL;
923         }
924
925         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
926
927         return retval;
928
929 }
930
931 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
932                                              const __u8 * data,
933                                              yaffs_ExtendedTags * tags,
934                                              int useReserve)
935 {
936         int attempts = 0;
937         int writeOk = 0;
938         int chunk;
939
940         yaffs_InvalidateCheckpoint(dev);
941
942         do {
943                 yaffs_BlockInfo *bi = 0;
944                 int erasedOk = 0;
945
946                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
947                 if (chunk < 0) {
948                         /* no space */
949                         break;
950                 }
951
952                 /* First check this chunk is erased, if it needs
953                  * checking.  The checking policy (unless forced
954                  * always on) is as follows:
955                  *
956                  * Check the first page we try to write in a block.
957                  * If the check passes then we don't need to check any
958                  * more.        If the check fails, we check again...
959                  * If the block has been erased, we don't need to check.
960                  *
961                  * However, if the block has been prioritised for gc,
962                  * then we think there might be something odd about
963                  * this block and stop using it.
964                  *
965                  * Rationale: We should only ever see chunks that have
966                  * not been erased if there was a partially written
967                  * chunk due to power loss.  This checking policy should
968                  * catch that case with very few checks and thus save a
969                  * lot of checks that are most likely not needed.
970                  */
971                 if (bi->gcPrioritise) {
972                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
973                         /* try another chunk */
974                         continue;
975                 }
976
977                 /* let's give it a try */
978                 attempts++;
979
980 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
981                 bi->skipErasedCheck = 0;
982 #endif
983                 if (!bi->skipErasedCheck) {
984                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
985                         if (erasedOk != YAFFS_OK) {
986                                 T(YAFFS_TRACE_ERROR,
987                                 (TSTR ("**>> yaffs chunk %d was not erased"
988                                 TENDSTR), chunk));
989
990                                 /* try another chunk */
991                                 continue;
992                         }
993                         bi->skipErasedCheck = 1;
994                 }
995
996                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
997                                 data, tags);
998                 if (writeOk != YAFFS_OK) {
999                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1000                         /* try another chunk */
1001                         continue;
1002                 }
1003
1004                 /* Copy the data into the robustification buffer */
1005                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1006
1007         } while (writeOk != YAFFS_OK && 
1008                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1009         
1010         if(!writeOk)
1011                 chunk = -1;
1012
1013         if (attempts > 1) {
1014                 T(YAFFS_TRACE_ERROR,
1015                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1016                         attempts));
1017
1018                 dev->nRetriedWrites += (attempts - 1);
1019         }
1020
1021         return chunk;
1022 }
1023
1024 /*
1025  * Block retiring for handling a broken block.
1026  */
1027  
1028 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1029 {
1030         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1031
1032         yaffs_InvalidateCheckpoint(dev);
1033         
1034         yaffs_MarkBlockBad(dev, blockInNAND);
1035
1036         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1037         bi->gcPrioritise = 0;
1038         bi->needsRetiring = 0;
1039
1040         dev->nRetiredBlocks++;
1041 }
1042
1043 /*
1044  * Functions for robustisizing TODO
1045  *
1046  */
1047  
1048 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1049                                      const __u8 * data,
1050                                      const yaffs_ExtendedTags * tags)
1051 {
1052 }
1053
1054 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1055                                     const yaffs_ExtendedTags * tags)
1056 {
1057 }
1058
1059 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1060 {
1061         if(!bi->gcPrioritise){
1062                 bi->gcPrioritise = 1;
1063                 dev->hasPendingPrioritisedGCs = 1;
1064                 bi->chunkErrorStrikes ++;
1065                 
1066                 if(bi->chunkErrorStrikes > 3){
1067                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1068                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1069
1070                 }
1071                 
1072         }
1073 }
1074
1075 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1076 {
1077
1078         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1079         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1080
1081         yaffs_HandleChunkError(dev,bi);
1082                 
1083         
1084         if(erasedOk ) {
1085                 /* Was an actual write failure, so mark the block for retirement  */
1086                 bi->needsRetiring = 1;
1087                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1088                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1089
1090                 
1091         }
1092         
1093         /* Delete the chunk */
1094         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1095 }
1096
1097
1098 /*---------------- Name handling functions ------------*/ 
1099
1100 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1101 {
1102         __u16 sum = 0;
1103         __u16 i = 1;
1104
1105         const YUCHAR *bname = (const YUCHAR *) name;
1106         if (bname) {
1107                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1108
1109 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1110                         sum += yaffs_toupper(*bname) * i;
1111 #else
1112                         sum += (*bname) * i;
1113 #endif
1114                         i++;
1115                         bname++;
1116                 }
1117         }
1118         
1119         return sum;
1120 }
1121
1122 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1123 {
1124 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1125         memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1)); 
1126         if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1127                 yaffs_strcpy(obj->shortName, name);
1128         } else {
1129                 obj->shortName[0] = _Y('\0');
1130         }
1131 #endif
1132         obj->sum = yaffs_CalcNameSum(name);
1133 }
1134
1135 /*-------------------- TNODES -------------------
1136
1137  * List of spare tnodes
1138  * The list is hooked together using the first pointer
1139  * in the tnode.
1140  */
1141  
1142 /* yaffs_CreateTnodes creates a bunch more tnodes and
1143  * adds them to the tnode free list.
1144  * Don't use this function directly
1145  */
1146
1147 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1148 {
1149         int i;
1150         int tnodeSize;
1151         yaffs_Tnode *newTnodes;
1152         __u8 *mem;
1153         yaffs_Tnode *curr;
1154         yaffs_Tnode *next;
1155         yaffs_TnodeList *tnl;
1156
1157         if (nTnodes < 1)
1158                 return YAFFS_OK;
1159                 
1160         /* Calculate the tnode size in bytes for variable width tnode support.
1161          * Must be a multiple of 32-bits  */
1162         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1163
1164         if(tnodeSize < sizeof(yaffs_Tnode))
1165                 tnodeSize = sizeof(yaffs_Tnode);
1166                 
1167
1168         /* make these things */
1169
1170         newTnodes = YMALLOC(nTnodes * tnodeSize);
1171         mem = (__u8 *)newTnodes;
1172
1173         if (!newTnodes) {
1174                 T(YAFFS_TRACE_ERROR,
1175                   (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1176                 return YAFFS_FAIL;
1177         }
1178
1179         /* Hook them into the free list */
1180 #if 0
1181         for (i = 0; i < nTnodes - 1; i++) {
1182                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1183 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1184                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1185 #endif
1186         }
1187
1188         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1189 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1190         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1191 #endif
1192         dev->freeTnodes = newTnodes;
1193 #else
1194         /* New hookup for wide tnodes */
1195         for(i = 0; i < nTnodes -1; i++) {
1196                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1197                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1198                 curr->internal[0] = next;
1199         }
1200         
1201         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1202         curr->internal[0] = dev->freeTnodes;
1203         dev->freeTnodes = (yaffs_Tnode *)mem;
1204
1205 #endif
1206
1207
1208         dev->nFreeTnodes += nTnodes;
1209         dev->nTnodesCreated += nTnodes;
1210
1211         /* Now add this bunch of tnodes to a list for freeing up.
1212          * NB If we can't add this to the management list it isn't fatal
1213          * but it just means we can't free this bunch of tnodes later.
1214          */
1215          
1216         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1217         if (!tnl) {
1218                 T(YAFFS_TRACE_ERROR,
1219                   (TSTR
1220                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1221                    return YAFFS_FAIL;
1222
1223         } else {
1224                 tnl->tnodes = newTnodes;
1225                 tnl->next = dev->allocatedTnodeList;
1226                 dev->allocatedTnodeList = tnl;
1227         }
1228
1229         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1230
1231         return YAFFS_OK;
1232 }
1233
1234 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1235
1236 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1237 {
1238         yaffs_Tnode *tn = NULL;
1239
1240         /* If there are none left make more */
1241         if (!dev->freeTnodes) {
1242                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1243         }
1244
1245         if (dev->freeTnodes) {
1246                 tn = dev->freeTnodes;
1247 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1248                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1249                         /* Hoosterman, this thing looks like it isn't in the list */
1250                         T(YAFFS_TRACE_ALWAYS,
1251                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1252                 }
1253 #endif
1254                 dev->freeTnodes = dev->freeTnodes->internal[0];
1255                 dev->nFreeTnodes--;
1256         }
1257
1258         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1259
1260         return tn;
1261 }
1262
1263 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1264 {
1265         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1266         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1267
1268         if(tnodeSize < sizeof(yaffs_Tnode))
1269                 tnodeSize = sizeof(yaffs_Tnode);
1270         
1271         if(tn)
1272                 memset(tn, 0, tnodeSize);
1273
1274         return tn;      
1275 }
1276
1277 /* FreeTnode frees up a tnode and puts it back on the free list */
1278 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1279 {
1280         if (tn) {
1281 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1282                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1283                         /* Hoosterman, this thing looks like it is already in the list */
1284                         T(YAFFS_TRACE_ALWAYS,
1285                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1286                 }
1287                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1288 #endif
1289                 tn->internal[0] = dev->freeTnodes;
1290                 dev->freeTnodes = tn;
1291                 dev->nFreeTnodes++;
1292         }
1293         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1294         
1295 }
1296
1297 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1298 {
1299         /* Free the list of allocated tnodes */
1300         yaffs_TnodeList *tmp;
1301
1302         while (dev->allocatedTnodeList) {
1303                 tmp = dev->allocatedTnodeList->next;
1304
1305                 YFREE(dev->allocatedTnodeList->tnodes);
1306                 YFREE(dev->allocatedTnodeList);
1307                 dev->allocatedTnodeList = tmp;
1308
1309         }
1310
1311         dev->freeTnodes = NULL;
1312         dev->nFreeTnodes = 0;
1313 }
1314
1315 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1316 {
1317         dev->allocatedTnodeList = NULL;
1318         dev->freeTnodes = NULL;
1319         dev->nFreeTnodes = 0;
1320         dev->nTnodesCreated = 0;
1321
1322 }
1323
1324
1325 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1326 {
1327   __u32 *map = (__u32 *)tn;
1328   __u32 bitInMap;
1329   __u32 bitInWord;
1330   __u32 wordInMap;
1331   __u32 mask;
1332   
1333   pos &= YAFFS_TNODES_LEVEL0_MASK;
1334   val >>= dev->chunkGroupBits;
1335   
1336   bitInMap = pos * dev->tnodeWidth;
1337   wordInMap = bitInMap /32;
1338   bitInWord = bitInMap & (32 -1);
1339   
1340   mask = dev->tnodeMask << bitInWord;
1341   
1342   map[wordInMap] &= ~mask;
1343   map[wordInMap] |= (mask & (val << bitInWord));
1344   
1345   if(dev->tnodeWidth > (32-bitInWord)) {
1346     bitInWord = (32 - bitInWord);
1347     wordInMap++;;
1348     mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1349     map[wordInMap] &= ~mask;
1350     map[wordInMap] |= (mask & (val >> bitInWord));
1351   }
1352 }
1353
1354 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1355 {
1356   __u32 *map = (__u32 *)tn;
1357   __u32 bitInMap;
1358   __u32 bitInWord;
1359   __u32 wordInMap;
1360   __u32 val;
1361   
1362   pos &= YAFFS_TNODES_LEVEL0_MASK;
1363   
1364   bitInMap = pos * dev->tnodeWidth;
1365   wordInMap = bitInMap /32;
1366   bitInWord = bitInMap & (32 -1);
1367   
1368   val = map[wordInMap] >> bitInWord;
1369   
1370   if(dev->tnodeWidth > (32-bitInWord)) {
1371     bitInWord = (32 - bitInWord);
1372     wordInMap++;;
1373     val |= (map[wordInMap] << bitInWord);
1374   }
1375   
1376   val &= dev->tnodeMask;
1377   val <<= dev->chunkGroupBits;
1378   
1379   return val;
1380 }
1381
1382 /* ------------------- End of individual tnode manipulation -----------------*/
1383
1384 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1385  * The look up tree is represented by the top tnode and the number of topLevel
1386  * in the tree. 0 means only the level 0 tnode is in the tree.
1387  */
1388
1389 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1390 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1391                                           yaffs_FileStructure * fStruct,
1392                                           __u32 chunkId)
1393 {
1394
1395         yaffs_Tnode *tn = fStruct->top;
1396         __u32 i;
1397         int requiredTallness;
1398         int level = fStruct->topLevel;
1399
1400         /* Check sane level and chunk Id */
1401         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1402                 return NULL;
1403         }
1404
1405         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1406                 return NULL;
1407         }
1408
1409         /* First check we're tall enough (ie enough topLevel) */
1410
1411         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1412         requiredTallness = 0;
1413         while (i) {
1414                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1415                 requiredTallness++;
1416         }
1417
1418         if (requiredTallness > fStruct->topLevel) {
1419                 /* Not tall enough, so we can't find it, return NULL. */
1420                 return NULL;
1421         }
1422
1423         /* Traverse down to level 0 */
1424         while (level > 0 && tn) {
1425                 tn = tn->
1426                     internal[(chunkId >>
1427                                ( YAFFS_TNODES_LEVEL0_BITS + 
1428                                  (level - 1) *
1429                                  YAFFS_TNODES_INTERNAL_BITS)
1430                               ) &
1431                              YAFFS_TNODES_INTERNAL_MASK];
1432                 level--;
1433
1434         }
1435
1436         return tn;
1437 }
1438
1439 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1440  * This happens in two steps:
1441  *  1. If the tree isn't tall enough, then make it taller.
1442  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1443  *
1444  * Used when modifying the tree.
1445  *
1446  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1447  *  be plugged into the ttree.
1448  */
1449  
1450 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1451                                                yaffs_FileStructure * fStruct,
1452                                                __u32 chunkId,
1453                                                yaffs_Tnode *passedTn)
1454 {
1455
1456         int requiredTallness;
1457         int i;
1458         int l;
1459         yaffs_Tnode *tn;
1460
1461         __u32 x;
1462
1463
1464         /* Check sane level and page Id */
1465         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1466                 return NULL;
1467         }
1468
1469         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1470                 return NULL;
1471         }
1472
1473         /* First check we're tall enough (ie enough topLevel) */
1474
1475         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1476         requiredTallness = 0;
1477         while (x) {
1478                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1479                 requiredTallness++;
1480         }
1481
1482
1483         if (requiredTallness > fStruct->topLevel) {
1484                 /* Not tall enough,gotta make the tree taller */
1485                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1486                 
1487                         tn = yaffs_GetTnode(dev);
1488
1489                         if (tn) {
1490                                 tn->internal[0] = fStruct->top;
1491                                 fStruct->top = tn;
1492                         } else {
1493                                 T(YAFFS_TRACE_ERROR,
1494                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
1495                         }
1496                 }
1497
1498                 fStruct->topLevel = requiredTallness;
1499         }
1500
1501         /* Traverse down to level 0, adding anything we need */
1502
1503         l = fStruct->topLevel;
1504         tn = fStruct->top;
1505         
1506         if(l > 0) {
1507                 while (l > 0 && tn) {
1508                         x = (chunkId >>
1509                              ( YAFFS_TNODES_LEVEL0_BITS +
1510                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1511                             YAFFS_TNODES_INTERNAL_MASK;
1512
1513
1514                         if((l>1) && !tn->internal[x]){
1515                                 /* Add missing non-level-zero tnode */
1516                                 tn->internal[x] = yaffs_GetTnode(dev);
1517
1518                         } else if(l == 1) {
1519                                 /* Looking from level 1 at level 0 */
1520                                 if (passedTn) {
1521                                         /* If we already have one, then release it.*/
1522                                         if(tn->internal[x])
1523                                                 yaffs_FreeTnode(dev,tn->internal[x]);
1524                                         tn->internal[x] = passedTn;
1525                         
1526                                 } else if(!tn->internal[x]) {
1527                                         /* Don't have one, none passed in */
1528                                         tn->internal[x] = yaffs_GetTnode(dev);
1529                                 }
1530                         }
1531                 
1532                         tn = tn->internal[x];
1533                         l--;
1534                 }
1535         } else {
1536                 /* top is level 0 */
1537                 if(passedTn) {
1538                         memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1539                         yaffs_FreeTnode(dev,passedTn);
1540                 }
1541         }
1542
1543         return tn;
1544 }
1545
1546 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1547                                   yaffs_ExtendedTags * tags, int objectId,
1548                                   int chunkInInode)
1549 {
1550         int j;
1551
1552         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1553                 if (yaffs_CheckChunkBit
1554                     (dev, theChunk / dev->nChunksPerBlock,
1555                      theChunk % dev->nChunksPerBlock)) {
1556                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1557                                                         tags);
1558                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1559                                 /* found it; */
1560                                 return theChunk;
1561
1562                         }
1563                 }
1564                 theChunk++;
1565         }
1566         return -1;
1567 }
1568
1569
1570 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1571  * chunks and tnodes in the file
1572  * Returns 1 if the tree was deleted. 
1573  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1574  */
1575
1576 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1577                               int chunkOffset, int *limit)
1578 {
1579         int i;
1580         int chunkInInode;
1581         int theChunk;
1582         yaffs_ExtendedTags tags;
1583         int foundChunk;
1584         yaffs_Device *dev = in->myDev;
1585
1586         int allDone = 1;
1587
1588         if (tn) {
1589                 if (level > 0) {
1590
1591                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1592                              i--) {
1593                                 if (tn->internal[i]) {
1594                                         if (limit && (*limit) < 0) {
1595                                                 allDone = 0;
1596                                         } else {
1597                                                 allDone =
1598                                                     yaffs_DeleteWorker(in,
1599                                                                        tn->
1600                                                                        internal
1601                                                                        [i],
1602                                                                        level -
1603                                                                        1,
1604                                                                        (chunkOffset
1605                                                                         <<
1606                                                                         YAFFS_TNODES_INTERNAL_BITS)
1607                                                                        + i,
1608                                                                        limit);
1609                                         }
1610                                         if (allDone) {
1611                                                 yaffs_FreeTnode(dev,
1612                                                                 tn->
1613                                                                 internal[i]);
1614                                                 tn->internal[i] = NULL;
1615                                         }
1616                                 }
1617
1618                         }
1619                         return (allDone) ? 1 : 0;
1620                 } else if (level == 0) {
1621                         int hitLimit = 0;
1622
1623                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1624                              i--) {
1625                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1626                                 if (theChunk) {
1627
1628                                         chunkInInode =
1629                                             (chunkOffset <<
1630                                              YAFFS_TNODES_LEVEL0_BITS) + i;
1631
1632                                         foundChunk =
1633                                             yaffs_FindChunkInGroup(dev,
1634                                                                    theChunk,
1635                                                                    &tags,
1636                                                                    in->objectId,
1637                                                                    chunkInInode);
1638
1639                                         if (foundChunk > 0) {
1640                                                 yaffs_DeleteChunk(dev,
1641                                                                   foundChunk, 1,
1642                                                                   __LINE__);
1643                                                 in->nDataChunks--;
1644                                                 if (limit) {
1645                                                         *limit = *limit - 1;
1646                                                         if (*limit <= 0) {
1647                                                                 hitLimit = 1;
1648                                                         }
1649                                                 }
1650
1651                                         }
1652
1653                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1654                                 }
1655
1656                         }
1657                         return (i < 0) ? 1 : 0;
1658
1659                 }
1660
1661         }
1662
1663         return 1;
1664
1665 }
1666
1667 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1668 {
1669
1670         yaffs_BlockInfo *theBlock;
1671
1672         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1673
1674         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1675         if (theBlock) {
1676                 theBlock->softDeletions++;
1677                 dev->nFreeChunks++;
1678         }
1679 }
1680
1681 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1682  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1683  * of the tnode.
1684  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1685  */
1686  
1687 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1688                                   __u32 level, int chunkOffset)
1689 {
1690         int i;
1691         int theChunk;
1692         int allDone = 1;
1693         yaffs_Device *dev = in->myDev;
1694
1695         if (tn) {
1696                 if (level > 0) {
1697
1698                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1699                              i--) {
1700                                 if (tn->internal[i]) {
1701                                         allDone =
1702                                             yaffs_SoftDeleteWorker(in,
1703                                                                    tn->
1704                                                                    internal[i],
1705                                                                    level - 1,
1706                                                                    (chunkOffset
1707                                                                     <<
1708                                                                     YAFFS_TNODES_INTERNAL_BITS)
1709                                                                    + i);
1710                                         if (allDone) {
1711                                                 yaffs_FreeTnode(dev,
1712                                                                 tn->
1713                                                                 internal[i]);
1714                                                 tn->internal[i] = NULL;
1715                                         } else {
1716                                                 /* Hoosterman... how could this happen? */
1717                                         }
1718                                 }
1719                         }
1720                         return (allDone) ? 1 : 0;
1721                 } else if (level == 0) {
1722
1723                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1724                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1725                                 if (theChunk) {
1726                                         /* Note this does not find the real chunk, only the chunk group.
1727                                          * We make an assumption that a chunk group is not larger than 
1728                                          * a block.
1729                                          */
1730                                         yaffs_SoftDeleteChunk(dev, theChunk);
1731                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1732                                 }
1733
1734                         }
1735                         return 1;
1736
1737                 }
1738
1739         }
1740
1741         return 1;
1742
1743 }
1744
1745 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1746 {
1747         if (obj->deleted &&
1748             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1749                 if (obj->nDataChunks <= 0) {
1750                         /* Empty file with no duplicate object headers, just delete it immediately */
1751                         yaffs_FreeTnode(obj->myDev,
1752                                         obj->variant.fileVariant.top);
1753                         obj->variant.fileVariant.top = NULL;
1754                         T(YAFFS_TRACE_TRACING,
1755                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1756                            obj->objectId));
1757                         yaffs_DoGenericObjectDeletion(obj);
1758                 } else {
1759                         yaffs_SoftDeleteWorker(obj,
1760                                                obj->variant.fileVariant.top,
1761                                                obj->variant.fileVariant.
1762                                                topLevel, 0);
1763                         obj->softDeleted = 1;
1764                 }
1765         }
1766 }
1767
1768 /* Pruning removes any part of the file structure tree that is beyond the
1769  * bounds of the file (ie that does not point to chunks).
1770  *
1771  * A file should only get pruned when its size is reduced.
1772  *
1773  * Before pruning, the chunks must be pulled from the tree and the
1774  * level 0 tnode entries must be zeroed out.
1775  * Could also use this for file deletion, but that's probably better handled
1776  * by a special case.
1777  */
1778
1779 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1780                                       __u32 level, int del0)
1781 {
1782         int i;
1783         int hasData;
1784
1785         if (tn) {
1786                 hasData = 0;
1787
1788                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1789                         if (tn->internal[i] && level > 0) {
1790                                 tn->internal[i] =
1791                                     yaffs_PruneWorker(dev, tn->internal[i],
1792                                                       level - 1,
1793                                                       (i == 0) ? del0 : 1);
1794                         }
1795
1796                         if (tn->internal[i]) {
1797                                 hasData++;
1798                         }
1799                 }
1800
1801                 if (hasData == 0 && del0) {
1802                         /* Free and return NULL */
1803
1804                         yaffs_FreeTnode(dev, tn);
1805                         tn = NULL;
1806                 }
1807
1808         }
1809
1810         return tn;
1811
1812 }
1813
1814 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1815                                     yaffs_FileStructure * fStruct)
1816 {
1817         int i;
1818         int hasData;
1819         int done = 0;
1820         yaffs_Tnode *tn;
1821
1822         if (fStruct->topLevel > 0) {
1823                 fStruct->top =
1824                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1825
1826                 /* Now we have a tree with all the non-zero branches NULL but the height
1827                  * is the same as it was.
1828                  * Let's see if we can trim internal tnodes to shorten the tree.
1829                  * We can do this if only the 0th element in the tnode is in use 
1830                  * (ie all the non-zero are NULL)
1831                  */
1832
1833                 while (fStruct->topLevel && !done) {
1834                         tn = fStruct->top;
1835
1836                         hasData = 0;
1837                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1838                                 if (tn->internal[i]) {
1839                                         hasData++;
1840                                 }
1841                         }
1842
1843                         if (!hasData) {
1844                                 fStruct->top = tn->internal[0];
1845                                 fStruct->topLevel--;
1846                                 yaffs_FreeTnode(dev, tn);
1847                         } else {
1848                                 done = 1;
1849                         }
1850                 }
1851         }
1852
1853         return YAFFS_OK;
1854 }
1855
1856 /*-------------------- End of File Structure functions.-------------------*/
1857
1858 /* yaffs_CreateFreeObjects creates a bunch more objects and
1859  * adds them to the object free list.
1860  */
1861 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1862 {
1863         int i;
1864         yaffs_Object *newObjects;
1865         yaffs_ObjectList *list;
1866
1867         if (nObjects < 1)
1868                 return YAFFS_OK;
1869
1870         /* make these things */
1871         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1872         list = YMALLOC(sizeof(yaffs_ObjectList));
1873
1874         if (!newObjects || !list) {
1875                 if(newObjects)
1876                         YFREE(newObjects);
1877                 if(list)
1878                         YFREE(list);
1879                 T(YAFFS_TRACE_ALLOCATE,
1880                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1881                 return YAFFS_FAIL;
1882         }
1883         
1884         /* Hook them into the free list */
1885         for (i = 0; i < nObjects - 1; i++) {
1886                 newObjects[i].siblings.next =
1887                     (struct ylist_head *)(&newObjects[i + 1]);
1888         }
1889
1890         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1891         dev->freeObjects = newObjects;
1892         dev->nFreeObjects += nObjects;
1893         dev->nObjectsCreated += nObjects;
1894
1895         /* Now add this bunch of Objects to a list for freeing up. */
1896
1897         list->objects = newObjects;
1898         list->next = dev->allocatedObjectList;
1899         dev->allocatedObjectList = list;
1900
1901         return YAFFS_OK;
1902 }
1903
1904
1905 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1906 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1907 {
1908         yaffs_Object *tn = NULL;
1909
1910 #ifdef VALGRIND_TEST
1911         tn = YMALLOC(sizeof(yaffs_Object));
1912 #else
1913         /* If there are none left make more */
1914         if (!dev->freeObjects) {
1915                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1916         }
1917
1918         if (dev->freeObjects) {
1919                 tn = dev->freeObjects;
1920                 dev->freeObjects =
1921                     (yaffs_Object *) (dev->freeObjects->siblings.next);
1922                 dev->nFreeObjects--;
1923         }
1924 #endif
1925         if(tn){
1926                 /* Now sweeten it up... */
1927
1928                 memset(tn, 0, sizeof(yaffs_Object));
1929                 tn->myDev = dev;
1930                 tn->hdrChunk = 0;
1931                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1932                 YINIT_LIST_HEAD(&(tn->hardLinks));
1933                 YINIT_LIST_HEAD(&(tn->hashLink));
1934                 YINIT_LIST_HEAD(&tn->siblings);
1935                 
1936
1937                 /* Now make the directory sane */
1938                 if(dev->rootDir){
1939                         tn->parent = dev->rootDir;
1940                         ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1941                 }
1942
1943                 /* Add it to the lost and found directory.
1944                  * NB Can't put root or lostNFound in lostNFound so
1945                  * check if lostNFound exists first
1946                  */
1947                 if (dev->lostNFoundDir) {
1948                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1949                 }
1950         }
1951         
1952         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1953
1954         return tn;
1955 }
1956
1957 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1958                                                __u32 mode)
1959 {
1960
1961         yaffs_Object *obj =
1962             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1963         if (obj) {
1964                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
1965                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1966                 obj->unlinkAllowed = 0; /* ... or unlink it */
1967                 obj->deleted = 0;
1968                 obj->unlinked = 0;
1969                 obj->yst_mode = mode;
1970                 obj->myDev = dev;
1971                 obj->hdrChunk = 0;      /* Not a valid chunk. */
1972         }
1973
1974         return obj;
1975
1976 }
1977
1978 static void yaffs_UnhashObject(yaffs_Object * tn)
1979 {
1980         int bucket;
1981         yaffs_Device *dev = tn->myDev;
1982
1983         /* If it is still linked into the bucket list, free from the list */
1984         if (!ylist_empty(&tn->hashLink)) {
1985                 ylist_del_init(&tn->hashLink);
1986                 bucket = yaffs_HashFunction(tn->objectId);
1987                 dev->objectBucket[bucket].count--;
1988         }
1989
1990 }
1991
1992 /*  FreeObject frees up a Object and puts it back on the free list */
1993 static void yaffs_FreeObject(yaffs_Object * tn)
1994 {
1995
1996         yaffs_Device *dev = tn->myDev;
1997
1998         
1999         if(tn->parent)
2000                 YBUG();
2001         if(!ylist_empty(&tn->siblings))
2002                 YBUG();
2003
2004
2005 #ifdef  __KERNEL__
2006         if (tn->myInode) {
2007                 /* We're still hooked up to a cached inode.
2008                  * Don't delete now, but mark for later deletion
2009                  */
2010                 tn->deferedFree = 1;
2011                 return;
2012         }
2013 #endif
2014
2015         yaffs_UnhashObject(tn);
2016
2017 #ifdef VALGRIND_TEST
2018         YFREE(tn);
2019 #else
2020         /* Link into the free list. */
2021         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2022         dev->freeObjects = tn;
2023         dev->nFreeObjects++;
2024 #endif
2025         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2026
2027 }
2028
2029 #ifdef __KERNEL__
2030
2031 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2032 {
2033         if (obj->deferedFree) {
2034                 yaffs_FreeObject(obj);
2035         }
2036 }
2037
2038 #endif
2039
2040 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2041 {
2042         /* Free the list of allocated Objects */
2043
2044         yaffs_ObjectList *tmp;
2045
2046         while (dev->allocatedObjectList) {
2047                 tmp = dev->allocatedObjectList->next;
2048                 YFREE(dev->allocatedObjectList->objects);
2049                 YFREE(dev->allocatedObjectList);
2050
2051                 dev->allocatedObjectList = tmp;
2052         }
2053
2054         dev->freeObjects = NULL;
2055         dev->nFreeObjects = 0;
2056 }
2057
2058 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2059 {
2060         int i;
2061
2062         dev->allocatedObjectList = NULL;
2063         dev->freeObjects = NULL;
2064         dev->nFreeObjects = 0;
2065
2066         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2067                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2068                 dev->objectBucket[i].count = 0;
2069         }
2070
2071 }
2072
2073 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2074 {
2075         static int x = 0;
2076         int i;
2077         int l = 999;
2078         int lowest = 999999;
2079
2080         /* First let's see if we can find one that's empty. */
2081
2082         for (i = 0; i < 10 && lowest > 0; i++) {
2083                 x++;
2084                 x %= YAFFS_NOBJECT_BUCKETS;
2085                 if (dev->objectBucket[x].count < lowest) {
2086                         lowest = dev->objectBucket[x].count;
2087                         l = x;
2088                 }
2089
2090         }
2091
2092         /* If we didn't find an empty list, then try
2093          * looking a bit further for a short one
2094          */
2095
2096         for (i = 0; i < 10 && lowest > 3; i++) {
2097                 x++;
2098                 x %= YAFFS_NOBJECT_BUCKETS;
2099                 if (dev->objectBucket[x].count < lowest) {
2100                         lowest = dev->objectBucket[x].count;
2101                         l = x;
2102                 }
2103
2104         }
2105
2106         return l;
2107 }
2108
2109 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2110 {
2111         int bucket = yaffs_FindNiceObjectBucket(dev);
2112
2113         /* Now find an object value that has not already been taken
2114          * by scanning the list.
2115          */
2116
2117         int found = 0;
2118         struct ylist_head *i;
2119
2120         __u32 n = (__u32) bucket;
2121
2122         /* yaffs_CheckObjectHashSanity();  */
2123
2124         while (!found) {
2125                 found = 1;
2126                 n += YAFFS_NOBJECT_BUCKETS;
2127                 if (1 || dev->objectBucket[bucket].count > 0) {
2128                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2129                                 /* If there is already one in the list */
2130                                 if (i
2131                                     && ylist_entry(i, yaffs_Object,
2132                                                   hashLink)->objectId == n) {
2133                                         found = 0;
2134                                 }
2135                         }
2136                 }
2137         }
2138
2139
2140         return n;
2141 }
2142
2143 static void yaffs_HashObject(yaffs_Object * in)
2144 {
2145         int bucket = yaffs_HashFunction(in->objectId);
2146         yaffs_Device *dev = in->myDev;
2147
2148         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2149         dev->objectBucket[bucket].count++;
2150
2151 }
2152
2153 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2154 {
2155         int bucket = yaffs_HashFunction(number);
2156         struct ylist_head *i;
2157         yaffs_Object *in;
2158
2159         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2160                 /* Look if it is in the list */
2161                 if (i) {
2162                         in = ylist_entry(i, yaffs_Object, hashLink);
2163                         if (in->objectId == number) {
2164 #ifdef __KERNEL__
2165                                 /* Don't tell the VFS about this one if it is defered free */
2166                                 if (in->deferedFree)
2167                                         return NULL;
2168 #endif
2169
2170                                 return in;
2171                         }
2172                 }
2173         }
2174
2175         return NULL;
2176 }
2177
2178 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2179                                     yaffs_ObjectType type)
2180 {
2181
2182         yaffs_Object *theObject;
2183         yaffs_Tnode *tn = NULL;
2184
2185         if (number < 0) {
2186                 number = yaffs_CreateNewObjectNumber(dev);
2187         }
2188
2189         theObject = yaffs_AllocateEmptyObject(dev);
2190         if(!theObject)
2191                 return NULL;
2192                 
2193         if(type == YAFFS_OBJECT_TYPE_FILE){
2194                 tn = yaffs_GetTnode(dev);
2195                 if(!tn){
2196                         yaffs_FreeObject(theObject);
2197                         return NULL;
2198                 }
2199         }
2200                 
2201         
2202
2203         if (theObject) {
2204                 theObject->fake = 0;
2205                 theObject->renameAllowed = 1;
2206                 theObject->unlinkAllowed = 1;
2207                 theObject->objectId = number;
2208                 yaffs_HashObject(theObject);
2209                 theObject->variantType = type;
2210 #ifdef CONFIG_YAFFS_WINCE
2211                 yfsd_WinFileTimeNow(theObject->win_atime);
2212                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2213                     theObject->win_atime[0];
2214                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2215                     theObject->win_atime[1];
2216
2217 #else
2218
2219                 theObject->yst_atime = theObject->yst_mtime =
2220                     theObject->yst_ctime = Y_CURRENT_TIME;
2221 #endif
2222
2223 #if 0
2224                 theObject->sum_prev = 12345;
2225                 theObject->sum_trailer = 6789;
2226 #endif
2227
2228                 switch (type) {
2229                 case YAFFS_OBJECT_TYPE_FILE:
2230                         theObject->variant.fileVariant.fileSize = 0;
2231                         theObject->variant.fileVariant.scannedFileSize = 0;
2232                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2233                         theObject->variant.fileVariant.topLevel = 0;
2234                         theObject->variant.fileVariant.top = tn;
2235                         break;
2236                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2237                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2238                                        children);
2239                         break;
2240                 case YAFFS_OBJECT_TYPE_SYMLINK:
2241                 case YAFFS_OBJECT_TYPE_HARDLINK:
2242                 case YAFFS_OBJECT_TYPE_SPECIAL:
2243                         /* No action required */
2244                         break;
2245                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2246                         /* todo this should not happen */
2247                         break;
2248                 }
2249         }
2250
2251         return theObject;
2252 }
2253
2254 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2255                                                       int number,
2256                                                       yaffs_ObjectType type)
2257 {
2258         yaffs_Object *theObject = NULL;
2259
2260         if (number > 0) {
2261                 theObject = yaffs_FindObjectByNumber(dev, number);
2262         }
2263
2264         if (!theObject) {
2265                 theObject = yaffs_CreateNewObject(dev, number, type);
2266         }
2267
2268         return theObject;
2269
2270 }
2271                         
2272
2273 static YCHAR *yaffs_CloneString(const YCHAR * str)
2274 {
2275         YCHAR *newStr = NULL;
2276
2277         if (str && *str) {
2278                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2279                 if(newStr)
2280                         yaffs_strcpy(newStr, str);
2281         }
2282
2283         return newStr;
2284
2285 }
2286
2287 /*
2288  * Mknod (create) a new object.
2289  * equivalentObject only has meaning for a hard link;
2290  * aliasString only has meaning for a sumlink.
2291  * rdev only has meaning for devices (a subset of special objects)
2292  */
2293  
2294 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2295                                        yaffs_Object * parent,
2296                                        const YCHAR * name,
2297                                        __u32 mode,
2298                                        __u32 uid,
2299                                        __u32 gid,
2300                                        yaffs_Object * equivalentObject,
2301                                        const YCHAR * aliasString, __u32 rdev)
2302 {
2303         yaffs_Object *in;
2304         YCHAR *str = NULL;
2305
2306         yaffs_Device *dev = parent->myDev;
2307
2308         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2309         if (yaffs_FindObjectByName(parent, name)) {
2310                 return NULL;
2311         }
2312
2313         in = yaffs_CreateNewObject(dev, -1, type);
2314
2315         if(!in)
2316                 return YAFFS_FAIL;
2317         
2318         if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2319                 str = yaffs_CloneString(aliasString);
2320                 if(!str){
2321                         yaffs_FreeObject(in);
2322                         return NULL;
2323                 }
2324         }
2325         
2326         
2327
2328         if (in) {
2329                 in->hdrChunk = 0;
2330                 in->valid = 1;
2331                 in->variantType = type;
2332
2333                 in->yst_mode = mode;
2334
2335 #ifdef CONFIG_YAFFS_WINCE
2336                 yfsd_WinFileTimeNow(in->win_atime);
2337                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2338                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2339
2340 #else
2341                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2342
2343                 in->yst_rdev = rdev;
2344                 in->yst_uid = uid;
2345                 in->yst_gid = gid;
2346 #endif
2347                 in->nDataChunks = 0;
2348
2349                 yaffs_SetObjectName(in, name);
2350                 in->dirty = 1;
2351
2352                 yaffs_AddObjectToDirectory(parent, in);
2353
2354                 in->myDev = parent->myDev;
2355
2356                 switch (type) {
2357                 case YAFFS_OBJECT_TYPE_SYMLINK:
2358                         in->variant.symLinkVariant.alias = str;
2359                         break;
2360                 case YAFFS_OBJECT_TYPE_HARDLINK:
2361                         in->variant.hardLinkVariant.equivalentObject =
2362                             equivalentObject;
2363                         in->variant.hardLinkVariant.equivalentObjectId =
2364                             equivalentObject->objectId;
2365                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2366                         break;
2367                 case YAFFS_OBJECT_TYPE_FILE:    
2368                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2369                 case YAFFS_OBJECT_TYPE_SPECIAL:
2370                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2371                         /* do nothing */
2372                         break;
2373                 }
2374
2375                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2376                         /* Could not create the object header, fail the creation */
2377                         yaffs_DestroyObject(in);
2378                         in = NULL;
2379                 }
2380
2381         }
2382
2383         return in;
2384 }
2385
2386 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2387                               __u32 mode, __u32 uid, __u32 gid)
2388 {
2389         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2390                                  uid, gid, NULL, NULL, 0);
2391 }
2392
2393 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2394                                    __u32 mode, __u32 uid, __u32 gid)
2395 {
2396         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2397                                  mode, uid, gid, NULL, NULL, 0);
2398 }
2399
2400 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2401                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2402 {
2403         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2404                                  uid, gid, NULL, NULL, rdev);
2405 }
2406
2407 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2408                                  __u32 mode, __u32 uid, __u32 gid,
2409                                  const YCHAR * alias)
2410 {
2411         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2412                                  uid, gid, NULL, alias, 0);
2413 }
2414
2415 /* yaffs_Link returns the object id of the equivalent object.*/
2416 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2417                          yaffs_Object * equivalentObject)
2418 {
2419         /* Get the real object in case we were fed a hard link as an equivalent object */
2420         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2421
2422         if (yaffs_MknodObject
2423             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2424              equivalentObject, NULL, 0)) {
2425                 return equivalentObject;
2426         } else {
2427                 return NULL;
2428         }
2429
2430 }
2431
2432 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2433                                   const YCHAR * newName, int force, int shadows)
2434 {
2435         int unlinkOp;
2436         int deleteOp;
2437
2438         yaffs_Object *existingTarget;
2439
2440         if (newDir == NULL) {
2441                 newDir = obj->parent;   /* use the old directory */
2442         }
2443
2444         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2445                 T(YAFFS_TRACE_ALWAYS,
2446                   (TSTR
2447                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2448                     TENDSTR)));
2449                 YBUG();
2450         }
2451         
2452         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2453         if (obj->myDev->isYaffs2) {
2454                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2455         } else {
2456                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2457                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2458         }
2459
2460         deleteOp = (newDir == obj->myDev->deletedDir);
2461
2462         existingTarget = yaffs_FindObjectByName(newDir, newName);
2463
2464         /* If the object is a file going into the unlinked directory, 
2465          *   then it is OK to just stuff it in since duplicate names are allowed.
2466          *   else only proceed if the new name does not exist and if we're putting 
2467          *   it into a directory.
2468          */
2469         if ((unlinkOp ||
2470              deleteOp ||
2471              force ||
2472              (shadows > 0) ||
2473              !existingTarget) &&
2474             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2475                 yaffs_SetObjectName(obj, newName);
2476                 obj->dirty = 1;
2477
2478                 yaffs_AddObjectToDirectory(newDir, obj);
2479
2480                 if (unlinkOp)
2481                         obj->unlinked = 1;
2482
2483                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2484                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2485                         return YAFFS_OK;
2486         }
2487
2488         return YAFFS_FAIL;
2489 }
2490
2491 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2492                        yaffs_Object * newDir, const YCHAR * newName)
2493 {
2494         yaffs_Object *obj=NULL;
2495         yaffs_Object *existingTarget=NULL;
2496         int force = 0;
2497         
2498         
2499         if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2500                 YBUG();
2501         if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2502                 YBUG();
2503
2504 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2505         /* Special case for case insemsitive systems (eg. WinCE).
2506          * While look-up is case insensitive, the name isn't.
2507          * Therefore we might want to change x.txt to X.txt
2508         */
2509         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2510                 force = 1;
2511         }
2512 #endif
2513
2514         else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2515           /* ENAMETOOLONG */
2516           return YAFFS_FAIL;
2517
2518         obj = yaffs_FindObjectByName(oldDir, oldName);
2519
2520         if (obj && obj->renameAllowed) {
2521
2522                 /* Now do the handling for an existing target, if there is one */
2523
2524                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2525                 if (existingTarget &&
2526                     existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2527                     !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2528                         /* There is a target that is a non-empty directory, so we fail */
2529                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2530                 } else if (existingTarget && existingTarget != obj) {
2531                         /* Nuke the target first, using shadowing, 
2532                          * but only if it isn't the same object
2533                          */
2534                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2535                                                existingTarget->objectId);
2536                         yaffs_UnlinkObject(existingTarget);
2537                 }
2538
2539                 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2540         }
2541         return YAFFS_FAIL;
2542 }
2543
2544 /*------------------------- Block Management and Page Allocation ----------------*/
2545
2546 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2547 {
2548         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2549         
2550         dev->blockInfo = NULL;
2551         dev->chunkBits = NULL;
2552         
2553         dev->allocationBlock = -1;      /* force it to get a new one */
2554
2555         /* If the first allocation strategy fails, thry the alternate one */
2556         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2557         if(!dev->blockInfo){
2558                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2559                 dev->blockInfoAlt = 1;
2560         }
2561         else
2562                 dev->blockInfoAlt = 0;
2563                 
2564         if(dev->blockInfo){
2565         
2566                 /* Set up dynamic blockinfo stuff. */
2567                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2568                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2569                 if(!dev->chunkBits){
2570                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2571                         dev->chunkBitsAlt = 1;
2572                 }
2573                 else
2574                         dev->chunkBitsAlt = 0;
2575         }
2576         
2577         if (dev->blockInfo && dev->chunkBits) {
2578                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2579                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2580                 return YAFFS_OK;
2581         }
2582
2583         return YAFFS_FAIL;
2584
2585 }
2586
2587 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2588 {
2589         if(dev->blockInfoAlt && dev->blockInfo)
2590                 YFREE_ALT(dev->blockInfo);
2591         else if(dev->blockInfo)
2592                 YFREE(dev->blockInfo);
2593
2594         dev->blockInfoAlt = 0;
2595
2596         dev->blockInfo = NULL;
2597         
2598         if(dev->chunkBitsAlt && dev->chunkBits)
2599                 YFREE_ALT(dev->chunkBits);
2600         else if(dev->chunkBits)
2601                 YFREE(dev->chunkBits);
2602         dev->chunkBitsAlt = 0;
2603         dev->chunkBits = NULL;
2604 }
2605
2606 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2607                                             yaffs_BlockInfo * bi)
2608 {
2609         int i;
2610         __u32 seq;
2611         yaffs_BlockInfo *b;
2612
2613         if (!dev->isYaffs2)
2614                 return 1;       /* disqualification only applies to yaffs2. */
2615
2616         if (!bi->hasShrinkHeader)
2617                 return 1;       /* can gc */
2618
2619         /* Find the oldest dirty sequence number if we don't know it and save it
2620          * so we don't have to keep recomputing it.
2621          */
2622         if (!dev->oldestDirtySequence) {
2623                 seq = dev->sequenceNumber;
2624
2625                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2626                      i++) {
2627                         b = yaffs_GetBlockInfo(dev, i);
2628                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2629                             (b->pagesInUse - b->softDeletions) <
2630                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2631                                 seq = b->sequenceNumber;
2632                         }
2633                 }
2634                 dev->oldestDirtySequence = seq;
2635         }
2636
2637         /* Can't do gc of this block if there are any blocks older than this one that have
2638          * discarded pages.
2639          */
2640         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2641
2642 }
2643
2644 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2645  * for garbage collection.
2646  */
2647
2648 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2649                                                int aggressive)
2650 {
2651
2652         int b = dev->currentDirtyChecker;
2653
2654         int i;
2655         int iterations;
2656         int dirtiest = -1;
2657         int pagesInUse = 0;
2658         int prioritised=0;
2659         yaffs_BlockInfo *bi;
2660         int pendingPrioritisedExist = 0;
2661         
2662         /* First let's see if we need to grab a prioritised block */
2663         if(dev->hasPendingPrioritisedGCs){
2664                 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2665
2666                         bi = yaffs_GetBlockInfo(dev, i);
2667                         //yaffs_VerifyBlock(dev,bi,i);
2668                         
2669                         if(bi->gcPrioritise) {
2670                                 pendingPrioritisedExist = 1;
2671                                 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2672                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2673                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2674                                         dirtiest = i;
2675                                         prioritised = 1;
2676                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2677                                 }
2678                         }
2679                 }
2680                 
2681                 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2682                         dev->hasPendingPrioritisedGCs = 0;
2683         }
2684
2685         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2686          * search harder.
2687          * else (we're doing a leasurely gc), then we only bother to do this if the
2688          * block has only a few pages in use.
2689          */
2690
2691         dev->nonAggressiveSkip--;
2692
2693         if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2694                 return -1;
2695         }
2696
2697         if(!prioritised)
2698                 pagesInUse =
2699                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2700
2701         if (aggressive) {
2702                 iterations =
2703                     dev->internalEndBlock - dev->internalStartBlock + 1;
2704         } else {
2705                 iterations =
2706                     dev->internalEndBlock - dev->internalStartBlock + 1;
2707                 iterations = iterations / 16;
2708                 if (iterations > 200) {
2709                         iterations = 200;
2710                 }
2711         }
2712
2713         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2714                 b++;
2715                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2716                         b = dev->internalStartBlock;
2717                 }
2718
2719                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2720                         T(YAFFS_TRACE_ERROR,
2721                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2722                         YBUG();
2723                 }
2724
2725                 bi = yaffs_GetBlockInfo(dev, b);
2726
2727 #if 0
2728                 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2729                         dirtiest = b;
2730                         pagesInUse = 0;
2731                 }
2732                 else 
2733 #endif
2734
2735                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2736                        (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2737                         yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2738                         dirtiest = b;
2739                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2740                 }
2741         }
2742
2743         dev->currentDirtyChecker = b;
2744
2745         if (dirtiest > 0) {
2746                 T(YAFFS_TRACE_GC,
2747                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2748                    dev->nChunksPerBlock - pagesInUse,prioritised));
2749         }
2750
2751         dev->oldestDirtySequence = 0;
2752
2753         if (dirtiest > 0) {
2754                 dev->nonAggressiveSkip = 4;
2755         }
2756
2757         return dirtiest;
2758 }
2759
2760 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2761 {
2762         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2763
2764         int erasedOk = 0;
2765
2766         /* If the block is still healthy erase it and mark as clean.
2767          * If the block has had a data failure, then retire it.
2768          */
2769          
2770         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2771                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2772                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2773                 
2774         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2775
2776         if (!bi->needsRetiring) {
2777                 yaffs_InvalidateCheckpoint(dev);
2778                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2779                 if (!erasedOk) {
2780                         dev->nErasureFailures++;
2781                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2782                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2783                 }
2784         }
2785
2786         if (erasedOk && 
2787             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2788                 int i;
2789                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2790                         if (!yaffs_CheckChunkErased
2791                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2792                                 T(YAFFS_TRACE_ERROR,
2793                                   (TSTR
2794                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2795                                     TENDSTR), blockNo, i));
2796                         }
2797                 }
2798         }
2799
2800         if (erasedOk) {
2801                 /* Clean it up... */
2802                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2803                 dev->nErasedBlocks++;
2804                 bi->pagesInUse = 0;
2805                 bi->softDeletions = 0;
2806                 bi->hasShrinkHeader = 0;
2807                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2808                 bi->gcPrioritise = 0;
2809                 yaffs_ClearChunkBits(dev, blockNo);
2810
2811                 T(YAFFS_TRACE_ERASE,
2812                   (TSTR("Erased block %d" TENDSTR), blockNo));
2813         } else {
2814                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2815
2816                 yaffs_RetireBlock(dev, blockNo);
2817                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2818                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2819         }
2820 }
2821
2822 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2823 {
2824         int i;
2825
2826         yaffs_BlockInfo *bi;
2827
2828         if (dev->nErasedBlocks < 1) {
2829                 /* Hoosterman we've got a problem.
2830                  * Can't get space to gc
2831                  */
2832                 T(YAFFS_TRACE_ERROR,
2833                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2834
2835                 return -1;
2836         }
2837         
2838         /* Find an empty block. */
2839
2840         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2841                 dev->allocationBlockFinder++;
2842                 if (dev->allocationBlockFinder < dev->internalStartBlock
2843                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2844                         dev->allocationBlockFinder = dev->internalStartBlock;
2845                 }
2846
2847                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2848
2849                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2850                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2851                         dev->sequenceNumber++;
2852                         bi->sequenceNumber = dev->sequenceNumber;
2853                         dev->nErasedBlocks--;
2854                         T(YAFFS_TRACE_ALLOCATE,
2855                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2856                            dev->allocationBlockFinder, dev->sequenceNumber,
2857                            dev->nErasedBlocks));
2858                         return dev->allocationBlockFinder;
2859                 }
2860         }
2861
2862         T(YAFFS_TRACE_ALWAYS,
2863           (TSTR
2864            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2865             TENDSTR), dev->nErasedBlocks));
2866
2867         return -1;
2868 }
2869
2870
2871
2872 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2873 {
2874         if(!dev->nCheckpointBlocksRequired &&
2875            dev->isYaffs2){
2876                 /* Not a valid value so recalculate */
2877                 int nBytes = 0;
2878                 int nBlocks;
2879                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2880                 int tnodeSize;
2881
2882                 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2883
2884                 if(tnodeSize < sizeof(yaffs_Tnode))
2885                         tnodeSize = sizeof(yaffs_Tnode);
2886                 
2887                 nBytes += sizeof(yaffs_CheckpointValidity);
2888                 nBytes += sizeof(yaffs_CheckpointDevice);
2889                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2890                 nBytes += devBlocks * dev->chunkBitmapStride;
2891                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2892                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2893                 nBytes += sizeof(yaffs_CheckpointValidity);
2894                 nBytes += sizeof(__u32); /* checksum*/
2895         
2896                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2897         
2898                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2899         
2900                 dev->nCheckpointBlocksRequired = nBlocks;
2901         }
2902
2903         return dev->nCheckpointBlocksRequired;
2904 }
2905
2906 // Check if there's space to allocate...
2907 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2908 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2909 {
2910         int reservedChunks;
2911         int reservedBlocks = dev->nReservedBlocks;
2912         int checkpointBlocks;
2913         
2914         if(dev->isYaffs2){
2915                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) - 
2916                                     dev->blocksInCheckpoint;
2917                 if(checkpointBlocks < 0)
2918                         checkpointBlocks = 0;
2919         } else {
2920                 checkpointBlocks =0;
2921         }
2922         
2923         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2924         
2925         return (dev->nFreeChunks > reservedChunks);
2926 }
2927
2928 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2929 {
2930         int retVal;
2931         yaffs_BlockInfo *bi;
2932
2933         if (dev->allocationBlock < 0) {
2934                 /* Get next block to allocate off */
2935                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2936                 dev->allocationPage = 0;
2937         }
2938
2939         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2940                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2941                 return -1;
2942         }
2943
2944         if (dev->nErasedBlocks < dev->nReservedBlocks
2945             && dev->allocationPage == 0) {
2946                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2947         }
2948
2949         /* Next page please.... */
2950         if (dev->allocationBlock >= 0) {
2951                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2952
2953                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2954                     dev->allocationPage;
2955                 bi->pagesInUse++;
2956                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2957                                   dev->allocationPage);
2958
2959                 dev->allocationPage++;
2960
2961                 dev->nFreeChunks--;
2962
2963                 /* If the block is full set the state to full */
2964                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2965                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2966                         dev->allocationBlock = -1;
2967                 }
2968
2969                 if(blockUsedPtr)
2970                         *blockUsedPtr = bi;
2971                         
2972                 return retVal;
2973         }
2974         
2975         T(YAFFS_TRACE_ERROR,
2976           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2977
2978         return -1;
2979 }
2980
2981 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2982 {
2983         int n;
2984
2985         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2986
2987         if (dev->allocationBlock > 0) {
2988                 n += (dev->nChunksPerBlock - dev->allocationPage);
2989         }
2990
2991         return n;
2992
2993 }
2994
2995 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
2996 {
2997         int oldChunk;
2998         int newChunk;
2999         int markNAND;
3000         int retVal = YAFFS_OK;
3001         int cleanups = 0;
3002         int i;
3003         int isCheckpointBlock;
3004         int matchingChunk;
3005         int maxCopies;
3006
3007         int chunksBefore = yaffs_GetErasedChunks(dev);
3008         int chunksAfter;
3009
3010         yaffs_ExtendedTags tags;
3011
3012         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3013
3014         yaffs_Object *object;
3015
3016         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3017         
3018         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3019
3020         T(YAFFS_TRACE_TRACING,
3021           (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR), 
3022           block,
3023           bi->pagesInUse,
3024           bi->hasShrinkHeader,
3025           wholeBlock));
3026
3027         /*yaffs_VerifyFreeChunks(dev); */
3028
3029         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3030
3031         /* Take off the number of soft deleted entries because
3032          * they're going to get really deleted during GC.
3033          */
3034         dev->nFreeChunks -= bi->softDeletions;
3035
3036         dev->isDoingGC = 1;
3037
3038         if (isCheckpointBlock ||
3039             !yaffs_StillSomeChunkBits(dev, block)) {
3040                 T(YAFFS_TRACE_TRACING,
3041                   (TSTR
3042                    ("Collecting block %d that has no chunks in use" TENDSTR),
3043                    block));
3044                 yaffs_BlockBecameDirty(dev, block);
3045         } else {
3046
3047                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3048                 
3049                 yaffs_VerifyBlock(dev,bi,block);
3050
3051                 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3052                 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3053                 
3054                 for ( /* init already done */;
3055                      retVal == YAFFS_OK &&
3056                      dev->gcChunk < dev->nChunksPerBlock &&
3057                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3058                      maxCopies > 0;
3059                      dev->gcChunk++, oldChunk++) {
3060                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3061
3062                                 /* This page is in use and might need to be copied off */
3063                                 
3064                                 maxCopies--;
3065
3066                                 markNAND = 1;
3067
3068                                 yaffs_InitialiseTags(&tags);
3069
3070                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3071                                                                 buffer, &tags);
3072
3073                                 object =
3074                                     yaffs_FindObjectByNumber(dev,
3075                                                              tags.objectId);
3076
3077                                 T(YAFFS_TRACE_GC_DETAIL,
3078                                   (TSTR
3079                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3080                                    dev->gcChunk, tags.objectId, tags.chunkId,
3081                                    tags.byteCount));
3082                                    
3083                                 if(object && !yaffs_SkipVerification(dev)){
3084                                         if(tags.chunkId == 0)
3085                                                 matchingChunk = object->hdrChunk;
3086                                         else if(object->softDeleted)
3087                                                 matchingChunk = oldChunk; /* Defeat the test */
3088                                         else
3089                                                 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3090                                         
3091                                         if(oldChunk != matchingChunk)
3092                                                 T(YAFFS_TRACE_ERROR,
3093                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3094                                                   oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3095                                                 
3096                                 }
3097
3098                                 if (!object) {
3099                                         T(YAFFS_TRACE_ERROR,
3100                                           (TSTR
3101                                            ("page %d in gc has no object: %d %d %d "
3102                                             TENDSTR), oldChunk,
3103                                             tags.objectId, tags.chunkId, tags.byteCount));
3104                                 }
3105
3106                                 if (object && 
3107                                     object->deleted &&
3108                                     object->softDeleted &&
3109                                     tags.chunkId != 0) {
3110                                         /* Data chunk in a soft deleted file, throw it away
3111                                          * It's a soft deleted data chunk,
3112                                          * No need to copy this, just forget about it and 
3113                                          * fix up the object.
3114                                          */
3115
3116                                         object->nDataChunks--;
3117
3118                                         if (object->nDataChunks <= 0) {
3119                                                 /* remeber to clean up the object */
3120                                                 dev->gcCleanupList[cleanups] =
3121                                                     tags.objectId;
3122                                                 cleanups++;
3123                                         }
3124                                         markNAND = 0;
3125                                 } else if (0
3126                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
3127                                            ) {
3128                                         /* Deleted object header with no data chunks.
3129                                          * Can be discarded and the file deleted.
3130                                          */
3131                                         object->hdrChunk = 0;
3132                                         yaffs_FreeTnode(object->myDev,
3133                                                         object->variant.
3134                                                         fileVariant.top);
3135                                         object->variant.fileVariant.top = NULL;
3136                                         yaffs_DoGenericObjectDeletion(object);
3137
3138                                 } else if (object) {
3139                                         /* It's either a data chunk in a live file or
3140                                          * an ObjectHeader, so we're interested in it.
3141                                          * NB Need to keep the ObjectHeaders of deleted files
3142                                          * until the whole file has been deleted off
3143                                          */
3144                                         tags.serialNumber++;
3145
3146                                         dev->nGCCopies++;
3147
3148                                         if (tags.chunkId == 0) {
3149                                                 /* It is an object Id,
3150                                                  * We need to nuke the shrinkheader flags first
3151                                                  * We no longer want the shrinkHeader flag since its work is done
3152                                                  * and if it is left in place it will mess up scanning.
3153                                                  * Also, clear out any shadowing stuff
3154                                                  */
3155
3156                                                 yaffs_ObjectHeader *oh;
3157                                                 oh = (yaffs_ObjectHeader *)buffer;
3158                                                 oh->isShrink = 0;
3159                                                 tags.extraShadows = 0;
3160                                                 tags.extraIsShrinkHeader = 0;
3161                                                 
3162                                                 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3163                                         }
3164
3165                                         newChunk =
3166                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3167
3168                                         if (newChunk < 0) {
3169                                                 retVal = YAFFS_FAIL;
3170                                         } else {
3171
3172                                                 /* Ok, now fix up the Tnodes etc. */
3173
3174                                                 if (tags.chunkId == 0) {
3175                                                         /* It's a header */
3176                                                         object->hdrChunk =  newChunk;
3177                                                         object->serial =   tags.serialNumber;
3178                                                 } else {
3179                                                         /* It's a data chunk */
3180                                                         yaffs_PutChunkIntoFile
3181                                                             (object,
3182                                                              tags.chunkId,
3183                                                              newChunk, 0);
3184                                                 }
3185                                         }
3186                                 }
3187
3188                                 if(retVal == YAFFS_OK)
3189                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3190
3191                         }
3192                 }
3193
3194                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3195                 
3196
3197
3198                 /* Do any required cleanups */
3199                 for (i = 0; i < cleanups; i++) {
3200                         /* Time to delete the file too */
3201                         object =
3202                             yaffs_FindObjectByNumber(dev,
3203                                                      dev->gcCleanupList[i]);
3204                         if (object) {
3205                                 yaffs_FreeTnode(dev,
3206                                                 object->variant.fileVariant.
3207                                                 top);
3208                                 object->variant.fileVariant.top = NULL;
3209                                 T(YAFFS_TRACE_GC,
3210                                   (TSTR
3211                                    ("yaffs: About to finally delete object %d"
3212                                     TENDSTR), object->objectId));
3213                                 yaffs_DoGenericObjectDeletion(object);
3214                                 object->myDev->nDeletedFiles--;
3215                         }
3216
3217                 }
3218
3219         }
3220
3221         yaffs_VerifyCollectedBlock(dev,bi,block);
3222           
3223         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3224                 T(YAFFS_TRACE_GC,
3225                   (TSTR
3226                    ("gc did not increase free chunks before %d after %d"
3227                     TENDSTR), chunksBefore, chunksAfter));
3228         }
3229
3230         /* If the gc completed then clear the current gcBlock so that we find another. */
3231         if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3232                 dev->gcBlock = -1;
3233                 dev->gcChunk = 0;
3234         }
3235         
3236         dev->isDoingGC = 0;
3237
3238         return retVal;
3239 }
3240
3241 /* New garbage collector
3242  * If we're very low on erased blocks then we do aggressive garbage collection
3243  * otherwise we do "leasurely" garbage collection.
3244  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3245  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3246  *
3247  * The idea is to help clear out space in a more spread-out manner.
3248  * Dunno if it really does anything useful.
3249  */
3250 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3251 {
3252         int block;
3253         int aggressive;
3254         int gcOk = YAFFS_OK;
3255         int maxTries = 0;
3256         
3257         int checkpointBlockAdjust;
3258
3259         if (dev->isDoingGC) {
3260                 /* Bail out so we don't get recursive gc */
3261                 return YAFFS_OK;
3262         }
3263         
3264         /* This loop should pass the first time.
3265          * We'll only see looping here if the erase of the collected block fails.
3266          */
3267
3268         do {
3269                 maxTries++;
3270                 
3271                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3272                 if(checkpointBlockAdjust < 0)
3273                         checkpointBlockAdjust = 0;
3274
3275                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3276                         /* We need a block soon...*/
3277                         aggressive = 1;
3278                 } else {
3279                         /* We're in no hurry */
3280                         aggressive = 0;
3281                 }
3282
3283                 if(dev->gcBlock <= 0){
3284                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3285                         dev->gcChunk = 0;
3286                 }
3287                 
3288                 block = dev->gcBlock;
3289
3290                 if (block > 0) {
3291                         dev->garbageCollections++;
3292                         if (!aggressive) {
3293                                 dev->passiveGarbageCollections++;
3294                         }
3295
3296                         T(YAFFS_TRACE_GC,
3297                           (TSTR
3298                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3299                            dev->nErasedBlocks, aggressive));
3300
3301                         gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3302                 }
3303
3304                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3305                         T(YAFFS_TRACE_GC,
3306                           (TSTR
3307                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3308                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3309                 }
3310         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && 
3311                  (block > 0) &&
3312                  (maxTries < 2));
3313
3314         return aggressive ? gcOk : YAFFS_OK;
3315 }
3316
3317 /*-------------------------  TAGS --------------------------------*/
3318
3319 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3320                            int chunkInObject)
3321 {
3322         return (tags->chunkId == chunkInObject &&
3323                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3324
3325 }
3326
3327
3328 /*-------------------- Data file manipulation -----------------*/
3329
3330 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3331                                  yaffs_ExtendedTags * tags)
3332 {
3333         /*Get the Tnode, then get the level 0 offset chunk offset */
3334         yaffs_Tnode *tn;
3335         int theChunk = -1;
3336         yaffs_ExtendedTags localTags;
3337         int retVal = -1;
3338
3339         yaffs_Device *dev = in->myDev;
3340
3341         if (!tags) {
3342                 /* Passed a NULL, so use our own tags space */
3343                 tags = &localTags;
3344         }
3345
3346         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3347
3348         if (tn) {
3349                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3350
3351                 retVal =
3352                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3353                                            chunkInInode);
3354         }
3355         return retVal;
3356 }
3357
3358 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3359                                           yaffs_ExtendedTags * tags)
3360 {
3361         /* Get the Tnode, then get the level 0 offset chunk offset */
3362         yaffs_Tnode *tn;
3363         int theChunk = -1;
3364         yaffs_ExtendedTags localTags;
3365
3366         yaffs_Device *dev = in->myDev;
3367         int retVal = -1;
3368
3369         if (!tags) {
3370                 /* Passed a NULL, so use our own tags space */
3371                 tags = &localTags;
3372         }
3373
3374         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3375
3376         if (tn) {
3377
3378                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3379
3380                 retVal =
3381                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3382                                            chunkInInode);
3383
3384                 /* Delete the entry in the filestructure (if found) */
3385                 if (retVal != -1) {
3386                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3387                 }
3388         } else {
3389                 /*T(("No level 0 found for %d\n", chunkInInode)); */
3390         }
3391
3392         if (retVal == -1) {
3393                 /* T(("Could not find %d to delete\n",chunkInInode)); */
3394         }
3395         return retVal;
3396 }
3397
3398 #ifdef YAFFS_PARANOID
3399
3400 static int yaffs_CheckFileSanity(yaffs_Object * in)
3401 {
3402         int chunk;
3403         int nChunks;
3404         int fSize;
3405         int failed = 0;
3406         int objId;
3407         yaffs_Tnode *tn;
3408         yaffs_Tags localTags;
3409         yaffs_Tags *tags = &localTags;
3410         int theChunk;
3411         int chunkDeleted;
3412
3413         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3414                 /* T(("Object not a file\n")); */
3415                 return YAFFS_FAIL;
3416         }
3417
3418         objId = in->objectId;
3419         fSize = in->variant.fileVariant.fileSize;
3420         nChunks =
3421             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3422
3423         for (chunk = 1; chunk <= nChunks; chunk++) {
3424                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3425                                            chunk);
3426
3427                 if (tn) {
3428
3429                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3430
3431                         if (yaffs_CheckChunkBits
3432                             (dev, theChunk / dev->nChunksPerBlock,
3433                              theChunk % dev->nChunksPerBlock)) {
3434
3435                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3436                                                             tags,
3437                                                             &chunkDeleted);
3438                                 if (yaffs_TagsMatch
3439                                     (tags, in->objectId, chunk, chunkDeleted)) {
3440                                         /* found it; */
3441
3442                                 }
3443                         } else {
3444
3445                                 failed = 1;
3446                         }
3447
3448                 } else {
3449                         /* T(("No level 0 found for %d\n", chunk)); */
3450                 }
3451         }
3452
3453         return failed ? YAFFS_FAIL : YAFFS_OK;
3454 }
3455
3456 #endif
3457
3458 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3459                                   int chunkInNAND, int inScan)
3460 {
3461         /* NB inScan is zero unless scanning. 
3462          * For forward scanning, inScan is > 0; 
3463          * for backward scanning inScan is < 0
3464          */
3465          
3466         yaffs_Tnode *tn;
3467         yaffs_Device *dev = in->myDev;
3468         int existingChunk;
3469         yaffs_ExtendedTags existingTags;
3470         yaffs_ExtendedTags newTags;
3471         unsigned existingSerial, newSerial;
3472
3473         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3474                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3475                  * If it is not during Scanning then something went wrong!
3476                  */
3477                 if (!inScan) {
3478                         T(YAFFS_TRACE_ERROR,
3479                           (TSTR
3480                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3481                             TENDSTR)));
3482                         YBUG();
3483                 }
3484
3485                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3486                 return YAFFS_OK;
3487         }
3488
3489         tn = yaffs_AddOrFindLevel0Tnode(dev, 
3490                                         &in->variant.fileVariant,
3491                                         chunkInInode,
3492                                         NULL);
3493         if (!tn) {
3494                 return YAFFS_FAIL;
3495         }
3496
3497         existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3498
3499         if (inScan != 0) {
3500                 /* If we're scanning then we need to test for duplicates
3501                  * NB This does not need to be efficient since it should only ever 
3502                  * happen when the power fails during a write, then only one
3503                  * chunk should ever be affected.
3504                  *
3505                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3506                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3507                  */
3508
3509                 if (existingChunk > 0) {
3510                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3511                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3512                          *
3513                          * We have a duplicate now we need to decide which one to use:
3514                          *
3515                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3516                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3517                          * YAFFS1: Get both sets of tags and compare serial numbers.
3518                          */
3519
3520                         if (inScan > 0) {
3521                                 /* Only do this for forward scanning */
3522                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3523                                                                 chunkInNAND,
3524                                                                 NULL, &newTags);
3525
3526                                 /* Do a proper find */
3527                                 existingChunk =
3528                                     yaffs_FindChunkInFile(in, chunkInInode,
3529                                                           &existingTags);
3530                         }
3531
3532                         if (existingChunk <= 0) {
3533                                 /*Hoosterman - how did this happen? */
3534
3535                                 T(YAFFS_TRACE_ERROR,
3536                                   (TSTR
3537                                    ("yaffs tragedy: existing chunk < 0 in scan"
3538                                     TENDSTR)));
3539
3540                         }
3541
3542                         /* NB The deleted flags should be false, otherwise the chunks will 
3543                          * not be loaded during a scan
3544                          */
3545
3546                         if(inScan > 0) {
3547                                 newSerial = newTags.serialNumber;
3548                                 existingSerial = existingTags.serialNumber;
3549                         }
3550
3551                         if ((inScan > 0) &&
3552                             (in->myDev->isYaffs2 ||
3553                              existingChunk <= 0 ||
3554                              ((existingSerial + 1) & 3) == newSerial)) {
3555                                 /* Forward scanning.                            
3556                                  * Use new
3557                                  * Delete the old one and drop through to update the tnode
3558                                  */
3559                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3560                                                   __LINE__);
3561                         } else {
3562                                 /* Backward scanning or we want to use the existing one
3563                                  * Use existing.
3564                                  * Delete the new one and return early so that the tnode isn't changed
3565                                  */
3566                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3567                                                   __LINE__);
3568                                 return YAFFS_OK;
3569                         }
3570                 }
3571
3572         }
3573
3574         if (existingChunk == 0) {
3575                 in->nDataChunks++;
3576         }
3577
3578         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3579
3580         return YAFFS_OK;
3581 }
3582
3583 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3584                                          __u8 * buffer)
3585 {
3586         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3587
3588         if (chunkInNAND >= 0) {
3589                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3590                                                        buffer,NULL);
3591         } else {
3592                 T(YAFFS_TRACE_NANDACCESS,
3593                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3594                    chunkInNAND));
3595                 /* get sane (zero) data if you read a hole */
3596                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);       
3597                 return 0;
3598         }
3599
3600 }
3601
3602 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3603 {
3604         int block;
3605         int page;
3606         yaffs_ExtendedTags tags;
3607         yaffs_BlockInfo *bi;
3608
3609         if (chunkId <= 0)
3610                 return;
3611                 
3612
3613         dev->nDeletions++;
3614         block = chunkId / dev->nChunksPerBlock;
3615         page = chunkId % dev->nChunksPerBlock;
3616
3617
3618         if(!yaffs_CheckChunkBit(dev,block,page))
3619                 T(YAFFS_TRACE_VERIFY,
3620                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3621                          chunkId));
3622
3623         bi = yaffs_GetBlockInfo(dev, block);
3624
3625         T(YAFFS_TRACE_DELETION,
3626           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3627
3628         if (markNAND &&
3629             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3630
3631                 yaffs_InitialiseTags(&tags);
3632
3633                 tags.chunkDeleted = 1;
3634
3635                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3636                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3637         } else {
3638                 dev->nUnmarkedDeletions++;
3639         }
3640
3641         /* Pull out of the management area.
3642          * If the whole block became dirty, this will kick off an erasure.
3643          */
3644         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3645             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3646             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3647             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3648                 dev->nFreeChunks++;
3649
3650                 yaffs_ClearChunkBit(dev, block, page);
3651
3652                 bi->pagesInUse--;
3653
3654                 if (bi->pagesInUse == 0 &&
3655                     !bi->hasShrinkHeader &&
3656                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3657                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3658                         yaffs_BlockBecameDirty(dev, block);
3659                 }
3660
3661         } else {
3662                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3663         }
3664
3665 }
3666
3667 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3668                                         const __u8 * buffer, int nBytes,
3669                                         int useReserve)
3670 {
3671         /* Find old chunk Need to do this to get serial number
3672          * Write new one and patch into tree.
3673          * Invalidate old tags.
3674          */
3675
3676         int prevChunkId;
3677         yaffs_ExtendedTags prevTags;
3678
3679         int newChunkId;
3680         yaffs_ExtendedTags newTags;
3681
3682         yaffs_Device *dev = in->myDev;
3683
3684         yaffs_CheckGarbageCollection(dev);
3685
3686         /* Get the previous chunk at this location in the file if it exists */
3687         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3688
3689         /* Set up new tags */
3690         yaffs_InitialiseTags(&newTags);
3691
3692         newTags.chunkId = chunkInInode;
3693         newTags.objectId = in->objectId;
3694         newTags.serialNumber =
3695             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3696         newTags.byteCount = nBytes;
3697         
3698         if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3699           T(YAFFS_TRACE_ERROR,
3700           (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3701           while(1){}
3702         }
3703         
3704         
3705
3706         newChunkId =
3707             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3708                                               useReserve);
3709
3710         if (newChunkId >= 0) {
3711                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3712
3713                 if (prevChunkId >= 0) {
3714                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3715
3716                 }
3717
3718                 yaffs_CheckFileSanity(in);
3719         }
3720         return newChunkId;
3721
3722 }
3723
3724 /* UpdateObjectHeader updates the header on NAND for an object.
3725  * If name is not NULL, then that new name is used.
3726  */
3727 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3728                              int isShrink, int shadows)
3729 {
3730
3731         yaffs_BlockInfo *bi;
3732
3733         yaffs_Device *dev = in->myDev;
3734
3735         int prevChunkId;
3736         int retVal = 0;
3737         int result = 0;
3738
3739         int newChunkId;
3740         yaffs_ExtendedTags newTags;
3741         yaffs_ExtendedTags oldTags;
3742
3743         __u8 *buffer = NULL;
3744         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3745
3746         yaffs_ObjectHeader *oh = NULL;
3747         
3748         yaffs_strcpy(oldName,_Y("silly old name"));
3749
3750
3751         if (!in->fake || 
3752             in == dev->rootDir || /* The rootDir should also be saved */
3753             force) {
3754
3755                 yaffs_CheckGarbageCollection(dev);
3756                 yaffs_CheckObjectDetailsLoaded(in);
3757
3758                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3759                 oh = (yaffs_ObjectHeader *) buffer;
3760
3761                 prevChunkId = in->hdrChunk;
3762
3763                 if (prevChunkId > 0) {
3764                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3765                                                         buffer, &oldTags);
3766                         
3767                         yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3768                                                                                 
3769                         memcpy(oldName, oh->name, sizeof(oh->name));
3770                 }
3771
3772                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3773
3774                 oh->type = in->variantType;
3775                 oh->yst_mode = in->yst_mode;
3776                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3777
3778 #ifdef CONFIG_YAFFS_WINCE
3779                 oh->win_atime[0] = in->win_atime[0];
3780                 oh->win_ctime[0] = in->win_ctime[0];
3781                 oh->win_mtime[0] = in->win_mtime[0];
3782                 oh->win_atime[1] = in->win_atime[1];
3783                 oh->win_ctime[1] = in->win_ctime[1];
3784                 oh->win_mtime[1] = in->win_mtime[1];
3785 #else
3786                 oh->yst_uid = in->yst_uid;
3787                 oh->yst_gid = in->yst_gid;
3788                 oh->yst_atime = in->yst_atime;
3789                 oh->yst_mtime = in->yst_mtime;
3790                 oh->yst_ctime = in->yst_ctime;
3791                 oh->yst_rdev = in->yst_rdev;
3792 #endif
3793                 if (in->parent) {
3794                         oh->parentObjectId = in->parent->objectId;
3795                 } else {
3796                         oh->parentObjectId = 0;
3797                 }
3798
3799                 if (name && *name) {
3800                         memset(oh->name, 0, sizeof(oh->name));
3801                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3802                 } else if (prevChunkId>=0) {
3803                         memcpy(oh->name, oldName, sizeof(oh->name));
3804                 } else {
3805                         memset(oh->name, 0, sizeof(oh->name));
3806                 }
3807
3808                 oh->isShrink = isShrink;
3809
3810                 switch (in->variantType) {
3811                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3812                         /* Should not happen */
3813                         break;
3814                 case YAFFS_OBJECT_TYPE_FILE:
3815                         oh->fileSize =
3816                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3817                              || oh->parentObjectId ==
3818                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3819                             fileVariant.fileSize;
3820                         break;
3821                 case YAFFS_OBJECT_TYPE_HARDLINK:
3822                         oh->equivalentObjectId =
3823                             in->variant.hardLinkVariant.equivalentObjectId;
3824                         break;
3825                 case YAFFS_OBJECT_TYPE_SPECIAL:
3826                         /* Do nothing */
3827                         break;
3828                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3829                         /* Do nothing */
3830                         break;
3831                 case YAFFS_OBJECT_TYPE_SYMLINK:
3832                         yaffs_strncpy(oh->alias,
3833                                       in->variant.symLinkVariant.alias,
3834                                       YAFFS_MAX_ALIAS_LENGTH);
3835                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3836                         break;
3837                 }
3838
3839                 /* Tags */
3840                 yaffs_InitialiseTags(&newTags);
3841                 in->serial++;
3842                 newTags.chunkId = 0;
3843                 newTags.objectId = in->objectId;
3844                 newTags.serialNumber = in->serial;
3845
3846                 /* Add extra info for file header */
3847
3848                 newTags.extraHeaderInfoAvailable = 1;
3849                 newTags.extraParentObjectId = oh->parentObjectId;
3850                 newTags.extraFileLength = oh->fileSize;
3851                 newTags.extraIsShrinkHeader = oh->isShrink;
3852                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3853                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3854                 newTags.extraObjectType = in->variantType;
3855
3856                 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3857
3858                 /* Create new chunk in NAND */
3859                 newChunkId =
3860                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3861                                                       (prevChunkId >= 0) ? 1 : 0);
3862
3863                 if (newChunkId >= 0) {
3864
3865                         in->hdrChunk = newChunkId;
3866
3867                         if (prevChunkId >= 0) {
3868                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3869                                                   __LINE__);
3870                         }
3871
3872                         if(!yaffs_ObjectHasCachedWriteData(in))
3873                                 in->dirty = 0;
3874
3875                         /* If this was a shrink, then mark the block that the chunk lives on */
3876                         if (isShrink) {
3877                                 bi = yaffs_GetBlockInfo(in->myDev,