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