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