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