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