*** empty log message ***
[yaffs/.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet another FFS. A NAND-flash specific file system.
3  * yaffs_guts.c  The main guts of YAFFS
4  *
5  * Copyright (C) 2002 Aleph One Ltd.
6  *   for Toby Churchill Ltd and Brightstar Engineering
7  *
8  * Created by Charles Manning <charles@aleph1.co.uk>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License version 2 as
12  * published by the Free Software Foundation.
13  *
14  */
15  //yaffs_guts.c
16
17 const char *yaffs_guts_c_version="$Id: yaffs_guts.c,v 1.24 2003-04-03 17:58:56 charles Exp $";
18
19 #include "yportenv.h"
20
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
23
24
25
26
27 #define YAFFS_PASSIVE_GC_CHUNKS 2
28
29 // External functions for ECC on data
30 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
31 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
32
33
34 // countBits is a quick way of counting the number of bits in a byte.
35 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
36
37 static const char yaffs_countBitsTable[256] =
38 {
39 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
40 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
41 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
42 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
43 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
44 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
45 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
46 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
47 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
48 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
49 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
50 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
51 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
52 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
53 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
54 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
55 };
56
57 static int yaffs_CountBits(__u8 x)
58 {
59         int retVal;
60         retVal = yaffs_countBitsTable[x];
61         return retVal;
62 }
63
64
65
66 // Local prototypes
67 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
68 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
69 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
70 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
71
72 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
73 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
74 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force);
75 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND);
76 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
77 static int yaffs_CheckStructures(void);
78 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
80
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
82
83 // Robustification
84 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
85 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
86 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
87 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare);
88 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare);
89
90 static int  yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
91
92 static int yaffs_UnlinkWorker(yaffs_Object *obj);
93 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj);
94
95 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1);
96
97
98
99 loff_t yaffs_GetFileSize(yaffs_Object *obj);
100
101 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
102 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
103
104
105 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
106
107 #ifdef YAFFS_PARANOID
108 static int yaffs_CheckFileSanity(yaffs_Object *in);
109 #else
110 #define yaffs_CheckFileSanity(in)
111 #endif
112
113 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
114 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
115
116 // Chunk bitmap manipulations
117
118 static __inline __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
119 {
120         if(blk < dev->startBlock || blk > dev->endBlock)
121         {
122                 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
123                 YBUG();
124         }
125         return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->startBlock));
126 }
127
128 static __inline__ void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
129 {
130         __u8 *blkBits = yaffs_BlockBits(dev,blk);
131
132          memset(blkBits,0,dev->chunkBitmapStride);
133 }
134
135 static __inline__ void yaffs_ClearChunkBit(yaffs_Device *dev,int blk,int chunk)
136 {
137         __u8 *blkBits = yaffs_BlockBits(dev,blk);
138         
139         blkBits[chunk/8] &=  ~ (1<<(chunk & 7));
140 }
141
142 static __inline__ void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
143 {
144         __u8 *blkBits = yaffs_BlockBits(dev,blk);
145
146         blkBits[chunk/8] |=   (1<<(chunk & 7));
147 }
148
149 static __inline__ int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
150 {
151         __u8 *blkBits = yaffs_BlockBits(dev,blk);
152         return (blkBits[chunk/8] &  (1<<(chunk & 7))) ? 1 :0;
153 }
154
155 static __inline__ int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
156 {
157         __u8 *blkBits = yaffs_BlockBits(dev,blk);
158         int i;
159         for(i = 0; i < dev->chunkBitmapStride; i++)
160         {
161                 if(*blkBits) return 1;
162                 blkBits++;
163         }
164         return 0;
165 }
166
167 // Function to manipulate block info
168 static  __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
169 {
170         if(blk < dev->startBlock || blk > dev->endBlock)
171         {
172                 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),blk));
173                 YBUG();
174         }
175         return &dev->blockInfo[blk - dev->startBlock];
176 }
177
178
179 static  __inline__ int yaffs_HashFunction(int n)
180 {
181         return (n % YAFFS_NOBJECT_BUCKETS);
182 }
183
184
185 yaffs_Object *yaffs_Root(yaffs_Device *dev)
186 {
187         return dev->rootDir;
188 }
189
190 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
191 {
192         return dev->lostNFoundDir;
193 }
194
195
196 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
197 {
198         if(chunkInNAND < dev->startBlock * dev->nChunksPerBlock)
199         {
200                 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
201                 return YAFFS_FAIL;
202         }
203
204         dev->nPageWrites++;
205         return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
206 }
207
208
209
210 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
211                                                         int chunkInNAND, 
212                                                         __u8 *data, 
213                                                         yaffs_Spare *spare, 
214                                                         int doErrorCorrection)
215 {
216         int retVal;
217         yaffs_Spare localSpare;
218
219         dev->nPageReads++;
220         
221         
222
223         
224         if(!spare && data)
225         {
226                 // If we don't have a real spare, then we use a local one.
227                 // Need this for the calculation of the ecc
228                 spare = &localSpare;
229         }
230         
231
232         if(!dev->useNANDECC)
233         {
234                 retVal  = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
235                 if(data && doErrorCorrection)
236                 {
237                         // Do ECC correction
238                         //Todo handle any errors
239                 int eccResult1,eccResult2;
240                 __u8 calcEcc[3];
241                 
242                         nand_calculate_ecc(data,calcEcc);
243                         eccResult1 = nand_correct_data (data,spare->ecc1, calcEcc);
244                         nand_calculate_ecc(&data[256],calcEcc);
245                         eccResult2 = nand_correct_data (&data[256],spare->ecc2, calcEcc);
246
247                         if(eccResult1>0)
248                         {
249                                 T(YAFFS_TRACE_ERROR, (TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
250                                 dev->eccFixed++;
251                         }
252                         else if(eccResult1<0)
253                         {
254                                 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
255                                 dev->eccUnfixed++;
256                         }
257
258                         if(eccResult2>0)
259                         {
260                                 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
261                                 dev->eccFixed++;
262                         }
263                         else if(eccResult2<0)
264                         {
265                                 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
266                                 dev->eccUnfixed++;
267                         }
268
269                         if(eccResult1 || eccResult2)
270                         {
271                                 // Hoosterman, we had a data problem on this page
272                                 yaffs_HandleReadDataError(dev,chunkInNAND);
273                         }
274                 }
275         }
276         else
277         {
278         // Must allocate enough memory for spare+2*sizeof(int) for ecc results from device.
279         struct yaffs_NANDSpare nspare;
280                 retVal  = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
281                 memcpy (spare, &nspare, sizeof(yaffs_Spare));
282                 if(data && doErrorCorrection)
283                 {
284                         if(nspare.eccres1>0)
285                         {
286                                 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
287                         }
288                         else if(nspare.eccres1<0)
289                         {
290                                 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
291                         }
292
293                         if(nspare.eccres2>0)
294                         {
295                                 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
296                         }
297                         else if(nspare.eccres2<0)
298                         {
299                                 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
300                         }
301
302                         if(nspare.eccres1 || nspare.eccres2)
303                         {
304                                 // Hoosterman, we had a data problem on this page
305                                 yaffs_HandleReadDataError(dev,chunkInNAND);
306                         }
307
308                 }
309         }
310         return retVal;
311 }
312
313
314 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
315 {
316
317         static int init = 0;
318         static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
319         static __u8 data[YAFFS_BYTES_PER_CHUNK];
320     // Might as well always allocate the larger size for dev->useNANDECC == true;
321         static __u8 spare[sizeof(struct yaffs_NANDSpare)];      
322
323         dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
324         
325         if(!init)
326         {
327                 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
328                 init = 1;
329         }
330         
331         if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return  YAFFS_FAIL;
332         if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
333
334         
335         return YAFFS_OK;
336         
337 }
338
339
340
341 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
342 {
343         dev->nBlockErasures++;
344         return dev->eraseBlockInNAND(dev,blockInNAND);
345 }
346
347 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
348 {
349         return dev->initialiseNAND(dev);
350 }
351
352 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
353 {
354         int chunk;
355         
356         int writeOk = 1;
357         int attempts = 0;
358         
359         unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
360         yaffs_Spare rbSpare;
361         
362         do{
363                 chunk = yaffs_AllocateChunk(dev,useReserve);
364         
365                 if(chunk >= 0)
366                 {
367
368                         // First check this chunk is erased...
369 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
370                         writeOk = yaffs_CheckChunkErased(dev,chunk);
371 #endif          
372                         if(!writeOk)
373                         {
374                                 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
375                         }
376                         else
377                         {
378                                 writeOk =  yaffs_WriteChunkToNAND(dev,chunk,data,spare);
379                         }
380                         attempts++;
381                         if(writeOk)
382                         {
383                                 // Readback & verify
384                                 // If verify fails, then delete this chunk and try again
385                                 // To verify we compare everything except the block and 
386                                 // page status bytes.
387                                 // NB We check a raw read without ECC correction applied
388                                 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
389                                 
390 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
391                                 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
392                                 {
393                                         // Didn't verify
394                                         T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
395
396                                         writeOk = 0;
397                                 }       
398 #endif                          
399                                 
400                         }
401                         if(writeOk)
402                         {
403                                 // Copy the data into the write buffer.
404                                 // NB We do this at the end to prevent duplicates in the case of a write error.
405                                 //Todo
406                                 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
407                         }
408                         else
409                         {
410                                 yaffs_HandleWriteChunkError(dev,chunk);
411                         }
412                 }
413                 
414         } while(chunk >= 0 && ! writeOk);
415         
416         if(attempts > 1)
417         {
418                 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
419                 dev->nRetriedWrites+= (attempts - 1);   
420         }
421         
422         return chunk;
423 }
424
425 ///
426 // Functions for robustisizing
427 //
428 //
429
430 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
431 {
432         // Ding the blockStatus in the first two pages of the block.
433         
434         yaffs_Spare spare;
435
436         memset(&spare, 0xff,sizeof(yaffs_Spare));
437
438         spare.blockStatus = 0;
439         
440         // TODO change this retirement marking for other NAND types
441         yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock, NULL , &spare);
442         yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock + 1, NULL , &spare);
443         
444         yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
445         dev->nRetiredBlocks++;
446 }
447
448
449
450 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
451 {
452         dev->doingBufferedBlockRewrite = 1;
453         //
454         //      Remove erased chunks
455         //  Rewrite existing chunks to a new block
456         //      Set current write block to the new block
457         
458         dev->doingBufferedBlockRewrite = 0;
459         
460         return 1;
461 }
462
463
464 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
465 {
466         int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
467
468         // Mark the block for retirement
469         yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
470         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
471
472
473         //TODO  
474         // Just do a garbage collection on the affected block then retire the block
475         // NB recursion
476 }
477
478
479 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
480 {
481 }
482
483 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare)
484 {
485 }
486
487 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare)
488 {
489 }
490
491 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
492 {
493         int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
494
495         // Mark the block for retirement
496         yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
497         // Delete the chunk
498         yaffs_DeleteChunk(dev,chunkInNAND,1);
499 }
500
501
502
503
504 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1)
505 {
506
507
508         if( memcmp(d0,d1,YAFFS_BYTES_PER_CHUNK) != 0 ||
509                 s0->tagByte0 != s1->tagByte0 ||
510                 s0->tagByte1 != s1->tagByte1 ||
511                 s0->tagByte2 != s1->tagByte2 ||
512                 s0->tagByte3 != s1->tagByte3 ||
513                 s0->tagByte4 != s1->tagByte4 ||
514                 s0->tagByte5 != s1->tagByte5 ||
515                 s0->tagByte6 != s1->tagByte6 ||
516                 s0->tagByte7 != s1->tagByte7 ||
517                 s0->ecc1[0]  != s1->ecc1[0]  ||
518                 s0->ecc1[1]  != s1->ecc1[1]  ||
519                 s0->ecc1[2]  != s1->ecc1[2]  ||
520                 s0->ecc2[0]  != s1->ecc2[0]  ||
521                 s0->ecc2[1]  != s1->ecc2[1]  ||
522                 s0->ecc2[2]  != s1->ecc2[2] )
523                 {
524                         return 0;
525                 }
526         
527         return 1;
528 }
529
530
531 ///////////////////////// Object management //////////////////
532 // List of spare objects
533 // The list is hooked together using the first pointer
534 // in the object
535
536 // static yaffs_Object *yaffs_freeObjects = NULL;
537
538 // static int yaffs_nFreeObjects;
539
540 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
541
542 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
543
544
545 static __u16 yaffs_CalcNameSum(const char *name)
546 {
547         __u16 sum = 0;
548         __u16 i = 1;
549         
550         __u8 *bname = (__u8 *)name;
551         if(bname)
552         {
553                 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
554                 {
555
556 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
557                         sum += toupper(*bname) * i;
558 #else
559                         sum += (*bname) * i;
560 #endif
561                         i++;
562                         bname++;
563                 }
564         }
565         return sum;
566 }
567
568 void yaffs_SetObjectName(yaffs_Object *obj, const char *name)
569 {
570 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
571                                         if(name && strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
572                                         {
573                                                 strcpy(obj->shortName,name);
574                                         }
575                                         else
576                                         {
577                                                 obj->shortName[0]='\0';
578                                         }
579 #endif
580                                         obj->sum = yaffs_CalcNameSum(name);
581 }
582
583 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
584 {
585         nand_calculate_ecc (data , spare->ecc1);
586         nand_calculate_ecc (&data[256] , spare->ecc2);
587 }
588
589 void yaffs_CalcTagsECC(yaffs_Tags *tags)
590 {
591         // Calculate an ecc
592         
593         unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
594         unsigned  i,j;
595         unsigned  ecc = 0;
596         unsigned bit = 0;
597
598         tags->ecc = 0;
599         
600         for(i = 0; i < 8; i++)
601         {
602                 for(j = 1; j &0xff; j<<=1)
603                 {
604                         bit++;
605                         if(b[i] & j)
606                         {
607                                 ecc ^= bit;
608                         }
609                 }
610         }
611         
612         tags->ecc = ecc;
613         
614         
615 }
616
617 int  yaffs_CheckECCOnTags(yaffs_Tags *tags)
618 {
619         unsigned ecc = tags->ecc;
620         
621         yaffs_CalcTagsECC(tags);
622         
623         ecc ^= tags->ecc;
624         
625         if(ecc && ecc <= 64)
626         {
627                 // TODO: Handle the failure better. Retire?
628                 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
629
630                 ecc--;
631                                 
632                 b[ecc / 8] ^= (1 << (ecc & 7));
633                 
634                 // Now recvalc the ecc
635                 yaffs_CalcTagsECC(tags);
636                 
637                 return 1; // recovered error
638         }
639         else if(ecc)
640         {
641                 // Wierd ecc failure value
642                 // TODO Need to do somethiong here
643                 return -1; //unrecovered error
644         }
645         
646         return 0;
647 }
648
649
650 ///////////////////////// TNODES ///////////////////////
651
652 // List of spare tnodes
653 // The list is hooked together using the first pointer
654 // in the tnode.
655
656 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
657
658 // static int yaffs_nFreeTnodes;
659
660 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
661
662
663
664 // yaffs_CreateTnodes creates a bunch more tnodes and
665 // adds them to the tnode free list.
666 // Don't use this function directly
667
668 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
669 {
670     int i;
671     yaffs_Tnode *newTnodes;
672     yaffs_TnodeList *tnl;
673     
674     if(nTnodes < 1) return YAFFS_OK;
675    
676         // make these things
677         
678     newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
679    
680     if (!newTnodes)
681     {
682                 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
683                 return YAFFS_FAIL;
684     }
685     
686     // Hook them into the free list
687     for(i = 0; i < nTnodes - 1; i++)
688     {
689         newTnodes[i].internal[0] = &newTnodes[i+1];
690 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
691         newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = 1;
692 #endif
693     }
694         
695         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
696 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
697         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = 1;
698 #endif
699         dev->freeTnodes = newTnodes;
700         dev->nFreeTnodes+= nTnodes;
701         dev->nTnodesCreated += nTnodes;
702
703         // Now add this bunch of tnodes to a list for freeing up.
704         // NB If we can't add this to the management list it isn't fatal
705         // but it just means we can't free this bunch of tnodes later.
706         tnl = YMALLOC(sizeof(yaffs_TnodeList));
707         if(!tnl)
708         {
709                 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
710                 
711         }
712         else
713         {
714                 tnl->tnodes = newTnodes;
715                 tnl->next = dev->allocatedTnodeList;
716                 dev->allocatedTnodeList = tnl;
717         }
718
719
720         T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
721
722
723         return YAFFS_OK;
724 }
725
726
727 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
728 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
729 {
730         yaffs_Tnode *tn = NULL;
731         
732         // If there are none left make more
733         if(!dev->freeTnodes)
734         {
735                 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
736         }
737         
738         if(dev->freeTnodes)
739         {
740                 tn = dev->freeTnodes;
741 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
742         if(tn->internal[YAFFS_NTNODES_INTERNAL] != 1)
743                 {
744                         // Hoosterman, this thing looks like it isn't in the list
745                                 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 1" TENDSTR)));
746                 }
747 #endif
748                 dev->freeTnodes = dev->freeTnodes->internal[0];
749                 dev->nFreeTnodes--;
750                 // zero out
751                 memset(tn,0,sizeof(yaffs_Tnode));
752         }
753         
754
755         return tn;
756 }
757
758
759 // FreeTnode frees up a tnode and puts it back on the free list
760 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
761 {
762         if(tn)
763         {
764 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
765         if(tn->internal[YAFFS_NTNODES_INTERNAL] != 0)
766                 {
767                         // Hoosterman, this thing looks like it is already in the list
768                                 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 2" TENDSTR)));
769                 }
770                 tn->internal[YAFFS_NTNODES_INTERNAL] = 1;
771 #endif
772                 tn->internal[0] = dev->freeTnodes;
773                 dev->freeTnodes = tn;
774                 dev->nFreeTnodes++;
775         }
776 }
777
778
779 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
780 {
781         // Free the list of allocated tnodes
782         
783         while(dev->allocatedTnodeList)
784         {
785                 YFREE(dev->allocatedTnodeList->tnodes);
786                 dev->allocatedTnodeList =  dev->allocatedTnodeList->next;
787         }
788         
789         dev->freeTnodes = NULL;
790         dev->nFreeTnodes = 0;
791 }
792
793 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
794 {
795         dev->allocatedTnodeList = NULL;
796         dev->freeTnodes = NULL;
797         dev->nFreeTnodes = 0;
798         dev->nTnodesCreated = 0;
799
800 }
801
802 #if 0
803 void yaffs_TnodeTest(yaffs_Device *dev)
804 {
805
806         int i;
807         int j;
808         yaffs_Tnode *tn[1000];
809         
810         YINFO("Testing TNodes");
811         
812         for(j = 0; j < 50; j++)
813         {
814                 for(i = 0; i < 1000; i++)
815                 {
816                         tn[i] = yaffs_GetTnode(dev);
817                         if(!tn[i])
818                         {
819                                 YALERT("Getting tnode failed");
820                         }
821                 }
822                 for(i = 0; i < 1000; i+=3)
823                 {
824                         yaffs_FreeTnode(dev,tn[i]);
825                         tn[i] = NULL;
826                 }
827                 
828         }
829 }
830 #endif
831
832
833 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
834
835 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
836 // The look up tree is represented by the top tnode and the number of topLevel
837 // in the tree. 0 means only the level 0 tnode is in the tree.
838
839
840 // FindLevel0Tnode finds the level 0 tnode, if one exists.
841 // Used when reading.....
842 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
843 {
844         
845         yaffs_Tnode *tn = fStruct->top;
846         __u32 i;
847         int requiredTallness;   
848         int level = fStruct->topLevel;
849         
850         // Check sane level and chunk Id
851         if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
852         {
853 //              char str[50];
854 //              sprintf(str,"Bad level %d",level);
855 //              YALERT(str);
856                 return NULL;
857         }
858         
859         if(chunkId > YAFFS_MAX_CHUNK_ID)
860         {
861 //              char str[50];
862 //              sprintf(str,"Bad chunkId %d",chunkId);
863 //              YALERT(str);
864                 return NULL;
865         }
866
867         // First check we're tall enough (ie enough topLevel)
868         
869         i = chunkId >> (/*dev->chunkGroupBits  + */YAFFS_TNODES_LEVEL0_BITS);
870         requiredTallness = 0;
871         while(i)
872         {
873                 i >>= YAFFS_TNODES_INTERNAL_BITS;
874                 requiredTallness++;
875         }
876         
877         
878         if(requiredTallness > fStruct->topLevel)
879         {
880                 // Not tall enough, so we can't find it, return NULL.
881                 return NULL;
882         }
883                 
884         
885         // Traverse down to level 0
886         while (level > 0 && tn)
887         {
888             tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) & 
889                                YAFFS_TNODES_INTERNAL_MASK]; 
890                 level--;
891         
892         }
893         
894         return tn;              
895 }
896
897 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
898 // This happens in two steps:
899 //  1. If the tree isn't tall enough, then make it taller.
900 //  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
901 //
902 // Used when modifying the tree.
903 //
904 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
905 {
906         
907         yaffs_Tnode *tn; 
908         
909         int requiredTallness;
910         int i;
911         int l;
912         
913         __u32 x;
914                 
915         
916         //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
917         
918         // Check sane level and page Id
919         if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
920         {
921 //              char str[50];
922 //              sprintf(str,"Bad level %d",fStruct->topLevel);
923 //              YALERT(str);
924                 return NULL;
925         }
926         
927         if(chunkId > YAFFS_MAX_CHUNK_ID)
928         {
929 //              char str[50];
930 //              sprintf(str,"Bad chunkId %d",chunkId);
931 //              YALERT(str);
932                 return NULL;
933         }
934         
935         // First check we're tall enough (ie enough topLevel)
936         
937         x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
938         requiredTallness = 0;
939         while(x)
940         {
941                 x >>= YAFFS_TNODES_INTERNAL_BITS;
942                 requiredTallness++;
943         }
944         
945         //T((TSTR(" required=%d"),requiredTallness));
946         
947         
948         if(requiredTallness > fStruct->topLevel)
949         {
950                 // Not tall enough,gotta make the tree taller
951                 for(i = fStruct->topLevel; i < requiredTallness; i++)
952                 {
953                         //T((TSTR(" add new top")));
954                         
955                         tn = yaffs_GetTnode(dev);
956                         
957                         if(tn)
958                         {
959                                 tn->internal[0] = fStruct->top;
960                                 fStruct->top = tn;
961                         }
962                         else
963                         {
964                                         T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
965                         }
966                 }
967                 
968                 fStruct->topLevel = requiredTallness;
969         }
970         
971         
972         // Traverse down to level 0, adding anything we need
973         
974         l = fStruct->topLevel;
975         tn = fStruct->top;
976         while (l > 0 && tn)
977         {
978                 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) & 
979                                YAFFS_TNODES_INTERNAL_MASK;
980                                
981                 //T((TSTR(" [%d:%d]"),l,i));
982                 
983             if(!tn->internal[x])
984             {
985                 //T((TSTR(" added")));
986                 
987                 tn->internal[x] = yaffs_GetTnode(dev);
988             }
989             
990             tn =        tn->internal[x];
991                 l--;
992         
993         }
994         
995         //TSTR(TENDSTR)));
996         
997         return tn;              
998 }
999
1000 // DeleteWorker scans backwards through the tnode tree and deletes all the
1001 // chunks and tnodes in the file
1002 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1003
1004 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1005 {
1006         int i;
1007         int chunkInInode;
1008         int theChunk;
1009         yaffs_Tags tags;
1010         int found;
1011         int chunkDeleted;
1012         int allDone = 1;
1013         
1014         
1015         if(tn)
1016         {
1017                 if(level > 0)
1018                 {
1019                 
1020                         for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1021                         {
1022                             if(tn->internal[i])
1023                         {
1024                                         if(limit && (*limit) < 0)
1025                                         {
1026                                                 allDone = 0;
1027                                         }
1028                                         else
1029                                         {
1030                                                 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1031                                                                                 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1032                                         }
1033                                         if(allDone)
1034                                         {
1035                                                 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1036                                         tn->internal[i] = NULL;
1037                                         }
1038                             }
1039                     
1040                         }
1041                         return (allDone) ? 1 : 0;
1042                 }
1043                 else if(level == 0)
1044                 {
1045                         int hitLimit = 0;
1046                         
1047                         for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1048                         {
1049                             if(tn->level0[i])
1050                         {
1051                                         int j;
1052                                         
1053                                         chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1054                                         
1055                                         theChunk =  tn->level0[i] << in->myDev->chunkGroupBits;
1056
1057                                         // Now we need to search for it
1058                                         for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
1059                                         {
1060                                                 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
1061                                                 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
1062                                                 {
1063                                                         // found it;
1064                                                         found = 1;
1065                                         
1066                                                 }
1067                                                 else
1068                                                 {
1069                                                         theChunk++;
1070                                                 }
1071                                         }
1072                                         
1073                                         if(found)
1074                                         {
1075                                                 yaffs_DeleteChunk(in->myDev,theChunk,1);
1076                                                 in->nDataChunks--;
1077                                                 if(limit)
1078                                                 { 
1079                                                         *limit = *limit-1;
1080                                                         if(limit <= 0) 
1081                                                         { 
1082                                                                 hitLimit = 1;
1083                                                         }
1084                                                 }
1085                                         
1086                                         }
1087                                         
1088                                 tn->level0[i] = 0;
1089                             }
1090                     
1091                         }
1092                         return (i < 0) ? 1 : 0;
1093
1094                         
1095                 }
1096                 
1097         }
1098         
1099         return 1;
1100         
1101 }
1102
1103 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1104 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1105 // of the tnode.
1106 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1107 //
1108 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1109 {
1110         int i;
1111         int chunkInInode;
1112         int theChunk;
1113         yaffs_BlockInfo *theBlock;
1114         yaffs_Tags tags;
1115         int found;
1116         int chunkDeleted;
1117         int allDone = 1;
1118         
1119         
1120         if(tn)
1121         {
1122                 if(level > 0)
1123                 {
1124                 
1125                         for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1126                         {
1127                             if(tn->internal[i])
1128                         {
1129                                                 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1130                                                                                 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1131                                         if(allDone)
1132                                         {
1133                                                 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1134                                         tn->internal[i] = NULL;
1135                                         }
1136                                         else
1137                                         {
1138                                                 //Hoosterman... how could this happen.
1139                                         }                           
1140                                 }                   
1141                         }
1142                         return (allDone) ? 1 : 0;
1143                 }
1144                 else if(level == 0)
1145                 {
1146                         
1147                         for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1148                         {
1149                             if(tn->level0[i])
1150                         {
1151                                         theChunk =  (tn->level0[i] << in->myDev->chunkGroupBits);
1152                                         T(YAFFS_TRACE_SCAN,(TSTR("soft delete tch %d cgb %d chunk %d" TENDSTR),
1153                                                 tn->level0[i],in->myDev->chunkGroupBits,theChunk));
1154                                                 
1155                                         theBlock =      yaffs_GetBlockInfo(in->myDev,  theChunk/in->myDev->nChunksPerBlock);
1156                                         if(theBlock)
1157                                         {
1158                                                 theBlock->softDeletions++;
1159                                         }
1160                                 tn->level0[i] = 0;
1161                             }
1162                     
1163                         }
1164                         return 1;
1165                         
1166                 }
1167                 
1168         }
1169         
1170         return 1;
1171                 
1172 }
1173
1174
1175
1176 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1177 {
1178         if(obj->deleted &&
1179            obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1180            !obj->softDeleted)
1181         {
1182                 if(obj->nDataChunks <= 0)
1183                 {
1184                                 // Empty file, just delete it immediately
1185                                 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1186                                 obj->variant.fileVariant.top = NULL;
1187                                 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1188                                 yaffs_DoGenericObjectDeletion(obj);     
1189                 }
1190                 else
1191                 {
1192                         yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1193                         obj->softDeleted = 1;
1194                 }
1195         }
1196 }
1197
1198
1199
1200
1201
1202 // Pruning removes any part of the file structure tree that is beyond the
1203 // bounds of the file (ie that does not point to chunks).
1204 //
1205 // A file should only get pruned when its size is reduced.
1206 //
1207 // Before pruning, the chunks must be pulled from the tree and the
1208 // level 0 tnode entries must be zeroed out.
1209 // Could also use this for file deletion, but that's probably better handled
1210 // by a special case.
1211
1212 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1213
1214 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1215 {
1216         int i;
1217         int hasData;
1218         
1219         if(tn)
1220         {
1221                 hasData = 0;
1222                 
1223                 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1224                 {
1225                     if(tn->internal[i] && level > 0)
1226                     {
1227                         tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1228                     }
1229                     
1230                     if(tn->internal[i])
1231                     {
1232                         hasData++;
1233                         }
1234                 }
1235                 
1236                 if(hasData == 0 && del0)
1237                 {
1238                         // Free and return NULL
1239                         
1240                         yaffs_FreeTnode(dev,tn);
1241                         tn = NULL;
1242                 }
1243                 
1244         }
1245
1246         return tn;
1247         
1248 }
1249
1250 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1251 {
1252         int i;
1253         int hasData;
1254         int done = 0;
1255         yaffs_Tnode *tn;
1256         
1257         if(fStruct->topLevel > 0)
1258         {
1259                 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1260                 
1261                 // Now we have a tree with all the non-zero branches NULL but the height
1262                 // is the same as it was.
1263                 // Let's see if we can trim internal tnodes to shorten the tree.
1264                 // We can do this if only the 0th element in the tnode is in use 
1265                 // (ie all the non-zero are NULL)
1266                 
1267                 while(fStruct->topLevel && !done)
1268                 {
1269                         tn = fStruct->top;
1270                         
1271                         hasData = 0;
1272                         for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1273                         {
1274                                 if(tn->internal[i])
1275                         {
1276                                 hasData++;
1277                                 }
1278                         }
1279                         
1280                         if(!hasData)
1281                         {
1282                                 fStruct->top = tn->internal[0];
1283                                 fStruct->topLevel--;
1284                                 yaffs_FreeTnode(dev,tn);
1285                         }
1286                         else
1287                         {
1288                                 done = 1;
1289                         }
1290                 }
1291         }
1292         
1293         return YAFFS_OK;
1294 }
1295
1296
1297
1298
1299
1300 /////////////////////// End of File Structure functions. /////////////////
1301
1302 // yaffs_CreateFreeObjects creates a bunch more objects and
1303 // adds them to the object free list.
1304 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1305 {
1306     int i;
1307     yaffs_Object *newObjects;
1308     yaffs_ObjectList *list;
1309     
1310     if(nObjects < 1) return YAFFS_OK;
1311    
1312         // make these things
1313         
1314     newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1315    
1316     if (!newObjects)
1317     {
1318                 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1319                 return YAFFS_FAIL;
1320     }
1321     
1322     // Hook them into the free list
1323     for(i = 0; i < nObjects - 1; i++)
1324     {
1325         newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1326     }
1327         
1328         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1329         dev->freeObjects = newObjects;
1330         dev->nFreeObjects+= nObjects;
1331         dev->nObjectsCreated+= nObjects;
1332         
1333         // Now add this bunch of Objects to a list for freeing up.
1334         
1335         list = YMALLOC(sizeof(yaffs_ObjectList));
1336         if(!list)
1337         {
1338                 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1339         }
1340         else
1341         {
1342                 list->objects = newObjects;
1343                 list->next = dev->allocatedObjectList;
1344                 dev->allocatedObjectList = list;
1345         }
1346         
1347         
1348         
1349         return YAFFS_OK;
1350 }
1351
1352
1353 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1354 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1355 {
1356         yaffs_Object *tn = NULL;
1357         
1358         // If there are none left make more
1359         if(!dev->freeObjects)
1360         {
1361                 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1362         }
1363         
1364         if(dev->freeObjects)
1365         {
1366                 tn = dev->freeObjects;
1367                 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1368                 dev->nFreeObjects--;
1369                 
1370                 // Now sweeten it up...
1371         
1372                 memset(tn,0,sizeof(yaffs_Object));
1373                 tn->myDev = dev;
1374                 tn->chunkId = -1;
1375                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1376                 INIT_LIST_HEAD(&(tn->hardLinks));
1377                 INIT_LIST_HEAD(&(tn->hashLink));
1378                 INIT_LIST_HEAD(&tn->siblings);
1379                 
1380                 // Add it to the lost and found directory.
1381                 // NB Can't put root or lostNFound in lostNFound so
1382                 // check if lostNFound exists first
1383                 if(dev->lostNFoundDir)
1384                 {
1385                         yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);      
1386                 }
1387         }
1388         
1389
1390         return tn;
1391 }
1392
1393 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1394 {
1395
1396         yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);              
1397         if(obj)
1398         {
1399                 obj->fake = 1;                  // it is fake so it has no NAND presence...
1400                 obj->renameAllowed= 0;  // ... and we're not allowed to rename it...
1401                 obj->unlinkAllowed= 0;  // ... or unlink it
1402                 obj->deleted = 0;
1403                 obj->unlinked = 0;
1404                 obj->st_mode = mode;
1405                 obj->myDev = dev;
1406                 obj->chunkId = 0; // Not a valid chunk.
1407         }
1408         
1409         return obj;
1410         
1411 }
1412
1413
1414 static void yaffs_UnhashObject(yaffs_Object *tn)
1415 {
1416         int bucket;
1417         yaffs_Device *dev = tn->myDev;
1418         
1419         
1420         // If it is still linked into the bucket list, free from the list
1421         if(!list_empty(&tn->hashLink))
1422         {
1423                 list_del_init(&tn->hashLink);
1424                 bucket =  yaffs_HashFunction(tn->objectId);
1425                 dev->objectBucket[bucket].count--;
1426         }
1427         
1428 }
1429
1430
1431 // FreeObject frees up a Object and puts it back on the free list
1432 static void yaffs_FreeObject(yaffs_Object *tn)
1433 {
1434
1435         yaffs_Device *dev = tn->myDev;
1436         
1437         yaffs_UnhashObject(tn);
1438         
1439         // Link into the free list.
1440         tn->siblings.next = (struct list_head *)(dev->freeObjects);
1441         dev->freeObjects = tn;
1442         dev->nFreeObjects++;
1443 }
1444
1445
1446
1447
1448 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1449 {
1450         // Free the list of allocated Objects
1451         
1452         while( dev->allocatedObjectList)
1453         {
1454                 YFREE(dev->allocatedObjectList->objects);
1455                 dev->allocatedObjectList =  dev->allocatedObjectList->next;
1456         }
1457         
1458         dev->freeObjects = NULL;
1459         dev->nFreeObjects = 0;
1460 }
1461
1462 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1463 {
1464         int i;
1465         
1466         dev->allocatedObjectList = NULL;
1467         dev->freeObjects = NULL;
1468         dev->nFreeObjects = 0;
1469         
1470         for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1471         {
1472                 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1473                 dev->objectBucket[i].count = 0; 
1474         }
1475
1476 }
1477
1478
1479
1480
1481
1482
1483 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1484 {
1485         static int x = 0;
1486         int i;
1487         int l = 999;
1488         int lowest = 999999;
1489
1490                 
1491         // First let's see if we can find one that's empty.
1492         
1493         for(i = 0; i < 10 && lowest > 0; i++)
1494          {
1495                 x++;
1496                 x %=  YAFFS_NOBJECT_BUCKETS;
1497                 if(dev->objectBucket[x].count < lowest)
1498                 {
1499                         lowest = dev->objectBucket[x].count;
1500                         l = x;
1501                 }
1502                 
1503         }
1504         
1505         // If we didn't find an empty list, then try
1506         // looking a bit further for a short one
1507         
1508         for(i = 0; i < 10 && lowest > 3; i++)
1509          {
1510                 x++;
1511                 x %=  YAFFS_NOBJECT_BUCKETS;
1512                 if(dev->objectBucket[x].count < lowest)
1513                 {
1514                         lowest = dev->objectBucket[x].count;
1515                         l = x;
1516                 }
1517                 
1518         }
1519         
1520         return l;
1521 }
1522
1523 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1524 {
1525         int bucket = yaffs_FindNiceObjectBucket(dev);
1526         
1527         // Now find an object value that has not already been taken
1528         // by scanning the list.
1529         
1530         int found = 0;
1531         struct list_head *i;
1532         
1533         __u32 n = (__u32)bucket;
1534
1535         //yaffs_CheckObjectHashSanity();        
1536         
1537         while(!found)
1538         {
1539                 found = 1;
1540                 n +=  YAFFS_NOBJECT_BUCKETS;
1541                 if(1 ||dev->objectBucket[bucket].count > 0)
1542                 {
1543                         list_for_each(i,&dev->objectBucket[bucket].list)
1544                         {
1545                                 // If there is already one in the list
1546                                 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1547                                 {
1548                                         found = 0;
1549                                 }
1550                         }
1551                 }
1552         }
1553         
1554         //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1555         
1556         return n;       
1557 }
1558
1559 void yaffs_HashObject(yaffs_Object *in)
1560 {
1561         int bucket = yaffs_HashFunction(in->objectId);
1562         yaffs_Device *dev = in->myDev;
1563         
1564         if(!list_empty(&in->hashLink))
1565         {
1566                 //YINFO("!!!");
1567         }
1568
1569         
1570         list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1571         dev->objectBucket[bucket].count++;
1572
1573 }
1574
1575 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1576 {
1577         int bucket = yaffs_HashFunction(number);
1578         struct list_head *i;
1579         yaffs_Object *in;
1580         
1581         list_for_each(i,&dev->objectBucket[bucket].list)
1582         {
1583                 // Look if it is in the list
1584                 if(i)
1585                 {
1586                         in = list_entry(i, yaffs_Object,hashLink);
1587                         if(in->objectId == number)
1588                         {
1589                                 return in;
1590                         }
1591                 }
1592         }
1593         
1594         return NULL;
1595 }
1596
1597
1598
1599 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1600 {
1601                 
1602         yaffs_Object *theObject;
1603
1604         if(number < 0)
1605         {
1606                 number = yaffs_CreateNewObjectNumber(dev);
1607         }
1608         
1609         theObject = yaffs_AllocateEmptyObject(dev);
1610         
1611         if(theObject)
1612         {
1613                 theObject->fake = 0;
1614                 theObject->renameAllowed = 1;
1615                 theObject->unlinkAllowed = 1;
1616                 theObject->objectId = number;
1617                 yaffs_HashObject(theObject);
1618                 theObject->variantType = type;
1619 #ifdef CONFIG_YAFFS_WINCE
1620                 yfsd_WinFileTimeNow(theObject->win_atime);
1621                 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1622                 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1623
1624 #else
1625                 theObject->st_atime = theObject->st_mtime =     theObject->st_ctime = CURRENT_TIME;
1626 #endif
1627                 switch(type)
1628                 {
1629                         case YAFFS_OBJECT_TYPE_FILE: 
1630                                 theObject->variant.fileVariant.fileSize = 0;
1631                                 theObject->variant.fileVariant.scannedFileSize = 0;
1632                                 theObject->variant.fileVariant.topLevel = 0;
1633                                 theObject->variant.fileVariant.top  = yaffs_GetTnode(dev);
1634                                 break;
1635                         case YAFFS_OBJECT_TYPE_DIRECTORY:
1636                                 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1637                                 break;
1638                         case YAFFS_OBJECT_TYPE_SYMLINK:
1639                                 // No action required
1640                                 break;
1641                         case YAFFS_OBJECT_TYPE_HARDLINK:
1642                                 // No action required
1643                                 break;
1644                         case YAFFS_OBJECT_TYPE_SPECIAL:
1645                                 // No action required
1646                                 break;
1647                         case YAFFS_OBJECT_TYPE_UNKNOWN:
1648                                 // todo this should not happen
1649                                 break;
1650                 }
1651         }
1652         
1653         return theObject;
1654 }
1655
1656 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1657 {
1658         yaffs_Object *theObject = NULL;
1659         
1660         if(number > 0)
1661         {
1662                 theObject = yaffs_FindObjectByNumber(dev,number);
1663         }
1664         
1665         if(!theObject)
1666         {
1667                 theObject = yaffs_CreateNewObject(dev,number,type);
1668         }
1669         
1670         return theObject;
1671
1672 }
1673
1674 char *yaffs_CloneString(const char *str)
1675 {
1676         char *newStr = NULL;
1677         
1678         if(str && *str)
1679         {
1680                 newStr = YMALLOC(strlen(str) + 1);
1681                 strcpy(newStr,str);
1682         }
1683
1684         return newStr;
1685         
1686 }
1687
1688 //
1689 // Mknod (create) a new object.
1690 // equivalentObject only has meaning for a hard link;
1691 // aliasString only has meaning for a sumlink.
1692 // rdev only has meaning for devices (a subset of special objects)
1693 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1694                                                                  yaffs_Object *parent,
1695                                                                  const char *name, 
1696                                                                  __u32 mode,
1697                                                                  __u32 uid,
1698                                                                  __u32 gid,
1699                                                                  yaffs_Object *equivalentObject,
1700                                                                  const char *aliasString,
1701                                                                  __u32 rdev)
1702 {
1703         yaffs_Object *in;
1704
1705         yaffs_Device *dev = parent->myDev;
1706         
1707         // Check if the entry exists. If it does then fail the call since we don't want a dup.
1708         if(yaffs_FindObjectByName(parent,name))
1709         {
1710                 return NULL;
1711         }
1712         
1713         in = yaffs_CreateNewObject(dev,-1,type);
1714         
1715         if(in)
1716         {
1717                 in->chunkId = -1;
1718                 in->valid = 1;
1719                 in->variantType = type;
1720
1721                 in->st_mode  = mode;
1722                 
1723 #ifdef CONFIG_YAFFS_WINCE
1724                 yfsd_WinFileTimeNow(in->win_atime);
1725                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1726                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[0];
1727                 
1728 #else
1729                 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1730                 in->st_rdev  = rdev;
1731                 in->st_uid   = uid;
1732                 in->st_gid   = gid;
1733 #endif          
1734                 in->nDataChunks = 0;
1735
1736                 yaffs_SetObjectName(in,name);
1737                 in->dirty = 1;
1738                 
1739                 yaffs_AddObjectToDirectory(parent,in);
1740                 
1741                 in->myDev = parent->myDev;
1742                 
1743                                 
1744                 switch(type)
1745                 {
1746                         case YAFFS_OBJECT_TYPE_SYMLINK:
1747                                 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1748                                 break;
1749                         case YAFFS_OBJECT_TYPE_HARDLINK:
1750                                 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1751                                 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1752                                 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1753                                 break;
1754                         case YAFFS_OBJECT_TYPE_FILE: // do nothing
1755                         case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1756                         case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1757                         case YAFFS_OBJECT_TYPE_UNKNOWN:
1758                                 break;
1759                 }
1760
1761                 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1762                    yaffs_UpdateObjectHeader(in,name,0) < 0)
1763                 {
1764                         // Could not create the object header, fail the creation
1765                         yaffs_AbortHalfCreatedObject(in);
1766                         in = NULL;
1767                 }
1768
1769         }
1770         
1771         return in;
1772 }
1773
1774 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1775 {
1776         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1777 }
1778
1779 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1780 {
1781         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1782 }
1783
1784 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1785 {
1786         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1787 }
1788
1789 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1790 {
1791         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1792 }
1793
1794 // NB yaffs_Link returns the object id of the equivalent object.
1795 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1796 {
1797         // Get the real object in case we were fed a hard link as an equivalent object
1798         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1799         
1800         if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1801         {
1802                 return equivalentObject;
1803         }
1804         else
1805         {
1806                 return NULL;
1807         }
1808         
1809 }
1810
1811
1812 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1813 {
1814         int unlinkOp;
1815
1816         if(newDir == NULL)
1817         {
1818                 newDir = obj->parent; // use the old directory
1819         }
1820
1821         unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1822         
1823         // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1824         // duplicate names are allowed.
1825         // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1826         if( (unlinkOp|| 
1827                  force || 
1828                  !yaffs_FindObjectByName(newDir,newName))  &&
1829              newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1830         {
1831                 yaffs_SetObjectName(obj,newName);
1832                 obj->dirty = 1;
1833                 
1834                 yaffs_AddObjectToDirectory(newDir,obj);
1835                 
1836                 if(unlinkOp) obj->unlinked = 1;
1837                 
1838                 
1839                 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1840                 {
1841                         return YAFFS_OK;
1842                 }
1843         }
1844         
1845         return YAFFS_FAIL;
1846 }
1847
1848
1849
1850 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1851 {
1852         yaffs_Object *obj;
1853         int force = 0;
1854         
1855 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1856         // Special case for WinCE.
1857         // While look-up is case insensitive, the name isn't.
1858         // THerefore we might want to change x.txt to X.txt
1859         if(oldDir == newDir && _stricmp(oldName,newName) == 0)
1860         {
1861                 force = 1;
1862         }       
1863 #endif
1864         
1865         obj = yaffs_FindObjectByName(oldDir,oldName);
1866         if(obj && obj->renameAllowed)
1867         {
1868                 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1869         }
1870         return YAFFS_FAIL;
1871 }
1872
1873
1874
1875 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1876 {
1877         // Scan the buckets and check that the lists 
1878         // have as many members as the count says there are
1879         int bucket;
1880         int countEm;
1881         struct list_head *j;
1882         int ok = YAFFS_OK;
1883         
1884         for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1885         {
1886                 countEm = 0;
1887                 
1888                 list_for_each(j,&dev->objectBucket[bucket].list)
1889                 {
1890                         countEm++;
1891                 }
1892                 
1893                 if(countEm != dev->objectBucket[bucket].count)
1894                 {
1895                         T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1896                         ok = YAFFS_FAIL;
1897                 }
1898         }
1899
1900         return ok;
1901 }
1902
1903 #if 0
1904 void yaffs_ObjectTest(yaffs_Device *dev)
1905 {
1906         yaffs_Object *in[1000];
1907         int inNo[1000];
1908         yaffs_Object *inold[1000];
1909         int i;
1910         int j;
1911         
1912         memset(in,0,1000*sizeof(yaffs_Object *));
1913         memset(inold,0,1000*sizeof(yaffs_Object *));
1914         
1915         yaffs_CheckObjectHashSanity(dev);
1916         
1917         for(j = 0; j < 10; j++)
1918         {
1919                 //T(("%d\n",j));
1920                 
1921                 for(i = 0; i < 1000; i++)
1922                 {
1923                         in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1924                         if(!in[i])
1925                         {
1926                                 YINFO("No more inodes");
1927                         }
1928                         else
1929                         {
1930                                 inNo[i] = in[i]->objectId;
1931                         }
1932                 }
1933                 
1934                 for(i = 0; i < 1000; i++)
1935                 {
1936                         if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1937                         {
1938                                 //T(("Differnce in look up test\n"));
1939                         }
1940                         else
1941                         {
1942                                 // T(("Look up ok\n"));
1943                         }
1944                 }
1945                 
1946                 yaffs_CheckObjectHashSanity(dev);
1947         
1948                 for(i = 0; i < 1000; i+=3)
1949                 {
1950                         yaffs_FreeObject(in[i]);        
1951                         in[i] = NULL;
1952                 }
1953                 
1954         
1955                 yaffs_CheckObjectHashSanity(dev);
1956         }
1957                 
1958 }
1959
1960 #endif
1961
1962 /////////////////////////// Block Management and Page Allocation ///////////////////
1963
1964
1965 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1966 {
1967         dev->allocationBlock = -1; // force it to get a new one
1968         //Todo we're assuming the malloc will pass.
1969         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1970         // Set up dynamic blockinfo stuff.
1971         dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
1972         dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1973         if(dev->blockInfo && dev->chunkBits)
1974         {
1975                 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1976                 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
1977                 return YAFFS_OK;
1978         }
1979         
1980         return YAFFS_FAIL;
1981         
1982 }
1983
1984 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1985 {
1986         YFREE(dev->blockInfo);
1987         dev->blockInfo = NULL;
1988         YFREE(dev->chunkBits);
1989         dev->chunkBits = NULL;
1990 }
1991
1992 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1993 // for garbage collection.
1994
1995 static int yaffs_FindDirtiestBlock(yaffs_Device *dev,int aggressive)
1996 {
1997
1998         int b = dev->currentDirtyChecker;
1999         
2000         int i;
2001         int iterations;
2002         int dirtiest = -1;
2003         int pagesInUse; 
2004         yaffs_BlockInfo *bi;
2005
2006         // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2007         // search further.
2008         
2009         pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2010         if(aggressive)
2011         {
2012                 iterations = dev->endBlock - dev->startBlock + 1;
2013         }
2014         else
2015         {
2016                 iterations = dev->endBlock - dev->startBlock + 1;
2017                 iterations = iterations / 16;
2018                 if(iterations > 200)
2019                 {
2020                         iterations = 200;
2021                 }
2022         }
2023         
2024         for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2025         {
2026                 b++;
2027                 if ( b < dev->startBlock || b > dev->endBlock)
2028                 {
2029                         b =  dev->startBlock;
2030                 }
2031
2032                 if(b < dev->startBlock || b > dev->endBlock)
2033                 {
2034                         T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2035                         YBUG();
2036                 }
2037                 
2038                 bi = yaffs_GetBlockInfo(dev,b);
2039                 
2040                 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2041                    (bi->pagesInUse - bi->softDeletions )< pagesInUse)
2042                 {
2043                         dirtiest = b;
2044                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2045                 }
2046         }
2047         
2048         dev->currentDirtyChecker = b;
2049         
2050         return dirtiest;
2051 }
2052
2053
2054 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2055 {
2056         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2057         
2058         int erasedOk = 0;
2059         
2060         // If the block is still healthy erase it and mark as clean.
2061         // If the block has had a data failure, then retire it.
2062         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2063
2064         if(!bi->needsRetiring)
2065         {
2066                 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2067                 if(!erasedOk)
2068                 {
2069                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2070                 }
2071         }
2072         
2073         if( erasedOk )
2074         {
2075                 // Clean it up...
2076                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2077                 dev->nErasedBlocks++;
2078                 bi->pagesInUse = 0;
2079                 bi->softDeletions = 0;
2080                 yaffs_ClearChunkBits(dev,blockNo);
2081         
2082                 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2083         }
2084         else
2085         {
2086                 yaffs_RetireBlock(dev,blockNo);
2087                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2088         }
2089 }
2090
2091
2092 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2093 {
2094         int i;
2095         
2096         yaffs_BlockInfo *bi;
2097         
2098         if(dev->nErasedBlocks < 1)
2099         {
2100                 // Hoosterman we've got a problem.
2101                 // Can't get space to gc
2102                 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during gc" TENDSTR)));
2103
2104                 return -1;
2105         }
2106         
2107         // Find an empty block.
2108         
2109         for(i = dev->startBlock; i <= dev->endBlock; i++)
2110         {
2111                 dev->allocationBlockFinder++;
2112                 if(dev->allocationBlockFinder <dev->startBlock || dev->allocationBlockFinder> dev->endBlock) 
2113                 {
2114                         dev->allocationBlockFinder = dev->startBlock;
2115                 }
2116                 
2117                 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2118
2119                 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2120                 {
2121                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2122                         dev->nErasedBlocks--;                   
2123                         return dev->allocationBlockFinder;
2124                 }
2125         }
2126         
2127         return -1;      
2128 }
2129
2130
2131
2132 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2133 {
2134         int retVal;
2135         yaffs_BlockInfo *bi;
2136         
2137         if(dev->allocationBlock < 0)
2138         {
2139                 // Get next block to allocate off
2140                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2141                 dev->allocationPage = 0;
2142         }
2143         
2144         if(!useReserve &&  dev->nErasedBlocks <= dev->nReservedBlocks)
2145         {
2146                 // Not enough space to allocate unless we're allowed to use the reserve.
2147                 return -1;
2148         }
2149         
2150         // Next page please....
2151         if(dev->allocationBlock >= 0)
2152         {
2153                 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2154                 
2155                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) + 
2156                                   dev->allocationPage;
2157                 bi->pagesInUse++;
2158                 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2159
2160                 dev->allocationPage++;
2161                 
2162                 dev->nFreeChunks--;
2163                 
2164                 // If the block is full set the state to full
2165                 if(dev->allocationPage >= dev->nChunksPerBlock)
2166                 {
2167                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2168                         dev->allocationBlock = -1;
2169                 }
2170
2171
2172                 return retVal;
2173                 
2174         }
2175         T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2176
2177         return -1;      
2178 }
2179
2180 // To determine if we have enough space we just look at the 
2181 // number of erased blocks.
2182 // The cache is allowed to use reserved blocks.
2183
2184 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2185 {
2186         return (dev->nErasedBlocks >= dev->nReservedBlocks);
2187 }
2188
2189
2190 static int  yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2191 {
2192         int oldChunk;
2193         int newChunk;
2194         int chunkInBlock;
2195         int markNAND;
2196         
2197         
2198         yaffs_Spare spare;
2199         yaffs_Tags  tags;
2200         __u8  buffer[YAFFS_BYTES_PER_CHUNK];
2201         
2202 //      yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2203         
2204         yaffs_Object *object;
2205
2206         //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));        
2207         
2208         for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock; 
2209             chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2210             chunkInBlock++, oldChunk++ )
2211         {
2212                 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2213                 {
2214                         
2215                         // This page is in use and might need to be copied off
2216                         
2217                         markNAND = 1;
2218                         
2219                         //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2220                         
2221                         yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
2222                         
2223                         yaffs_GetTagsFromSpare(dev,&spare,&tags);
2224
2225                         object = yaffs_FindObjectByNumber(dev,tags.objectId);
2226                         
2227                         if(object && object->deleted && tags.chunkId != 0)
2228                         {
2229                                 // Data chunk in a deleted file, throw it away
2230                                 // It's a deleted data chunk,
2231                                 // No need to copy this, just forget about it and fix up the
2232                                 // object.
2233                                 
2234                                 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0); 
2235                                 object->nDataChunks--;
2236                                 
2237                                 if(object->nDataChunks <= 0)
2238                                 {
2239                                         // Time to delete the file too
2240                                         yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2241                                         object->variant.fileVariant.top = NULL;
2242                                         T(YAFFS_TRACE_TRACING,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2243                                         yaffs_DoGenericObjectDeletion(object);                                  
2244                                 }
2245                                 markNAND = 0;
2246                         }
2247                         else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2248                         {
2249                                 // Deleted object header with no data chunks.
2250                                 // Can be discarded and the file deleted.
2251                                 object->chunkId = 0;
2252                                 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2253                                 object->variant.fileVariant.top = NULL;
2254                                 yaffs_DoGenericObjectDeletion(object);
2255                                 
2256                         }
2257                         else if(object)
2258                         {
2259                                 // It's either a data chunk in a live file or
2260                                 // an ObjectHeader, so we're interested in it.
2261                                 // NB Need to keep the ObjectHeaders of deleted files
2262                                 // until the whole file has been deleted off
2263                                 tags.serialNumber++;
2264                                 yaffs_LoadTagsIntoSpare(&spare,&tags);
2265
2266                                 dev->nGCCopies++;
2267
2268                                 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
2269                         
2270                                 if(newChunk < 0)
2271                                 {
2272                                         return YAFFS_FAIL;
2273                                 }
2274                         
2275                                 // Ok, now fix up the Tnodes etc.
2276                         
2277                                 if(tags.chunkId == 0)
2278                                 {
2279                                         // It's a header
2280                                         object->chunkId = newChunk;
2281                                 }
2282                                 else
2283                                 {
2284                                         // It's a data chunk
2285                                         yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2286                                 }
2287                         }
2288                         
2289                         yaffs_DeleteChunk(dev,oldChunk,markNAND);                       
2290                         
2291                 }
2292         }
2293
2294         return YAFFS_OK;
2295 }
2296
2297
2298 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2299 {
2300         // find a file to delete
2301         struct list_head *i;    
2302         yaffs_Object *l;
2303
2304
2305         //Scan the unlinked files looking for one to delete
2306         list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2307         {
2308                 if(i)
2309                 {
2310                         l = list_entry(i, yaffs_Object,siblings);
2311                         if(l->deleted)
2312                         {
2313                                 return l;                       
2314                         }
2315                 }
2316         }       
2317         return NULL;
2318 }
2319
2320
2321 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2322 {
2323         // This does background deletion on unlinked files.. only deleted ones.
2324         // If we don't have a file we're working on then find one
2325         if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2326         {
2327                 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2328         }
2329         
2330         // OK, we're working on a file...
2331         if(dev->unlinkedDeletion)
2332         {
2333                 yaffs_Object *obj = dev->unlinkedDeletion;
2334                 int delresult;
2335                 int limit; // Number of chunks to delete in a file.
2336                                    // NB this can be exceeded, but not by much.
2337                                    
2338                 limit = -1;
2339
2340                 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2341                 
2342                 if(obj->nDataChunks == 0)
2343                 {
2344                         // Done all the deleting of data chunks.
2345                         // Now dump the header and clean up
2346                         yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2347                         obj->variant.fileVariant.top = NULL;
2348                         yaffs_DoGenericObjectDeletion(obj);
2349                         dev->nDeletedFiles--;
2350                         dev->nUnlinkedFiles--;
2351                         dev->nBackgroundDeletions++;
2352                         dev->unlinkedDeletion = NULL;   
2353                 }
2354         }
2355 }
2356
2357
2358 #if 0
2359 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
2360 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2361 {
2362         int block;
2363         int aggressive=0;
2364         
2365         //yaffs_DoUnlinkedFileDeletion(dev);
2366         
2367         if(dev->nErasedBlocks <= (dev->nReservedBlocks + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2368         {
2369                 aggressive = 1;
2370         }               
2371         
2372         if(aggressive)
2373         {
2374                 block = yaffs_FindDirtiestBlock(dev,aggressive);
2375                 
2376                 if(block >= 0)
2377                 {
2378                         dev->garbageCollections++;
2379                         return yaffs_GarbageCollectBlock(dev,block);
2380                 }       
2381                 else
2382                 {
2383                         return YAFFS_FAIL;
2384                 }
2385         }
2386
2387         return YAFFS_OK;
2388 }
2389 #endif
2390
2391 // New garbage collector
2392 // If we're very low on erased blocks then we do aggressive garbage collection
2393 // otherwise we do "passive" garbage collection.
2394 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2395 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2396 //
2397 // The idea is to help clear out space in a more spread-out manner.
2398 // Dunno if it really does anything useful.
2399 //
2400 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2401 {
2402         int block;
2403         int aggressive=0;
2404         
2405         //yaffs_DoUnlinkedFileDeletion(dev);
2406         
2407         if(dev->nErasedBlocks <= (dev->nReservedBlocks + 1))
2408         {
2409                 aggressive = 1;
2410         }               
2411         
2412         block = yaffs_FindDirtiestBlock(dev,aggressive);
2413         
2414         if(block >= 0)
2415         {
2416                 dev->garbageCollections++;
2417                 if(!aggressive)
2418                 {
2419                         dev->passiveGarbageCollections++;
2420                 }
2421
2422                 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2423
2424                 return yaffs_GarbageCollectBlock(dev,block);
2425         }       
2426
2427         return aggressive ? YAFFS_FAIL : YAFFS_OK;
2428 }
2429
2430
2431 //////////////////////////// TAGS ///////////////////////////////////////
2432
2433 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2434 {
2435         yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2436         
2437         yaffs_CalcTagsECC(tagsPtr);
2438         
2439         sparePtr->tagByte0 = tu->asBytes[0];
2440         sparePtr->tagByte1 = tu->asBytes[1];
2441         sparePtr->tagByte2 = tu->asBytes[2];
2442         sparePtr->tagByte3 = tu->asBytes[3];
2443         sparePtr->tagByte4 = tu->asBytes[4];
2444         sparePtr->tagByte5 = tu->asBytes[5];
2445         sparePtr->tagByte6 = tu->asBytes[6];
2446         sparePtr->tagByte7 = tu->asBytes[7];
2447 }
2448
2449 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2450 {
2451         yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2452         int result;
2453
2454         tu->asBytes[0]= sparePtr->tagByte0;
2455         tu->asBytes[1]= sparePtr->tagByte1;
2456         tu->asBytes[2]= sparePtr->tagByte2;
2457         tu->asBytes[3]= sparePtr->tagByte3;
2458         tu->asBytes[4]= sparePtr->tagByte4;
2459         tu->asBytes[5]= sparePtr->tagByte5;
2460         tu->asBytes[6]= sparePtr->tagByte6;
2461         tu->asBytes[7]= sparePtr->tagByte7;
2462         
2463         result =  yaffs_CheckECCOnTags(tagsPtr);
2464         if(result> 0)
2465         {
2466                 dev->tagsEccFixed++;
2467         }
2468         else if(result <0)
2469         {
2470                 dev->tagsEccUnfixed++;
2471         }
2472 }
2473
2474 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2475 {
2476         memset(spare,0xFF,sizeof(yaffs_Spare));
2477 }
2478
2479 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2480 {
2481         if(tags)
2482         {
2483                 yaffs_Spare spare;
2484                 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2485                 {
2486                         *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2487                         yaffs_GetTagsFromSpare(dev,&spare,tags);
2488                         return YAFFS_OK;
2489                 }
2490                 else
2491                 {
2492                         return YAFFS_FAIL;
2493                 }
2494         }
2495         
2496         return YAFFS_OK;
2497 }
2498
2499 #if 0
2500 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2501 {
2502         // NB There must be tags, data is optional
2503         // If there is data, then an ECC is calculated on it.
2504         
2505         yaffs_Spare spare;
2506         
2507         if(!tags)
2508         {
2509                 return YAFFS_FAIL;
2510         }
2511         
2512         yaffs_SpareInitialise(&spare);
2513         
2514         if(!dev->useNANDECC && buffer)
2515         {
2516                 yaffs_CalcECC(buffer,&spare);
2517         }
2518         
2519         yaffs_LoadTagsIntoSpare(&spare,tags);
2520         
2521         return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2522         
2523 }
2524 #endif
2525
2526
2527 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2528 {
2529         // NB There must be tags, data is optional
2530         // If there is data, then an ECC is calculated on it.
2531         
2532         yaffs_Spare spare;
2533         
2534         if(!tags)
2535         {
2536                 return YAFFS_FAIL;
2537         }
2538         
2539         yaffs_SpareInitialise(&spare);
2540         
2541         if(!dev->useNANDECC && buffer)
2542         {
2543                 yaffs_CalcECC(buffer,&spare);
2544         }
2545         
2546         yaffs_LoadTagsIntoSpare(&spare,tags);
2547         
2548         return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2549         
2550 }
2551
2552 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2553 {
2554         return  (  tags->chunkId == chunkInObject &&
2555                            tags->objectId == objectId &&
2556                            !chunkDeleted) ? 1 : 0;
2557         
2558 }
2559
2560
2561
2562 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2563 {
2564         //Get the Tnode, then get the level 0 offset chunk offset
2565     yaffs_Tnode *tn;     
2566     int theChunk = -1;
2567     yaffs_Tags localTags;
2568     int i;
2569     int found = 0;
2570     int chunkDeleted;
2571     
2572     yaffs_Device *dev = in->myDev;
2573     
2574     
2575     if(!tags)
2576     {
2577         // Passed a NULL, so use our own tags space
2578         tags = &localTags;
2579     }
2580     
2581     tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2582     
2583     if(tn)
2584     {
2585                 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2586
2587                 // Now we need to do the shifting etc and search for it
2588                 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2589                 {
2590                         yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2591                         if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2592                         {
2593                                 // found it;
2594                                 found = 1;
2595                         }
2596                         else
2597                         {
2598                                 theChunk++;
2599                         }
2600                 }
2601     }
2602     return found ? theChunk : -1;
2603 }
2604
2605 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2606 {
2607         //Get the Tnode, then get the level 0 offset chunk offset
2608     yaffs_Tnode *tn;     
2609     int theChunk = -1;
2610     yaffs_Tags localTags;
2611     int i;
2612     int found = 0;
2613     yaffs_Device *dev = in->myDev;
2614     int chunkDeleted;
2615     
2616     if(!tags)
2617     {
2618         // Passed a NULL, so use our own tags space
2619         tags = &localTags;
2620     }
2621     
2622     tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2623     
2624     if(tn)
2625     {
2626     
2627                 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2628     
2629                 // Now we need to do the shifting etc and search for it
2630                 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2631                 {
2632                         yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2633                         if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2634                         {
2635                                 // found it;
2636                                 found = 1;
2637                         }
2638                         else
2639                         {
2640                                 theChunk++;
2641                         }
2642                 }
2643     
2644                 // Delete the entry in the filestructure
2645                 if(found)
2646                 {
2647                         tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2648                 }
2649     }
2650     else
2651     {
2652         //T(("No level 0 found for %d\n", chunkInInode));
2653     }
2654     
2655     if(!found)
2656     {
2657         //T(("Could not find %d to delete\n",chunkInInode));
2658     }
2659     return found ? theChunk : -1;
2660 }
2661
2662
2663 #ifdef YAFFS_PARANOID
2664
2665 static int yaffs_CheckFileSanity(yaffs_Object *in)
2666 {
2667         int chunk;
2668         int nChunks;
2669         int fSize;
2670         int failed = 0;
2671         int objId;
2672         yaffs_Tnode *tn;
2673     yaffs_Tags localTags;
2674     yaffs_Tags *tags = &localTags;
2675     int theChunk;
2676     int chunkDeleted;
2677     
2678         
2679         if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2680         {
2681                 //T(("Object not a file\n"));
2682                 return YAFFS_FAIL;
2683         }
2684         
2685         objId = in->objectId;
2686         fSize  = in->variant.fileVariant.fileSize;
2687         nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
2688         
2689         for(chunk = 1; chunk <= nChunks; chunk++)
2690         {
2691                 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2692     
2693                 if(tn)
2694                 {
2695     
2696                         theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2697     
2698
2699                                 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2700                                 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2701                                 {
2702                                         // found it;
2703                                 
2704                                 }
2705                                 else
2706                                 {
2707                                         //T(("File problem file [%d,%d] NAND %d  tags[%d,%d]\n",
2708                                         //              objId,chunk,theChunk,tags->chunkId,tags->objectId);
2709                                                         
2710                                         failed = 1;
2711                                                                 
2712                                 }
2713     
2714                 }
2715                 else
2716                 {
2717                         //T(("No level 0 found for %d\n", chunk));
2718                 }
2719         }
2720         
2721         return failed ? YAFFS_FAIL : YAFFS_OK;
2722 }
2723
2724 #endif
2725
2726 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2727 {
2728         yaffs_Tnode *tn;
2729         yaffs_Device *dev = in->myDev;
2730         int existingChunk;
2731         yaffs_Tags existingTags;
2732         yaffs_Tags newTags;
2733         unsigned existingSerial, newSerial;
2734         
2735         int newChunkDeleted;
2736         
2737         
2738         tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2739         if(!tn)
2740         {
2741                 return YAFFS_FAIL;
2742         }
2743
2744         existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];            
2745         
2746         if(inScan)
2747         {
2748                 // If we're scanning then we need to test for duplicates
2749                 // NB This does not need to be efficient since it should only ever 
2750                 // happen when the power fails during a write, then only one
2751                 // chunk should ever be affected.
2752         
2753                 
2754                 if(existingChunk != 0)
2755                 {
2756                         // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2757                         //    thus we have to do a FindChunkInFile to get the real chunk id.
2758                         //
2759                         // We have a duplicate now we need to decide which one to use
2760                         // To do this we get both sets of tags and compare serial numbers.
2761                         yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2762                         
2763                         
2764                         // Do a proper find
2765                         existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2766
2767                         if(existingChunk <=0)
2768                         {
2769                                 //Hoosterman - how did this happen?
2770                                 
2771                                 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
2772
2773                         }
2774
2775                         
2776                         // NB The deleted flags should be false, otherwise the chunks will 
2777                         // not be loaded during a scan
2778                         
2779                         newSerial = newTags.serialNumber;
2780                         existingSerial = existingTags.serialNumber;
2781                         
2782                         if( existingChunk <= 0 ||
2783                             ((existingSerial+1) & 3) == newSerial)
2784                         {
2785                                 // Use new
2786                                 // Delete the old one and drop through to update the tnode
2787                                 yaffs_DeleteChunk(dev,existingChunk,1);
2788                         }
2789                         else
2790                         {
2791                                 // Use existing.
2792                                 // Delete the new one and return early so that the tnode isn't changed
2793                                 yaffs_DeleteChunk(dev,chunkInNAND,1);
2794                                 return YAFFS_OK;
2795                         }
2796                 }
2797
2798         }
2799                 
2800         if(existingChunk == 0)
2801         {
2802                 in->nDataChunks++;
2803         }
2804         
2805         tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2806         
2807         return YAFFS_OK;
2808 }
2809
2810
2811
2812 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2813 {
2814     int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2815     
2816     if(chunkInNAND >= 0)
2817     {
2818                 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2819         }
2820         else
2821         {
2822                 return 0;
2823         }
2824
2825 }
2826
2827
2828 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND)
2829 {
2830         int block;
2831         int page;
2832         yaffs_Spare spare;
2833         yaffs_BlockInfo *bi;
2834         
2835         if(chunkId <= 0) return;        
2836         
2837         dev->nDeletions++;
2838         block = chunkId / dev->nChunksPerBlock;
2839         page = chunkId % dev->nChunksPerBlock;
2840         
2841         if(markNAND)
2842         {
2843                 yaffs_SpareInitialise(&spare);
2844         
2845                 spare.pageStatus = 0; // To mark it as deleted.
2846
2847         
2848                 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2849                 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2850         }
2851         else
2852         {
2853                         dev->nUnmarkedDeletions++;
2854         }       
2855         
2856         bi = yaffs_GetBlockInfo(dev,block);
2857                         
2858         
2859         // Pull out of the management area.
2860         // If the whole block became dirty, this will kick off an erasure.
2861         if(     bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2862             bi->blockState == YAFFS_BLOCK_STATE_FULL)
2863         {
2864                 dev->nFreeChunks++;
2865
2866                 yaffs_ClearChunkBit(dev,block,page);
2867                 bi->pagesInUse--;
2868                 
2869                 if(bi->pagesInUse == 0 &&
2870                bi->blockState == YAFFS_BLOCK_STATE_FULL)
2871             {
2872                 yaffs_BlockBecameDirty(dev,block);
2873             }
2874
2875         }
2876         else
2877         {
2878                 // T(("Bad news deleting chunk %d\n",chunkId));
2879         }
2880         
2881 }
2882
2883
2884
2885
2886 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2887 {
2888         // Find old chunk Need to do this to get serial number
2889         // Write new one and patch into tree.
2890         // Invalidate old tags.
2891
2892     int prevChunkId;
2893     yaffs_Tags prevTags;
2894     
2895     int newChunkId;
2896     yaffs_Tags newTags;
2897
2898     yaffs_Device *dev = in->myDev;    
2899
2900         yaffs_CheckGarbageCollection(dev);
2901
2902         // Get the previous chunk at this location in the file if it exists
2903     prevChunkId  = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2904     
2905     // Set up new tags
2906         newTags.chunkId = chunkInInode;
2907         newTags.objectId = in->objectId;
2908         newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2909         newTags.byteCount = nBytes;
2910         newTags.unusedStuff = 0xFFFFFFFF;
2911                 
2912         yaffs_CalcTagsECC(&newTags);
2913
2914         newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2915         if(newChunkId >= 0)
2916         {
2917                 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2918                 
2919                 
2920                 if(prevChunkId >= 0)
2921                 {
2922                         yaffs_DeleteChunk(dev,prevChunkId,1);
2923         
2924                 }
2925                 
2926                 yaffs_CheckFileSanity(in);
2927         }
2928         return newChunkId;
2929
2930
2931
2932
2933
2934 }
2935
2936
2937 // UpdateObjectHeader updates the header on NAND for an object.
2938 // If name is not NULL, then that new name is used.
2939 //
2940 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2941 {
2942
2943         yaffs_Device *dev = in->myDev;
2944         
2945     int prevChunkId;
2946     
2947     int newChunkId;
2948     yaffs_Tags newTags;
2949     __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2950     __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2951     
2952     yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2953     yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2954
2955     
2956     if(!in->fake || force)
2957     {
2958   
2959                 yaffs_CheckGarbageCollection(dev);              
2960     
2961                 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2962     
2963                 prevChunkId = in->chunkId;
2964     
2965                 if(prevChunkId >= 0)
2966                 {
2967                         yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);      
2968                 }
2969
2970                 // Header data
2971                 oh->type = in->variantType;
2972                 
2973                 oh->st_mode = in->st_mode;
2974
2975 #ifdef CONFIG_YAFFS_WINCE
2976                 oh->win_atime[0] = in->win_atime[0];
2977                 oh->win_ctime[0] = in->win_ctime[0];
2978                 oh->win_mtime[0] = in->win_mtime[0];
2979                 oh->win_atime[1] = in->win_atime[1];
2980                 oh->win_ctime[1] = in->win_ctime[1];
2981                 oh->win_mtime[1] = in->win_mtime[1];
2982 #else
2983                 oh->st_uid = in->st_uid;
2984                 oh->st_gid = in->st_gid;
2985                 oh->st_atime = in->st_atime;
2986                 oh->st_mtime = in->st_mtime;
2987                 oh->st_ctime = in->st_ctime;
2988                 oh->st_rdev = in->st_rdev;
2989 #endif  
2990                 if(in->parent)
2991                 {
2992                         oh->parentObjectId = in->parent->objectId;
2993                 }
2994                 else
2995                 {
2996                         oh->parentObjectId = 0;
2997                 }
2998                 
2999                 //oh->sum = in->sum;
3000                 if(name && *name)
3001                 {
3002                         memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3003                         strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3004                 }
3005                 else if(prevChunkId)
3006                 {       
3007                         memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
3008                 }
3009                 else
3010                 {
3011                         memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);   
3012                 }
3013         
3014                 switch(in->variantType)
3015                 {
3016                         case YAFFS_OBJECT_TYPE_UNKNOWN:         
3017                                 // Should not happen
3018                                 break;
3019                         case YAFFS_OBJECT_TYPE_FILE:
3020                                 oh->fileSize = in->variant.fileVariant.fileSize;
3021                                 break;
3022                         case YAFFS_OBJECT_TYPE_HARDLINK:
3023                                 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3024                                 break;
3025                         case YAFFS_OBJECT_TYPE_SPECIAL: 
3026                                 // Do nothing
3027                                 break;
3028                         case YAFFS_OBJECT_TYPE_DIRECTORY:       
3029                                 // Do nothing
3030                                 break;
3031                         case YAFFS_OBJECT_TYPE_SYMLINK:
3032                                 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3033                                 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3034                                 break;
3035                 }
3036
3037                 // Tags
3038                 in->serial++;
3039                 newTags.chunkId = 0;
3040                 newTags.objectId = in->objectId;
3041                 newTags.serialNumber = in->serial;
3042                 newTags.byteCount =   0xFFFFFFFF;
3043                 newTags.unusedStuff = 0xFFFFFFFF;
3044         
3045                 yaffs_CalcTagsECC(&newTags);
3046         
3047
3048                 // Create new chunk in NAND
3049                 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3050     
3051                 if(newChunkId >= 0)
3052                 {
3053                 
3054                         in->chunkId = newChunkId;               
3055                 
3056                         if(prevChunkId >= 0)
3057                         {
3058                                 yaffs_DeleteChunk(dev,prevChunkId,1);
3059                         }
3060                 
3061                         in->dirty = 0;
3062                 }
3063                 
3064                 return newChunkId;
3065
3066     }
3067     return 0;
3068 }
3069
3070
3071 /////////////////////// Short Operations Cache ////////////////////////////////
3072 //      In many siturations where there is no high level buffering (eg WinCE) a lot of
3073 //      reads might be short sequential reads, and a lot of writes may be short 
3074 //  sequential writes. eg. scanning/writing a jpeg file.
3075 //      In these cases, a short read/write cache can provide a huge perfomance benefit 
3076 //  with dumb-as-a-rock code.
3077 //  There are a limited number (~10) of cache chunks per device so that we don't
3078 //  need a very intelligent search.
3079
3080
3081
3082
3083
3084 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3085 {
3086         yaffs_Device *dev = obj->myDev;
3087         int lowest;
3088         int i;
3089         yaffs_ChunkCache *cache;
3090         int chunkWritten;
3091         int nBytes;
3092         int nCaches = obj->myDev->nShortOpCaches;
3093         
3094         if  (nCaches > 0)
3095         {
3096                 do{
3097                         cache = NULL;
3098                 
3099                         // Find the dirty cache for this object with the lowest chunk id.
3100                         for(i = 0; i < nCaches; i++)
3101                         {
3102                                 if(dev->srCache[i].object == obj &&
3103                                 dev->srCache[i].dirty)
3104                                 {
3105                                         if(!cache ||  dev->srCache[i].chunkId < lowest)
3106                                         {
3107                                                 cache = &dev->srCache[i];
3108                                                 lowest = cache->chunkId;
3109                                         }
3110                                 }
3111                         }
3112                 
3113                         if(cache)
3114                         {
3115                                 //Write it out
3116
3117 #if 0
3118                                 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3119                         
3120                                 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3121                                 {
3122                                         nBytes= YAFFS_BYTES_PER_CHUNK;
3123                                 }
3124 #endif                  
3125                                 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3126                                                                                                                         cache->chunkId,
3127                                                                                                                         cache->data,
3128                                                                                                                         cache->nBytes,1);
3129
3130                                 cache->dirty = 0;
3131                                 cache->object = NULL;
3132                         }
3133                 
3134                 } while(cache && chunkWritten > 0);
3135         
3136                 if(cache)
3137                 {
3138                         //Hoosterman, disk full while writing cache out.
3139                         T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3140
3141                 }
3142         }       
3143                 
3144 }
3145
3146
3147 // Grab us a chunk for use.
3148 // First look for an empty one. 
3149 // Then look for the least recently used non-dirty one.
3150 // Then look for the least recently used dirty one...., flush and look again.
3151 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3152 {
3153         int i;
3154         int usage;
3155         int theOne;
3156         
3157         if(dev->nShortOpCaches > 0)
3158         {
3159                 for(i = 0; i < dev->nShortOpCaches; i++)
3160                 {
3161                         if(!dev->srCache[i].object)
3162                         {
3163                                 //T(("Grabbing empty %d\n",i));
3164                                 
3165                                 //printf("Grabbing empty %d\n",i);
3166                         
3167                                 return &dev->srCache[i];
3168                         }
3169                 }
3170                 
3171                 return NULL;
3172         
3173                 theOne = -1; 
3174                 usage = 0; // just to stop the compiler grizzling
3175         
3176                 for(i = 0; i < dev->nShortOpCaches; i++)
3177                 {
3178                         if(!dev->srCache[i].dirty &&
3179                         ((dev->srCache[i].lastUse < usage  && theOne >= 0)|| 
3180                                 theOne < 0))
3181                         {
3182                                 usage = dev->srCache[i].lastUse;
3183                                 theOne = i;
3184                         }
3185                 }
3186         
3187                 //T(("Grabbing non-empty %d\n",theOne));
3188                 
3189                 //if(theOne >= 0) printf("Grabbed non-empty cache %d\n",theOne);
3190                 
3191                 return  theOne >= 0 ?  &dev->srCache[theOne] : NULL;
3192         }
3193         else
3194         {
3195                 return NULL;
3196         }
3197         
3198 }
3199
3200
3201 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3202 {
3203         yaffs_ChunkCache *cache;
3204         yaffs_Object *theObj;
3205         int usage;
3206         int i;
3207         int pushout;
3208         
3209         if(dev->nShortOpCaches > 0)
3210         {
3211                 // Try find a non-dirty one...
3212         
3213                 cache = yaffs_GrabChunkCacheWorker(dev);
3214         
3215                 if(!cache)
3216                 {
3217                         // They were all dirty, find the last recently used object and flush
3218                         // its cache, then  find again.
3219                         // NB what's here is not very accurate, we actually flush the object
3220                         // the last recently used page.
3221                 
3222                         theObj = dev->srCache[0].object;
3223                         usage = dev->srCache[0].lastUse;
3224                         cache = &dev->srCache[0];
3225                         pushout = 0;
3226         
3227                         for(i = 1; i < dev->nShortOpCaches; i++)
3228                         {
3229                                 if( dev->srCache[i].object && 
3230                                         dev->srCache[i].lastUse < usage)
3231                                 {
3232                                         usage  = dev->srCache[i].lastUse;
3233                                         theObj = dev->srCache[i].object;
3234                                         cache = &dev->srCache[i];
3235                                         pushout = i;
3236                                 }
3237                         }
3238                 
3239                         if(!cache || cache->dirty)
3240                         {
3241                         
3242                                 //printf("Dirty ");
3243                                 yaffs_FlushFilesChunkCache(theObj);
3244                 
3245                                 // Try again
3246                                 cache = yaffs_GrabChunkCacheWorker(dev);
3247                         }
3248                         else
3249                         {
3250                                 //printf(" pushout %d\n",pushout);
3251                         }
3252                         
3253                 }
3254
3255                 return cache;
3256         }
3257         else
3258                 return NULL;
3259
3260 }
3261
3262
3263 // Find a cached chunk
3264 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3265 {
3266         yaffs_Device *dev = obj->myDev;
3267         int i;
3268         if(dev->nShortOpCaches > 0)
3269         {
3270                 for(i = 0; i < dev->nShortOpCaches; i++)
3271                 {
3272                         if(dev->srCache[i].object == obj && 
3273                         dev->srCache[i].chunkId == chunkId)
3274                         {
3275                                 dev->cacheHits++;
3276                         
3277                                 return &dev->srCache[i];
3278                         }
3279                 }
3280         }
3281         return NULL;
3282 }
3283
3284 // Mark the chunk for the least recently used algorithym
3285 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3286 {
3287
3288         if(dev->nShortOpCaches > 0)
3289         {
3290                 if( dev->srLastUse < 0 || 
3291                         dev->srLastUse > 100000000)
3292                 {
3293                         // Reset the cache usages
3294                         int i;
3295                         for(i = 1; i < dev->nShortOpCaches; i++)
3296                         {
3297                                 dev->srCache[i].lastUse = 0;
3298                         }
3299                         dev->srLastUse = 0;
3300                 }
3301
3302                 dev->srLastUse++;
3303         
3304                 cache->lastUse = dev->srLastUse;
3305
3306                 if(isAWrite)
3307                 {
3308                         cache->dirty = 1;
3309                 }
3310         }
3311 }
3312
3313 // Invalidate a single cache page.
3314 // Do this when a whole page gets written,
3315 // ie the short cache for this page is no longer valid.
3316 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3317 {
3318         if(object->myDev->nShortOpCaches > 0)
3319         {
3320                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3321
3322                 if(cache)
3323                 {
3324                         cache->object = NULL;
3325                 }
3326         }
3327 }
3328
3329
3330 // Invalidate all the cache pages associated with this object
3331 // Do this whenever ther file is deleted or resized.
3332 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3333 {
3334         int i;
3335         yaffs_Device *dev = in->myDev;
3336         
3337         if(dev->nShortOpCaches > 0)
3338         { 
3339                 // Now invalidate it.
3340                 for(i = 0; i < dev->nShortOpCaches; i++)
3341                 {
3342                         if(dev->srCache[i].object == in)
3343                         {
3344                                 dev->srCache[i].object = NULL;
3345                         }
3346                 }
3347         }
3348 }
3349
3350
3351
3352
3353
3354 ///////////////////////// File read/write ///////////////////////////////
3355 // Read and write have very similar structures.
3356 // In general the read/write has three parts to it
3357 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3358 // * Some complete chunks
3359 // * An incomplete chunk to end off with
3360 //
3361 // Curve-balls: the first chunk might also be the last chunk.
3362
3363 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3364 {
3365         
3366         
3367         int chunk;
3368         int start;
3369         int nToCopy;
3370         int n = nBytes;
3371         int nDone = 0;
3372         yaffs_ChunkCache *cache;
3373         
3374         yaffs_Device *dev;
3375         
3376         dev = in->myDev;
3377         
3378         while(n > 0)
3379         {
3380                 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
3381                 start = offset % YAFFS_BYTES_PER_CHUNK;
3382
3383                 // OK now check for the curveball where the start and end are in
3384                 // the same chunk.      
3385                 if(     (start + n) < YAFFS_BYTES_PER_CHUNK)
3386                 {
3387                         nToCopy = n;
3388                 }
3389                 else
3390                 {
3391                         nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3392                 }
3393         
3394                 cache = yaffs_FindChunkCache(in,chunk);
3395                 
3396                 // If the chunk is already in the cache or it is less than a whole chunk
3397                 // then use the cache (if there is caching)
3398                 // else bypass the cache.
3399                 if( cache || nToCopy != YAFFS_BYTES_PER_CHUNK)
3400                 {
3401                         if(dev->nShortOpCaches > 0)
3402                         {
3403                                 
3404                                 // If we can't find the data in the cache, then load it up.
3405                                 
3406                                 if(!cache)
3407                                 {
3408                                         cache = yaffs_GrabChunkCache(in->myDev);
3409                                         cache->object = in;
3410                                         cache->chunkId = chunk;
3411                                         cache->dirty = 0;
3412                                         yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3413                                         cache->nBytes = 0;      
3414                                 }
3415                         
3416                                 yaffs_UseChunkCache(dev,cache,0);
3417
3418                                 memcpy(buffer,&cache->data[start],nToCopy);
3419                         }
3420                         else
3421                         {
3422                                 // Read into the local buffer then copy...
3423                                 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);               
3424                                 memcpy(buffer,&dev->localBuffer[start],nToCopy);
3425                         }
3426
3427                 }
3428                 else
3429                 {
3430 #ifdef CONFIG_YAFFS_WINCE
3431                         
3432                         // Under WinCE can't do direct transfer. Need to use a local buffer.
3433                         // This is because we otherwise screw up WinCE's memory mapper
3434                         yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3435                         memcpy(buffer,dev->localBuffer,YAFFS_BYTES_PER_CHUNK);
3436 #else
3437                         // A full chunk. Read directly into the supplied buffer.
3438                         yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3439 #endif
3440                 }
3441                 
3442                 n -= nToCopy;
3443                 offset += nToCopy;
3444                 buffer += nToCopy;
3445                 nDone += nToCopy;
3446                 
3447         }
3448         
3449         return nDone;
3450 }
3451
3452
3453
3454 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3455 {       
3456         
3457         int chunk;
3458         int start;
3459         int nToCopy;
3460         int n = nBytes;
3461         int nDone = 0;
3462         int nToWriteBack;
3463         int startOfWrite = offset;
3464         int chunkWritten = 0;
3465         int nBytesRead;
3466         
3467         yaffs_Device *dev;
3468         
3469         dev = in->myDev;
3470         
3471         
3472         while(n > 0 && chunkWritten >= 0)
3473         {
3474                 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
3475                 start = offset % YAFFS_BYTES_PER_CHUNK;
3476                 
3477
3478                 // OK now check for the curveball where the start and end are in
3479                 // the same chunk.
3480                 
3481                 if(     (start + n) < YAFFS_BYTES_PER_CHUNK)
3482                 {
3483                         nToCopy = n;
3484                         
3485                         // Now folks, to calculate how many bytes to write back....
3486                         // If we're overwriting and not writing to then end of file then
3487                         // we need to write back as much as was there before.
3488                         
3489                         nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
3490                         
3491                         if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
3492                         {
3493                                 nBytesRead = YAFFS_BYTES_PER_CHUNK;
3494                         }
3495                         
3496                         nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3497                         
3498                 }
3499                 else
3500                 {
3501                         nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3502                         nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3503                 }
3504         
3505                 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3506                 {
3507                         // An incomplete start or end chunk (or maybe both start and end chunk)
3508                         if(dev->nShortOpCaches > 0)
3509                         {
3510                                 yaffs_ChunkCache *cache;
3511                                 // If we can't find the data in the cache, then load it up.
3512                                 cache = yaffs_FindChunkCache(in,chunk);
3513                                 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3514                                 {
3515                                         cache = yaffs_GrabChunkCache(in->myDev);
3516                                         cache->object = in;
3517                                         cache->chunkId = chunk;
3518                                         cache->dirty = 0;
3519                                         yaffs_ReadChunkDataFromObject(in,chunk,cache->data);            
3520                                 }
3521                         
3522                                 if(cache)
3523                                 {       
3524                                         yaffs_UseChunkCache(dev,cache,1);
3525                                         memcpy(&cache->data[start],buffer,nToCopy);
3526                                         cache->nBytes = nToWriteBack;
3527                                 }
3528                                 else
3529                                 {
3530                                         chunkWritten = -1; // fail the write
3531                                 }
3532                         }
3533                         else
3534                         {
3535                                 // An incomplete start or end chunk (or maybe both start and end chunk)
3536                                 // Read into the local buffer then copy, then copy over and write back.
3537                 
3538                                 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3539                                 
3540                                 memcpy(&dev->localBuffer[start],buffer,nToCopy);
3541                         
3542                                 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,nToWriteBack,0);
3543                         
3544                                 //T(("Write with readback to chunk %d %d  start %d  copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3545                         }
3546                         
3547                 }
3548                 else
3549                 {
3550                         
3551 #ifdef CONFIG_YAFFS_WINCE
3552                         // Under WinCE can't do direct transfer. Need to use a local buffer.
3553                         // This is because we otherwise screw up WinCE's memory mapper
3554                         memcpy(dev->localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3555                         chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3556 #else
3557                         // A full chunk. Write directly from the supplied buffer.
3558                         chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3559 #endif
3560                         // Since we've overwritten the cached data, we better invalidate it.
3561                         yaffs_InvalidateChunkCache(in,chunk);
3562                         //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3563                 }
3564                 
3565                 if(chunkWritten >= 0)
3566                 {
3567                         n -= nToCopy;
3568                         offset += nToCopy;
3569                         buffer += nToCopy;
3570                         nDone += nToCopy;
3571                 }
3572                 
3573         }
3574         
3575         // Update file object
3576         
3577         if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3578         {
3579                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3580         }
3581         
3582         in->dirty = 1;
3583         
3584         return nDone;
3585 }
3586
3587
3588 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3589 {
3590         int i;
3591         int chunkId;
3592         int oldFileSize = in->variant.fileVariant.fileSize;
3593         int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3594         
3595         yaffs_Device *dev = in->myDev;
3596         
3597
3598         yaffs_FlushFilesChunkCache(in); 
3599         yaffs_InvalidateWholeChunkCache(in);
3600         
3601         if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3602         {
3603                 return yaffs_GetFileSize(in);
3604         }
3605         
3606         if(newSize < oldFileSize)
3607         {
3608                 
3609                 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3610                 
3611                 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3612                                                         YAFFS_BYTES_PER_CHUNK;
3613
3614                 // Delete backwards so that we don't end up with holes if
3615                 // power is lost part-way through the operation.
3616                 for(i = lastDel; i >= startDel; i--)
3617                 {
3618                         // NB this could be optimised somewhat,
3619                         // eg. could retrieve the tags and write them without
3620                         // using yaffs_DeleteChunk
3621
3622                         chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3623                         if(chunkId <= 0 || chunkId >= (dev->endBlock * 32))
3624                         {
3625                                 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3626                         }
3627                         else
3628                         {
3629                                 in->nDataChunks--;
3630                                 yaffs_DeleteChunk(dev,chunkId,1);
3631                         }
3632                 }
3633                 
3634                 
3635                 if(sizeOfPartialChunk != 0)
3636                 {
3637                         int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3638                         
3639                         // Got to read and rewrite the last chunk with its new size.
3640                         yaffs_ReadChunkDataFromObject(in,lastChunk,dev->localBuffer);
3641                         
3642                         yaffs_WriteChunkDataToObject(in,lastChunk,dev->localBuffer,sizeOfPartialChunk,1);
3643                                 
3644                 }
3645                 
3646                 in->variant.fileVariant.fileSize = newSize;
3647                 
3648                 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3649                 
3650                 return newSize;
3651                 
3652         }
3653         else
3654         {
3655                 return oldFileSize;
3656         }
3657 }
3658
3659
3660 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3661 {
3662         obj = yaffs_GetEquivalentObject(obj);
3663         
3664         switch(obj->variantType)
3665         {
3666                 case YAFFS_OBJECT_TYPE_FILE: 
3667                         return obj->variant.fileVariant.fileSize;
3668                 case YAFFS_OBJECT_TYPE_SYMLINK:
3669                         return strlen(obj->variant.symLinkVariant.alias);
3670                 default:
3671                         return 0;
3672         }
3673 }
3674
3675
3676
3677 // yaffs_FlushFile() updates the file's
3678 // objectId in NAND
3679
3680 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
3681 {
3682         int retVal;
3683         if(in->dirty)
3684         {
3685                 //T(("flushing object header\n"));
3686                 
3687                 yaffs_FlushFilesChunkCache(in);
3688                 if(updateTime)
3689                 {
3690 #ifdef CONFIG_YAFFS_WINCE
3691                         yfsd_WinFileTimeNow(in->win_mtime);
3692 #else
3693                         in->st_mtime = CURRENT_TIME;
3694 #endif
3695                 }
3696
3697                 retVal = (yaffs_UpdateObjectHeader(in,NULL,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
3698         }
3699         else
3700         {
3701                 retVal = YAFFS_OK;
3702         }
3703         
3704         return retVal;
3705         
3706 }
3707
3708
3709 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3710 {
3711
3712         // First off, invalidate the file's data in the cache, without flushing.
3713         yaffs_InvalidateWholeChunkCache(in);
3714         
3715         yaffs_RemoveObjectFromDirectory(in);
3716         yaffs_DeleteChunk(in->myDev,in->chunkId,1);
3717 #ifdef __KERNEL__
3718         if(in->myInode)
3719         {
3720                 in->myInode->u.generic_ip = NULL;
3721                 in->myInode = 0;
3722         }
3723 #endif
3724         yaffs_FreeObject(in);
3725         return YAFFS_OK;
3726
3727 }
3728
3729 // yaffs_DeleteFile deletes the whole file data
3730 // and the inode associated with the file.
3731 // It does not delete the links associated with the file.
3732 static int yaffs_UnlinkFile(yaffs_Object *in)
3733 {
3734
3735 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3736
3737         // Delete the file data & tnodes
3738
3739          yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3740          
3741
3742         yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3743         
3744         return  yaffs_DoGenericObjectDeletion(in);
3745 #else
3746         int retVal;
3747         int immediateDeletion=0;
3748         retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3749         if(1 || // Ignore the result of the change name. This will only fail
3750                         // if the disk was completely full (an error condition)
3751                         // We ignore the error so we can delete files to recover the disk
3752            retVal == YAFFS_OK)
3753         {
3754                 //in->unlinked = 1;
3755                 //in->myDev->nUnlinkedFiles++;
3756                 //in->renameAllowed = 0;
3757 #ifdef __KERNEL__
3758                 if(!in->myInode)
3759                 {
3760                         immediateDeletion = 1;
3761
3762                 }
3763 #else
3764                 if(in->inUse <= 0)
3765                 {
3766                         immediateDeletion = 1;
3767
3768                 }
3769 #endif
3770                 
3771                 if(immediateDeletion)
3772                 {
3773                         T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3774                         in->deleted=1;
3775                         in->myDev->nDeletedFiles++;
3776                         yaffs_SoftDeleteFile(in);
3777                 }
3778         
3779         }
3780         return retVal;
3781
3782         
3783 #endif
3784 }
3785
3786 int yaffs_DeleteFile(yaffs_Object *in)
3787 {
3788         int retVal = YAFFS_OK;
3789         
3790         if(in->nDataChunks > 0)
3791         {
3792                 // Use soft deletion
3793                 if(!in->unlinked)
3794                 {
3795                         retVal = yaffs_UnlinkFile(in);
3796                 }
3797                 if(retVal == YAFFS_OK && 
3798                 in->unlinked &&
3799                 !in->deleted)
3800                 {
3801                         in->deleted = 1;
3802                         in->myDev->nDeletedFiles++;
3803                         yaffs_SoftDeleteFile(in);
3804                 }
3805                 return in->deleted ? YAFFS_OK : YAFFS_FAIL;     
3806         }
3807         else
3808         {
3809                 // The file has no data chunks so we toss it immediately
3810                 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3811                 in->variant.fileVariant.top = NULL;
3812                 yaffs_DoGenericObjectDeletion(in);      
3813                 
3814                 return YAFFS_OK;        
3815         }
3816 }
3817
3818 static int yaffs_DeleteDirectory(yaffs_Object *in)
3819 {
3820         //First check that the directory is empty.
3821         if(list_empty(&in->variant.directoryVariant.children))
3822         {
3823                 return  yaffs_DoGenericObjectDeletion(in);
3824         }
3825         
3826         return YAFFS_FAIL;
3827         
3828 }
3829
3830 static int yaffs_DeleteSymLink(yaffs_Object *in)
3831 {
3832         YFREE(in->variant.symLinkVariant.alias);
3833
3834         return  yaffs_DoGenericObjectDeletion(in);
3835 }
3836
3837 static int yaffs_DeleteHardLink(yaffs_Object *in)
3838 {
3839         // remove this hardlink from the list assocaited with the equivalent
3840         // object
3841         list_del(&in->hardLinks);
3842         return  yaffs_DoGenericObjectDeletion(in);      
3843 }
3844
3845
3846 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj)
3847 {
3848         switch(obj->variantType)
3849         {
3850                 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
3851                 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
3852                 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
3853                 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
3854                 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
3855                 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
3856         }
3857 }
3858
3859
3860 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3861 {
3862
3863         
3864         if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3865         {
3866                 return  yaffs_DeleteHardLink(obj);
3867         }
3868         else if(!list_empty(&obj->hardLinks))
3869         {       
3870                 // Curve ball: We're unlinking an object that has a hardlink.
3871                 //
3872                 //      This problem arises because we are not strictly following
3873                 //  The Linux link/inode model.
3874                 //
3875                 // We can't really delete the object.
3876                 // Instead, we do the following:
3877                 // - Select a hardlink.
3878                 // - Unhook it from the hard links
3879                 // - Unhook it from its parent directory (so that the rename can work)
3880                 // - Rename the object to the hardlink's name.
3881                 // - Delete the hardlink
3882                 
3883                 
3884                 yaffs_Object *hl;
3885                 int retVal;
3886                 char name[YAFFS_MAX_NAME_LENGTH+1];
3887                 
3888                 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3889                 
3890                 list_del_init(&hl->hardLinks);
3891                 list_del_init(&hl->siblings);
3892                 
3893                 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3894                 
3895                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3896                 
3897                 if(retVal == YAFFS_OK)
3898                 {
3899                         retVal = yaffs_DoGenericObjectDeletion(hl);
3900                 }
3901                 return retVal;
3902                                 
3903         }
3904         else
3905         {
3906                 switch(obj->variantType)
3907                 {
3908                         case YAFFS_OBJECT_TYPE_FILE:
3909                                 return yaffs_UnlinkFile(obj);
3910                                 break;
3911                         case YAFFS_OBJECT_TYPE_DIRECTORY:
3912                                 return yaffs_DeleteDirectory(obj);
3913                                 break;
3914                         case YAFFS_OBJECT_TYPE_SYMLINK:
3915                                 return yaffs_DeleteSymLink(obj);
3916                                 break;
3917                         case YAFFS_OBJECT_TYPE_HARDLINK:
3918                         case YAFFS_OBJECT_TYPE_UNKNOWN:
3919                         default:
3920                                 return YAFFS_FAIL;
3921                 }
3922         }
3923 }
3924
3925 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3926 {
3927         yaffs_Object *obj;
3928         
3929          obj = yaffs_FindObjectByName(dir,name);
3930          
3931          if(obj && obj->unlinkAllowed)
3932          {
3933                 return yaffs_UnlinkWorker(obj);
3934          }
3935          
3936          return YAFFS_FAIL;
3937         
3938 }
3939
3940 //////////////// Initialisation Scanning /////////////////
3941
3942
3943
3944 // For now we use the SmartMedia check.
3945 // We look at the blockStatus byte in the first two chunks
3946 // These must be 0xFF to pass as OK.
3947 // todo: this function needs to be modifyable foir different NAND types
3948 // and different chunk sizes.  Suggest make this into a per-device configurable
3949 // function.
3950 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3951 {
3952         yaffs_Spare spare;
3953         
3954         yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&spare,1);
3955 #if 1
3956         if(yaffs_CountBits(spare.blockStatus) < 7)
3957         {
3958                 return 1;
3959         }
3960 #else
3961         if(spare.blockStatus != 0xFF)
3962         {
3963                 return 1;
3964         }
3965 #endif
3966         yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
3967
3968 #if 1
3969         if(yaffs_CountBits(spare.blockStatus) < 7)
3970         {
3971                 return 1;
3972         }
3973 #else
3974         if(spare.blockStatus != 0xFF)
3975         {
3976                 return 1;
3977         }
3978 #endif
3979         
3980         return 0;
3981         
3982 }
3983
3984 static int yaffs_Scan(yaffs_Device *dev)
3985 {
3986         yaffs_Spare spare;
3987         yaffs_Tags tags;
3988         int blk;
3989         int chunk;
3990         int c;
3991         int deleted;
3992         yaffs_BlockState state;
3993         yaffs_Object *hardList = NULL;
3994         yaffs_Object *hl;
3995         yaffs_BlockInfo *bi;
3996
3997         
3998         yaffs_ObjectHeader *oh;
3999         yaffs_Object *in;
4000         yaffs_Object *parent;
4001         
4002         __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
4003         
4004         
4005         // Scan all the blocks...
4006         
4007         for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
4008         {
4009                 deleted = 0;
4010                 bi = yaffs_GetBlockInfo(dev,blk);
4011                 yaffs_ClearChunkBits(dev,blk);
4012                 bi->pagesInUse = 0;
4013                 bi->softDeletions = 0;
4014                 state = YAFFS_BLOCK_STATE_SCANNING;
4015                 
4016                 
4017                 if(yaffs_IsBlockBad(dev,blk))
4018                 {
4019                         state = YAFFS_BLOCK_STATE_DEAD;
4020                         T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
4021                 }
4022                 
4023                 // Read each chunk in the block.
4024                 
4025                 for(c = 0; c < dev->nChunksPerBlock && 
4026                                    state == YAFFS_BLOCK_STATE_SCANNING; c++)
4027                 {
4028                         // Read the spare area and decide what to do
4029                         chunk = blk * dev->nChunksPerBlock + c;
4030                         
4031                         yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
4032
4033                         
4034                         // This block looks ok, now what's in this chunk?
4035                         yaffs_GetTagsFromSpare(dev,&spare,&tags);
4036                         
4037                         if(yaffs_CountBits(spare.pageStatus) < 6)
4038                         {
4039                                 // A deleted chunk
4040                                 deleted++;
4041                                 dev->nFreeChunks ++;
4042                                 //T((" %d %d deleted\n",blk,c));
4043                         }
4044                         else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
4045                         {
4046                                 // An unassigned chunk in the block
4047                                 // This means that either the block is empty or 
4048                                 // this is the one being allocated from
4049                                 
4050                                 if(c == 0)
4051                                 {
4052                                         // the block is unused
4053                                         state = YAFFS_BLOCK_STATE_EMPTY;
4054                                         dev->nErasedBlocks++;
4055                                 }
4056                                 else
4057                                 {
4058                                         // this is the block being allocated from
4059                                         T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4060                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
4061                                         dev->allocationBlock = blk;
4062                                         dev->allocationPage = c;
4063                                 }
4064
4065                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4066                         }
4067                         else if(tags.chunkId > 0)
4068                         {
4069                                 int endpos;
4070                                 // A data chunk.
4071                                 yaffs_SetChunkBit(dev,blk,c);
4072                                 bi->pagesInUse++;
4073                                                                 
4074                                 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4075                                 // PutChunkIntoFIle checks for a clash (two data chunks with
4076                                 // the same chunkId).
4077                                 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4078                                 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
4079                                 if(in->variant.fileVariant.scannedFileSize <endpos)
4080                                 {
4081                                         in->variant.fileVariant.scannedFileSize = endpos;
4082 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4083                                                 in->variant.fileVariant.fileSize =      
4084                                                         in->variant.fileVariant.scannedFileSize;
4085 #endif
4086
4087                                 }
4088                                 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));  
4089                         }
4090                         else
4091                         {
4092                                 // chunkId == 0, so it is an ObjectHeader.
4093                                 // Thus, we read in the object header and make the object
4094                                 yaffs_SetChunkBit(dev,blk,c);
4095                                 bi->pagesInUse++;
4096                                                         
4097                                 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
4098                                 
4099                                 oh = (yaffs_ObjectHeader *)chunkData;
4100                                 
4101                                 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4102                                 
4103                                 if(in->valid)
4104                                 {
4105                                         // We have already filled this one. We have a duplicate and need to resolve it.
4106                                         
4107                                         unsigned existingSerial = in->serial;
4108                                         unsigned newSerial = tags.serialNumber;
4109                                         
4110                                         if(((existingSerial+1) & 3) == newSerial)
4111                                         {
4112                                                 // Use new one - destroy the exisiting one
4113                                                 yaffs_DeleteChunk(dev,in->chunkId,1);
4114                                                 in->valid = 0;
4115                                         }
4116                                         else
4117                                         {
4118                                                 // Use existing - destroy this one.
4119                                                 yaffs_DeleteChunk(dev,chunk,1);
4120                                         }
4121                                 }
4122                                 
4123                                 if(!in->valid &&
4124                                    (tags.objectId == YAFFS_OBJECTID_ROOT ||
4125                                     tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4126                                 {
4127                                         // We only load some info, don't fiddle with directory structure
4128                                         in->valid = 1;
4129                                         in->variantType = oh->type;
4130         
4131                                         in->st_mode  = oh->st_mode;
4132 #ifdef CONFIG_YAFFS_WINCE
4133                                         in->win_atime[0] = oh->win_atime[0];
4134                                         in->win_ctime[0] = oh->win_ctime[0];
4135                                         in->win_mtime[0] = oh->win_mtime[0];
4136                                         in->win_atime[1] = oh->win_atime[1];
4137                                         in->win_ctime[1] = oh->win_ctime[1];
4138                                         in->win_mtime[1] = oh->win_mtime[1];
4139 #else
4140                                         in->st_uid   = oh->st_uid;
4141                                         in->st_gid   = oh->st_gid;
4142                                         in->st_atime = oh->st_atime;
4143                                         in->st_mtime = oh->st_mtime;
4144                                         in->st_ctime = oh->st_ctime;
4145                                         in->st_rdev = oh->st_rdev;
4146 #endif
4147                                         in->chunkId  = chunk;
4148
4149                                 }
4150                                 else if(!in->valid)
4151                                 {
4152                                         // we need to load this info
4153                                 
4154                                         in->valid = 1;
4155                                         in->variantType = oh->type;
4156         
4157                                         in->st_mode  = oh->st_mode;
4158 #ifdef CONFIG_YAFFS_WINCE
4159                                         in->win_atime[0] = oh->win_atime[0];
4160                                         in->win_ctime[0] = oh->win_ctime[0];
4161                                         in->win_mtime[0] = oh->win_mtime[0];
4162                                         in->win_atime[1] = oh->win_atime[1];
4163                                         in->win_ctime[1] = oh->win_ctime[1];
4164                                         in->win_mtime[1] = oh->win_mtime[1];
4165 #else
4166                                         in->st_uid   = oh->st_uid;
4167                                         in->st_gid   = oh->st_gid;
4168                                         in->st_atime = oh->st_atime;
4169                                         in->st_mtime = oh->st_mtime;
4170                                         in->st_ctime = oh->st_ctime;
4171                                         in->st_rdev = oh->st_rdev;
4172 #endif
4173                                         in->chunkId  = chunk;
4174
4175                                         yaffs_SetObjectName(in,oh->name);
4176                                         in->dirty = 0;
4177                                                         
4178                                         // directory stuff...
4179                                         // hook up to parent
4180         
4181                                         parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4182                                         if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4183                                         {
4184                                                 // Set up as a directory
4185                                                 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4186                                                 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4187                                         }
4188                                         else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4189                                         {
4190                                                 // Hoosterman, another problem....
4191                                                 // We're trying to use a non-directory as a directory
4192                                                 // Todo ... handle
4193                                                 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan" TENDSTR)));
4194
4195                                         }
4196                                 
4197                                         yaffs_AddObjectToDirectory(parent,in);
4198                                         if(parent == dev->unlinkedDir)
4199                                         {
4200                                                 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4201                                                 dev->nDeletedFiles++;
4202                                         }
4203                                 
4204                                         // Note re hardlinks.
4205                                         // Since we might scan a hardlink before its equivalent object is scanned
4206                                         // we put them all in a list.
4207                                         // After scanning is complete, we should have all the objects, so we run through this
4208                                         // list and fix up all the chains.              
4209         
4210                                         switch(in->variantType)
4211                                         {
4212                                                 case YAFFS_OBJECT_TYPE_UNKNOWN:         // Todo got a problem
4213                                                         break;
4214                                                 case YAFFS_OBJECT_TYPE_FILE:
4215 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4216                                                         in->variant.fileVariant.fileSize = oh->fileSize;
4217 #endif
4218                                                         break;
4219                                                 case YAFFS_OBJECT_TYPE_HARDLINK:
4220                                                         in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4221                                                         in->hardLinks.next = (struct list_head *)hardList;
4222                                                         hardList = in;
4223                                                         break;
4224                                                 case YAFFS_OBJECT_TYPE_DIRECTORY:       // Do nothing
4225                                                         break;
4226                                                 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4227                                                         break;
4228                                                 case YAFFS_OBJECT_TYPE_SYMLINK:         // Do nothing
4229                                                         in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4230                                                         break;
4231                                         }
4232                                         //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));        
4233                                 }
4234                         }
4235                 }
4236                 
4237                 if(state == YAFFS_BLOCK_STATE_SCANNING)
4238                 {
4239                         // If we got this far while scanning, then the block is fully allocated.
4240                         state = YAFFS_BLOCK_STATE_FULL; 
4241                 }
4242                 
4243                 bi->blockState = state;
4244                 
4245                 // Now let's see if it was dirty
4246                 if(     bi->pagesInUse == 0 &&
4247                 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4248             {
4249                 yaffs_BlockBecameDirty(dev,blk);
4250             }
4251
4252         }
4253         
4254         // Fix up the hard link chains.
4255         // We should now have scanned all the objects, now it's time to add these 
4256         // hardlinks.
4257         while(hardList)
4258         {
4259                 hl = hardList;
4260                 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4261                 
4262                 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4263                 
4264                 if(in)
4265                 {
4266                         // Add the hardlink pointers
4267                         hl->variant.hardLinkVariant.equivalentObject=in;
4268                         list_add(&hl->hardLinks,&in->hardLinks);
4269                 }
4270                 else
4271                 {
4272                         //Todo Need to report/handle this better.
4273                         // Got a problem... hardlink to a non-existant object
4274                         hl->variant.hardLinkVariant.equivalentObject=NULL;
4275                         INIT_LIST_HEAD(&hl->hardLinks);
4276                         
4277                 }
4278                 
4279         }
4280         
4281         {
4282                 struct list_head *i;    
4283                 struct list_head *n;
4284                         
4285                 yaffs_Object *l;
4286                 // Soft delete all the unlinked files
4287                 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
4288                 {
4289                         if(i)
4290                         {
4291                                 l = list_entry(i, yaffs_Object,siblings);
4292                                 if(l->deleted)
4293                                 {
4294                                         yaffs_SoftDeleteFile(l);                
4295                                 }
4296                         }
4297                 }       
4298         }
4299         
4300         
4301         return YAFFS_OK;
4302 }
4303
4304
4305 ////////////////////////// Directory Functions /////////////////////////
4306
4307
4308 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
4309 {
4310
4311         if(obj->siblings.prev == NULL)
4312         {
4313                 // Not initialised
4314                 INIT_LIST_HEAD(&obj->siblings);
4315                 
4316         }
4317         else if(!list_empty(&obj->siblings))
4318         {
4319                 // If it is holed up somewhere else, un hook it
4320                 list_del_init(&obj->siblings);
4321         }
4322         // Now add it
4323         list_add(&obj->siblings,&directory->variant.directoryVariant.children);
4324         obj->parent = directory;
4325         
4326         if(directory == obj->myDev->unlinkedDir)
4327         {
4328                 obj->unlinked = 1;
4329                 obj->myDev->nUnlinkedFiles++;
4330                 obj->renameAllowed = 0;
4331         }
4332 }
4333
4334 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4335 {
4336         list_del_init(&obj->siblings);
4337         obj->parent = NULL;
4338 }
4339
4340 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
4341 {
4342         int sum;
4343         
4344         struct list_head *i;
4345         char buffer[YAFFS_MAX_NAME_LENGTH+1];
4346         
4347         yaffs_Object *l;
4348         
4349         sum = yaffs_CalcNameSum(name);
4350         
4351         list_for_each(i,&directory->variant.directoryVariant.children)
4352         {
4353                 if(i)
4354                 {
4355                         l = list_entry(i, yaffs_Object,siblings);
4356                 
4357                         // Special case for lost-n-found
4358                         if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4359                         {
4360                                 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
4361                                 {
4362                                         return l;
4363                                 }
4364                         }
4365                         else if(yaffs_SumCompare(l->sum, sum))
4366                         {
4367                                 // Do a real check
4368                                 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
4369                                 if(yaffs_strcmp(name,buffer) == 0)
4370                                 {
4371                                         return l;
4372                                 }
4373                         
4374                         }                       
4375                 }
4376         }
4377         
4378         return NULL;
4379 }
4380
4381
4382 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
4383 {
4384         struct list_head *i;    
4385         yaffs_Object *l;
4386         
4387         
4388         list_for_each(i,&theDir->variant.directoryVariant.children)
4389         {
4390                 if(i)
4391                 {
4392                         l = list_entry(i, yaffs_Object,siblings);
4393                         if(l && !fn(l))
4394                         {
4395                                 return YAFFS_FAIL;
4396                         }
4397                 }
4398         }
4399         
4400         return YAFFS_OK;
4401
4402 }
4403
4404
4405 // GetEquivalentObject dereferences any hard links to get to the
4406 // actual object.
4407
4408 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4409 {
4410         if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4411         {
4412                 // We want the object id of the equivalent object, not this one
4413                 obj = obj->variant.hardLinkVariant.equivalentObject;
4414         }
4415         return obj;
4416
4417 }
4418
4419 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
4420 {
4421         memset(name,0,buffSize);
4422         
4423         if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4424         {
4425                 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
4426         }
4427         else if(obj->chunkId <= 0)
4428         {
4429                 char locName[20];
4430                 // make up a name
4431                 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
4432                 strncpy(name,locName,buffSize - 1);
4433
4434         }
4435 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4436         else if(obj->shortName[0])
4437         {
4438                 strcpy(name,obj->shortName);
4439         }
4440 #endif
4441         else
4442         {
4443                 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4444                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4445
4446                 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4447         
4448                 if(obj->chunkId >= 0)
4449                 {
4450                         yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
4451                 }
4452                 strncpy(name,oh->name,buffSize - 1);
4453         }
4454         
4455         return strlen(name);
4456 }
4457
4458 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4459 {
4460         
4461         // Dereference any hard linking
4462         obj = yaffs_GetEquivalentObject(obj);
4463         
4464         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4465         {
4466                 return obj->variant.fileVariant.fileSize;
4467         }
4468         if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4469         {
4470                 return strlen(obj->variant.symLinkVariant.alias);
4471         }
4472         else
4473         {
4474                 // Only a directory should drop through to here
4475                 return YAFFS_BYTES_PER_CHUNK;
4476         }       
4477 }
4478
4479 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4480 {
4481         int count = 0; 
4482         struct list_head *i;
4483         
4484         if(!obj->unlinked)
4485         {
4486                 count++;        // the object itself
4487         }
4488         list_for_each(i,&obj->hardLinks)
4489         {
4490                 count++;        // add the hard links;
4491         }
4492         return count;
4493         
4494 }
4495
4496
4497 int yaffs_GetObjectInode(yaffs_Object *obj)
4498 {
4499         obj = yaffs_GetEquivalentObject(obj);
4500         
4501         return obj->objectId;
4502 }
4503
4504 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4505 {
4506         obj = yaffs_GetEquivalentObject(obj);
4507         
4508         switch(obj->variantType)
4509         {
4510                 case YAFFS_OBJECT_TYPE_FILE:            return DT_REG; break;
4511                 case YAFFS_OBJECT_TYPE_DIRECTORY:       return DT_DIR; break;
4512                 case YAFFS_OBJECT_TYPE_SYMLINK:         return DT_LNK; break;
4513                 case YAFFS_OBJECT_TYPE_HARDLINK:        return DT_REG; break;
4514                 case YAFFS_OBJECT_TYPE_SPECIAL:         
4515                         if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
4516                         if(S_ISCHR(obj->st_mode)) return DT_CHR;
4517                         if(S_ISBLK(obj->st_mode)) return DT_BLK;
4518                         if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
4519                 default: return DT_REG; break;
4520         }
4521 }
4522
4523 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4524 {
4525         obj = yaffs_GetEquivalentObject(obj);
4526         if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4527         {
4528                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4529         }
4530         else
4531         {
4532                 return yaffs_CloneString("");
4533         }
4534 }
4535
4536 #ifndef CONFIG_YAFFS_WINCE
4537
4538 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4539 {
4540         unsigned int valid = attr->ia_valid;
4541         
4542         if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4543         if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4544         if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4545         
4546         if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
4547         if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
4548         if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
4549         
4550         if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4551         
4552         yaffs_UpdateObjectHeader(obj,NULL,1);
4553         
4554         return YAFFS_OK;
4555         
4556 }
4557 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4558 {
4559         unsigned int valid = 0;
4560         
4561         attr->ia_mode = obj->st_mode;   valid |= ATTR_MODE;
4562         attr->ia_uid = obj->st_uid;             valid |= ATTR_UID;
4563         attr->ia_gid = obj->st_gid;             valid |= ATTR_GID;
4564         
4565         attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
4566         attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
4567         attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
4568         
4569         attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4570         
4571         attr->ia_valid = valid;
4572         
4573         return YAFFS_OK;
4574         
4575 }
4576
4577 #endif
4578
4579 int yaffs_DumpObject(yaffs_Object *obj)
4580 {
4581 //      __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4582         char name[257];
4583 //      yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4584
4585 //      memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4586         
4587 //      if(obj->chunkId >= 0)
4588 //      {
4589 //              yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4590 //      }
4591         
4592         yaffs_GetObjectName(obj,name,256);
4593         
4594         T(YAFFS_TRACE_ALWAYS,(TSTR("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d type %d size %d\n" TENDSTR),
4595                         obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial, 
4596                         obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4597
4598 #if 0
4599         YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4600                         obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial, 
4601                         obj->sum, obj->chunkId));
4602                 switch(obj->variantType)
4603         {
4604                 case YAFFS_OBJECT_TYPE_FILE: 
4605                         YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4606                         break;
4607                 case YAFFS_OBJECT_TYPE_DIRECTORY:
4608                         YPRINTF((" DIRECTORY\n"));
4609                         break;
4610                 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4611                 case YAFFS_OBJECT_TYPE_SYMLINK:
4612                 case YAFFS_OBJECT_TYPE_UNKNOWN:
4613                 default:
4614         }
4615 #endif
4616         
4617         return YAFFS_OK;
4618 }
4619
4620
4621 ///////////////////////// Initialisation code ///////////////////////////
4622
4623
4624
4625 int yaffs_GutsInitialise(yaffs_Device *dev)
4626 {
4627         unsigned x;
4628         int bits;
4629         int extraBits;
4630         int nBlocks;
4631
4632         if(     dev->nBytesPerChunk != YAFFS_BYTES_PER_CHUNK ||
4633         
4634                 dev->nChunksPerBlock < 2 ||
4635                 dev->nReservedBlocks < 2 ||
4636                 dev->startBlock <= 0 ||
4637                 dev->endBlock <= 0 ||
4638                 dev->endBlock <= (dev->startBlock + dev->nReservedBlocks)
4639           )
4640         {
4641                 //these parameters must be set before stating yaffs
4642                 // Other parameters startBlock,
4643                 return YAFFS_FAIL;
4644         }
4645
4646
4647         
4648         if(!yaffs_CheckStructures())
4649         {
4650                 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
4651                 return YAFFS_FAIL;
4652         }
4653
4654         if(dev->isMounted)
4655         {
4656                 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
4657                 return YAFFS_FAIL;
4658         }
4659
4660         dev->isMounted = 1;
4661         
4662         if(dev->startBlock <= 0 ||
4663            (dev->endBlock - dev->startBlock) < 10)
4664         {
4665                 T(YAFFS_TRACE_ALWAYS,(TSTR("startBlock %d or endBlock %d invalid\n" TENDSTR),
4666                                 dev->startBlock, dev->endBlock));
4667                 return YAFFS_FAIL;
4668         }
4669         
4670         nBlocks = dev->endBlock - dev->startBlock + 1;
4671         
4672
4673                 
4674         // OK now calculate a few things for the device
4675         // Calculate chunkGroupBits. 
4676         // We need to find the next power of 2 > than endBlock
4677         
4678         x = dev->nChunksPerBlock * (dev->endBlock+1);
4679         
4680         for(bits = extraBits = 0; x > 1; bits++)
4681         {
4682                 if(x & 1) extraBits++;
4683                 x >>= 1;
4684         }
4685
4686         if(extraBits > 0) bits++;
4687         
4688         
4689         // Level0 Tnodes are 16 bits, so if the bitwidth of the
4690         // chunk range we're using is greater than 16 we need 
4691         // to figure out chunk shift and chunkGroupSize
4692         if(bits <= 16) 
4693         {
4694                 dev->chunkGroupBits = 0;
4695         }
4696         else
4697         {
4698                 dev->chunkGroupBits = bits - 16;
4699         }
4700         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4701         
4702         
4703         
4704         // More device initialisation
4705         dev->garbageCollections = 0;
4706         dev->passiveGarbageCollections = 0;
4707         dev->currentDirtyChecker = 0;
4708         dev->bufferedBlock = -1;
4709         dev->doingBufferedBlockRewrite = 0;
4710         dev->nDeletedFiles = 0;
4711         dev->nBackgroundDeletions=0;
4712         dev->nUnlinkedFiles = 0;
4713         dev->eccFixed=0;
4714         dev->eccUnfixed=0;
4715         dev->tagsEccFixed=0;
4716         dev->tagsEccUnfixed=0;
4717         
4718         dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
4719         
4720
4721         
4722         
4723         yaffs_InitialiseBlocks(dev,nBlocks);
4724         
4725         yaffs_InitialiseTnodes(dev);
4726
4727         yaffs_InitialiseObjects(dev);
4728         
4729         if(dev->nShortOpCaches > 0)
4730         { 
4731                 int i;
4732                 
4733                 if(dev->nShortOpCaches >  YAFFS_MAX_SHORT_OP_CACHES)
4734                 {
4735                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
4736                 }
4737                 
4738                 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
4739                 
4740                 for(i=0; i < dev->nShortOpCaches; i++)
4741                 {
4742                         dev->srCache[i].object = NULL;
4743                         dev->srCache[i].lastUse = 0;
4744                         dev->srCache[i].dirty = 0;
4745                 }
4746                 dev->srLastUse = 0;
4747         }
4748
4749         dev->cacheHits = 0;
4750         
4751         
4752         // Initialise the unlinked, root and lost and found directories
4753         dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4754         
4755         dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4756
4757         dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4758         dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4759         yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4760         
4761                 
4762         // Now scan the flash.  
4763         yaffs_Scan(dev);
4764         
4765         // Zero out stats
4766         dev->nPageReads = 0;
4767     dev->nPageWrites =  0;
4768         dev->nBlockErasures = 0;
4769         dev->nGCCopies = 0;
4770         dev->nRetriedWrites = 0;
4771         dev->nRetiredBlocks = 0;
4772
4773         
4774         return YAFFS_OK;
4775                 
4776 }
4777
4778 void yaffs_Deinitialise(yaffs_Device *dev)
4779 {
4780         if(dev->isMounted)
4781         {
4782         
4783                 yaffs_DeinitialiseBlocks(dev);
4784                 yaffs_DeinitialiseTnodes(dev);
4785                 yaffs_DeinitialiseObjects(dev);
4786                 YFREE(dev->localBuffer);
4787         }
4788         
4789 }
4790
4791 #if 0
4792
4793 int  yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4794 {
4795         int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
4796         
4797         struct list_head *i;    
4798         yaffs_Object *l;
4799         
4800         
4801         // To the free chunks add the chunks that are in the deleted unlinked files.
4802         list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4803         {
4804                 l = list_entry(i, yaffs_Object,siblings);
4805                 if(l->deleted)
4806                 {
4807                         nFree++;
4808                         nFree += l->nDataChunks;
4809                 }
4810         }
4811         
4812         
4813         // printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);        
4814
4815         if(nFree < 0) nFree = 0;
4816
4817         return nFree;   
4818         
4819 }
4820
4821 #endif
4822
4823 int  yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4824 {
4825         int nFree;
4826         int pending;
4827         int b;
4828         
4829         yaffs_BlockInfo *blk;
4830         
4831         struct list_head *i;    
4832         yaffs_Object *l;
4833         
4834         for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
4835         {
4836                 blk = yaffs_GetBlockInfo(dev,b);
4837                 
4838                 switch(blk->blockState)
4839                 {
4840                         case YAFFS_BLOCK_STATE_EMPTY:
4841                         case YAFFS_BLOCK_STATE_ALLOCATING: 
4842                         case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
4843                         default: break;
4844                 }
4845         }
4846         
4847         
4848         pending = 0;
4849         
4850         // To the free chunks add the chunks that are in the deleted unlinked files.
4851         list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4852         {
4853                 if(i)
4854                 {
4855                         l = list_entry(i, yaffs_Object,siblings);
4856                         if(l->deleted)
4857                         {
4858                                 pending++;
4859                                 pending += l->nDataChunks;
4860                         }
4861                 }
4862         }
4863         
4864         
4865         
4866         //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
4867         
4868         if(nFree != dev->nFreeChunks) 
4869         {
4870         //      printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
4871         }
4872
4873         nFree += pending;
4874         
4875         if(nFree < 0) nFree = 0;
4876
4877         return nFree;   
4878         
4879 }
4880
4881
4882
4883 /////////////////// YAFFS test code //////////////////////////////////
4884
4885 #define yaffs_CheckStruct(structure,syze, name) \
4886            if(sizeof(structure) != syze) \
4887                { \
4888                  T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
4889                  return YAFFS_FAIL; \
4890                    }
4891                  
4892                  
4893 static int yaffs_CheckStructures(void)
4894 {
4895         yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4896         yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4897         yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4898 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
4899         yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4900 #endif
4901         yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4902         
4903         
4904         return YAFFS_OK;
4905 }
4906
4907 #if 0
4908 void yaffs_GutsTest(yaffs_Device *dev)
4909 {
4910         
4911         if(yaffs_CheckStructures() != YAFFS_OK)
4912         {
4913                 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
4914                 return;
4915         }
4916         
4917         yaffs_TnodeTest(dev);
4918         yaffs_ObjectTest(dev);  
4919 }
4920 #endif
4921
4922
4923