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