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