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