2 * YAFFS: Yet another FFS. A NAND-flash specific file system.
3 * yaffs_guts.c The main guts of YAFFS
5 * Copyright (C) 2002 Aleph One Ltd.
6 * for Toby Churchill Ltd and Brightstar Engineering
8 * Created by Charles Manning <charles@aleph1.co.uk>
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.
17 const char *yaffs_guts_c_version="$Id: yaffs_guts.c,v 1.10 2002-09-27 20:50:50 charles Exp $";
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
25 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
28 // External functions for ECC on data
29 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
30 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
33 // countBits is a quick way of counting the number of bits in a byte.
34 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
36 static const char yaffs_countBitsTable[256] =
38 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
39 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
40 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
41 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
42 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
43 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
44 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
45 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
46 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
47 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
48 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
49 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
50 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
51 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
52 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
53 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
56 static int yaffs_CountBits(__u8 x)
59 retVal = yaffs_countBitsTable[x];
66 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
67 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
68 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
69 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
71 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
72 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
73 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force);
74 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
83 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
84 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
85 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
86 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare);
87 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare);
89 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
91 static int yaffs_UnlinkWorker(yaffs_Object *obj);
94 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1);
98 loff_t yaffs_GetFileSize(yaffs_Object *obj);
100 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
101 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
104 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
106 #ifdef YAFFS_PARANOID
107 static int yaffs_CheckFileSanity(yaffs_Object *in);
109 #define yaffs_CheckFileSanity(in)
112 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
113 static void yaffs_InvalidateChunkCache(yaffs_Object *in);
114 #define yaffs_INVALIDATECHUNKCACHE(in) yaffs_InvalidateChunkCache(in)
116 #define yaffs_INVALIDATECHUNKCACHE(in)
120 static __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
122 if(blk < dev->startBlock || blk > dev->endBlock)
126 return &dev->blockInfo[blk - dev->startBlock];
130 static __inline__ int yaffs_HashFunction(int n)
132 return (n % YAFFS_NOBJECT_BUCKETS);
136 yaffs_Object *yaffs_Root(yaffs_Device *dev)
141 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
143 return dev->lostNFoundDir;
147 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
150 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
154 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, __u8 *data, yaffs_Spare *spare,int doErrorCorrection)
158 yaffs_Spare localSpare;
159 int eccResult1,eccResult2;
165 // If we don't have a real spare, then we use a local one.
166 // Need this for the calculation of the ecc
170 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
171 if(data && doErrorCorrection)
174 //Todo handle any errors
175 nand_calculate_ecc(data,calcEcc);
176 eccResult1 = nand_correct_data (data,spare->ecc1, calcEcc);
177 nand_calculate_ecc(&data[256],calcEcc);
178 eccResult2 = nand_correct_data (&data[256],spare->ecc2, calcEcc);
182 T((TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
185 else if(eccResult1<0)
187 T((TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
193 T((TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
196 else if(eccResult2<0)
198 T((TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
202 if(eccResult1 || eccResult2)
204 // Hoosterman, we had a data problem on this page
205 yaffs_HandleReadDataError(dev,chunkInNAND);
212 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
216 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
217 static __u8 data[YAFFS_BYTES_PER_CHUNK];
218 static __u8 spare[16];
221 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
227 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
231 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL;
232 if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
241 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
243 dev->nBlockErasures++;
244 return dev->eraseBlockInNAND(dev,blockInNAND);
247 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
249 return dev->initialiseNAND(dev);
252 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
259 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
263 chunk = yaffs_AllocateChunk(dev,useReserve);
268 // First check this chunk is erased...
269 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
270 writeOk = yaffs_CheckChunkErased(dev,chunk);
274 T((TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
278 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
284 // If verify fails, then delete this chunk and try again
285 // To verify we compare everything except the block and
286 // page status bytes.
287 // NB We check a raw read without ECC correction applied
288 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
290 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
291 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
294 T((TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
303 // Copy the data into the write buffer.
304 // NB We do this at the end to prevent duplicates in the case of a write error.
306 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
310 yaffs_HandleWriteChunkError(dev,chunk);
314 } while(chunk >= 0 && ! writeOk);
318 T((TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
319 dev->nRetriedWrites+= (attempts - 1);
326 // Functions for robustisizing
330 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
332 // Ding the blockStatus in the first two pages of the block.
336 memset(&spare, 0xff,sizeof(yaffs_Spare));
338 spare.blockStatus = 0;
340 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK, NULL , &spare);
341 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK + 1, NULL , &spare);
343 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
344 dev->nRetiredBlocks++;
349 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
351 dev->doingBufferedBlockRewrite = 1;
353 // Remove erased chunks
354 // Rewrite existing chunks to a new block
355 // Set current write block to the new block
357 dev->doingBufferedBlockRewrite = 0;
363 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
365 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
367 // Mark the block for retirement
368 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
369 T((TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
373 // Just do a garbage collection on the affected block then retire the block
378 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
382 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare)
386 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare)
390 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
392 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
394 // Mark the block for retirement
395 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
397 yaffs_DeleteChunk(dev,chunkInNAND);
403 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1)
407 if( memcmp(d0,d1,YAFFS_BYTES_PER_CHUNK) != 0 ||
408 s0->tagByte0 != s1->tagByte0 ||
409 s0->tagByte1 != s1->tagByte1 ||
410 s0->tagByte2 != s1->tagByte2 ||
411 s0->tagByte3 != s1->tagByte3 ||
412 s0->tagByte4 != s1->tagByte4 ||
413 s0->tagByte5 != s1->tagByte5 ||
414 s0->tagByte6 != s1->tagByte6 ||
415 s0->tagByte7 != s1->tagByte7 ||
416 s0->ecc1[0] != s1->ecc1[0] ||
417 s0->ecc1[1] != s1->ecc1[1] ||
418 s0->ecc1[2] != s1->ecc1[2] ||
419 s0->ecc2[0] != s1->ecc2[0] ||
420 s0->ecc2[1] != s1->ecc2[1] ||
421 s0->ecc2[2] != s1->ecc2[2] )
430 ///////////////////////// Object management //////////////////
431 // List of spare objects
432 // The list is hooked together using the first pointer
435 // static yaffs_Object *yaffs_freeObjects = NULL;
437 // static int yaffs_nFreeObjects;
439 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
441 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
444 static __u16 yaffs_CalcNameSum(const char *name)
449 __u8 *bname = (__u8 *)name;
463 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
465 nand_calculate_ecc (data , spare->ecc1);
466 nand_calculate_ecc (&data[256] , spare->ecc2);
469 void yaffs_CalcTagsECC(yaffs_Tags *tags)
473 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
480 for(i = 0; i < 8; i++)
482 for(j = 1; j &0xff; j<<=1)
497 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
499 unsigned ecc = tags->ecc;
501 yaffs_CalcTagsECC(tags);
507 // TODO: Handle the failure better. Retire?
508 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
512 b[ecc / 8] ^= (1 << (ecc & 7));
514 // Now recvalc the ecc
515 yaffs_CalcTagsECC(tags);
517 return 1; // recovered error
521 // Wierd ecc failure value
522 // TODO Need to do somethiong here
523 return -1; //unrecovered error
530 ///////////////////////// TNODES ///////////////////////
532 // List of spare tnodes
533 // The list is hooked together using the first pointer
536 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
538 // static int yaffs_nFreeTnodes;
540 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
544 // yaffs_CreateTnodes creates a bunch more tnodes and
545 // adds them to the tnode free list.
546 // Don't use this function directly
548 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
551 yaffs_Tnode *newTnodes;
552 yaffs_TnodeList *tnl;
554 if(nTnodes < 1) return YAFFS_OK;
558 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
562 YALERT("Could not malloc tnodes");
566 // Hook them into the free list
567 for(i = 0; i < nTnodes - 1; i++)
569 newTnodes[i].internal[0] = &newTnodes[i+1];
572 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
573 dev->freeTnodes = newTnodes;
574 dev->nFreeTnodes+= nTnodes;
575 dev->nTnodesCreated += nTnodes;
577 // Now add this bunch of tnodes to a list for freeing up.
579 tnl = YMALLOC(sizeof(yaffs_TnodeList));
582 YALERT("Could not add tnodes to management list");
586 tnl->tnodes = newTnodes;
587 tnl->next = dev->allocatedTnodeList;
588 dev->allocatedTnodeList = tnl;
592 YINFO("Tnodes created");
599 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
600 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
602 yaffs_Tnode *tn = NULL;
604 // If there are none left make more
607 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
612 tn = dev->freeTnodes;
613 dev->freeTnodes = dev->freeTnodes->internal[0];
616 memset(tn,0,sizeof(yaffs_Tnode));
624 // FreeTnode frees up a tnode and puts it back on the free list
625 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
627 tn->internal[0] = dev->freeTnodes;
628 dev->freeTnodes = tn;
633 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
635 // Free the list of allocated tnodes
637 while(dev->allocatedTnodeList)
639 YFREE(dev->allocatedTnodeList->tnodes);
640 dev->allocatedTnodeList = dev->allocatedTnodeList->next;
643 dev->freeTnodes = NULL;
644 dev->nFreeTnodes = 0;
647 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
649 dev->allocatedTnodeList = NULL;
650 dev->freeTnodes = NULL;
651 dev->nFreeTnodes = 0;
652 dev->nTnodesCreated = 0;
656 void yaffs_TnodeTest(yaffs_Device *dev)
661 yaffs_Tnode *tn[1000];
663 YINFO("Testing TNodes");
665 for(j = 0; j < 50; j++)
667 for(i = 0; i < 1000; i++)
669 tn[i] = yaffs_GetTnode(dev);
672 YALERT("Getting tnode failed");
675 for(i = 0; i < 1000; i+=3)
677 yaffs_FreeTnode(dev,tn[i]);
684 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
686 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
687 // The look up tree is represented by the top tnode and the number of topLevel
688 // in the tree. 0 means only the level 0 tnode is in the tree.
691 // FindLevel0Tnode finds the level 0 tnode, if one exists.
692 // Used when reading.....
693 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
696 yaffs_Tnode *tn = fStruct->top;
698 int requiredTallness;
699 int level = fStruct->topLevel;
701 // Check sane level and chunk Id
702 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
705 sprintf(str,"Bad level %d",level);
710 if(chunkId > YAFFS_MAX_CHUNK_ID)
713 sprintf(str,"Bad chunkId %d",chunkId);
718 // First check we're tall enough (ie enough topLevel)
720 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
721 requiredTallness = 0;
724 i >>= YAFFS_TNODES_INTERNAL_BITS;
729 if(requiredTallness > fStruct->topLevel)
731 // Not tall enough, so we can't find it, return NULL.
736 // Traverse down to level 0
737 while (level > 0 && tn)
739 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
740 YAFFS_TNODES_INTERNAL_MASK];
748 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
749 // This happens in two steps:
750 // 1. If the tree isn't tall enough, then make it taller.
751 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
753 // Used when modifying the tree.
755 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
760 int requiredTallness;
766 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
768 // Check sane level and page Id
769 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
772 sprintf(str,"Bad level %d",fStruct->topLevel);
777 if(chunkId > YAFFS_MAX_CHUNK_ID)
780 sprintf(str,"Bad chunkId %d",chunkId);
785 // First check we're tall enough (ie enough topLevel)
787 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
788 requiredTallness = 0;
791 i >>= YAFFS_TNODES_INTERNAL_BITS;
795 //T((TSTR(" required=%d"),requiredTallness));
798 if(requiredTallness > fStruct->topLevel)
800 // Not tall enough,gotta make the tree taller
801 for(i = fStruct->topLevel; i < requiredTallness; i++)
803 //T((TSTR(" add new top")));
805 tn = yaffs_GetTnode(dev);
809 tn->internal[0] = fStruct->top;
814 YALERT("No more tnodes");
818 fStruct->topLevel = requiredTallness;
822 // Traverse down to level 0, adding anything we need
824 l = fStruct->topLevel;
828 i = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
829 YAFFS_TNODES_INTERNAL_MASK;
831 //T((TSTR(" [%d:%d]"),l,i));
835 //T((TSTR(" added")));
837 tn->internal[i] = yaffs_GetTnode(dev);
840 tn = tn->internal[i];
850 // DeleteWorker scans backwards through the tnode tree and deletes all the
851 // chunks and tnodes in the file
852 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
854 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
870 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
874 if(limit && (*limit) < 0)
880 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
881 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
885 yaffs_FreeTnode(in->myDev,tn->internal[i]);
886 tn->internal[i] = NULL;
891 return (allDone) ? 1 : 0;
895 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0; i--) //NB Don't apply the limit here, always delete a whole level0
901 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
903 theChunk = tn->level0[i] << in->myDev->chunkGroupBits;
905 // Now we need to search for it
906 for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
908 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
909 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
923 yaffs_DeleteChunk(in->myDev,theChunk);
950 // Pruning removes any part of the file structure tree that is beyond the
951 // bounds of the file (ie that does not point to chunks).
953 // A file should only get pruned when its size is reduced.
955 // Before pruning, the chunks must be pulled from the tree and the
956 // level 0 tnode entries must be zeroed out.
957 // Could also use this for file deletion, but that's probably better handled
958 // by a special case.
960 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
962 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
971 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
973 if(tn->internal[i] && level > 0)
975 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
984 if(hasData == 0 && del0)
986 // Free and return NULL
988 yaffs_FreeTnode(dev,tn);
998 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1005 if(fStruct->topLevel > 0)
1007 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1009 // Now we have a tree with all the non-zero branches NULL but the height
1010 // is the same as it was.
1011 // Let's see if we can trim internal tnodes to shorten the tree.
1012 // We can do this if only the 0th element in the tnode is in use
1013 // (ie all the non-zero are NULL)
1015 while(fStruct->topLevel && !done)
1020 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1030 fStruct->top = tn->internal[0];
1031 fStruct->topLevel--;
1032 yaffs_FreeTnode(dev,tn);
1047 /////////////////////// End of File Structure functions. /////////////////
1049 // yaffs_CreateFreeObjects creates a bunch more objects and
1050 // adds them to the object free list.
1051 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1054 yaffs_Object *newObjects;
1055 yaffs_ObjectList *list;
1057 if(nObjects < 1) return YAFFS_OK;
1059 // make these things
1061 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1065 YALERT("Could not allocate more objects");
1069 // Hook them into the free list
1070 for(i = 0; i < nObjects - 1; i++)
1072 (yaffs_Object *)newObjects[i].siblings.next = &newObjects[i+1];
1075 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1076 dev->freeObjects = newObjects;
1077 dev->nFreeObjects+= nObjects;
1078 dev->nObjectsCreated+= nObjects;
1080 // Now add this bunch of Objects to a list for freeing up.
1082 list = YMALLOC(sizeof(yaffs_ObjectList));
1085 YALERT("Could not add Objects to management list");
1089 list->objects = newObjects;
1090 list->next = dev->allocatedObjectList;
1091 dev->allocatedObjectList = list;
1095 YINFO("Objects created");
1102 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1103 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1105 yaffs_Object *tn = NULL;
1107 // If there are none left make more
1108 if(!dev->freeObjects)
1110 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1113 if(dev->freeObjects)
1115 tn = dev->freeObjects;
1116 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1117 dev->nFreeObjects--;
1119 // Now sweeten it up...
1121 memset(tn,0,sizeof(yaffs_Object));
1124 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1125 INIT_LIST_HEAD(&(tn->hardLinks));
1126 INIT_LIST_HEAD(&(tn->hashLink));
1127 INIT_LIST_HEAD(&tn->siblings);
1129 // Add it to the lost and found directory.
1130 // NB Can't put root or lostNFound in lostNFound so
1131 // check if lostNFound exists first
1132 if(dev->lostNFoundDir)
1134 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1142 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1145 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1148 obj->fake = 1; // it is fake so it has no NAND presence...
1149 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1150 obj->unlinkAllowed= 0; // ... or unlink it
1153 obj->st_mode = mode;
1155 obj->chunkId = 0; // Not a valid chunk.
1163 static void yaffs_UnhashObject(yaffs_Object *tn)
1166 yaffs_Device *dev = tn->myDev;
1169 // If it is still linked into the bucket list, free from the list
1170 if(!list_empty(&tn->hashLink))
1172 list_del_init(&tn->hashLink);
1173 bucket = yaffs_HashFunction(tn->objectId);
1174 dev->objectBucket[bucket].count--;
1180 // FreeObject frees up a Object and puts it back on the free list
1181 static void yaffs_FreeObject(yaffs_Object *tn)
1184 yaffs_Device *dev = tn->myDev;
1186 yaffs_UnhashObject(tn);
1188 // Link into the free list.
1189 (yaffs_Object *)(tn->siblings.next) = dev->freeObjects;
1190 dev->freeObjects = tn;
1191 dev->nFreeObjects++;
1197 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1199 // Free the list of allocated Objects
1201 while( dev->allocatedObjectList)
1203 YFREE(dev->allocatedObjectList->objects);
1204 dev->allocatedObjectList = dev->allocatedObjectList->next;
1207 dev->freeObjects = NULL;
1208 dev->nFreeObjects = 0;
1211 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1215 dev->allocatedObjectList = NULL;
1216 dev->freeObjects = NULL;
1217 dev->nFreeObjects = 0;
1219 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1221 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1222 dev->objectBucket[i].count = 0;
1232 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1237 int lowest = 999999;
1240 // First let's see if we can find one that's empty.
1242 for(i = 0; i < 10 && lowest > 0; i++)
1245 x %= YAFFS_NOBJECT_BUCKETS;
1246 if(dev->objectBucket[x].count < lowest)
1248 lowest = dev->objectBucket[x].count;
1254 // If we didn't find an empty list, then try
1255 // looking a bit further for a short one
1257 for(i = 0; i < 10 && lowest > 3; i++)
1260 x %= YAFFS_NOBJECT_BUCKETS;
1261 if(dev->objectBucket[x].count < lowest)
1263 lowest = dev->objectBucket[x].count;
1272 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1274 int bucket = yaffs_FindNiceObjectBucket(dev);
1276 // Now find an object value that has not already been taken
1277 // by scanning the list.
1280 struct list_head *i;
1284 //yaffs_CheckObjectHashSanity();
1289 n += YAFFS_NOBJECT_BUCKETS;
1290 if(1 ||dev->objectBucket[bucket].count > 0)
1292 list_for_each(i,&dev->objectBucket[bucket].list)
1294 // If there is already one in the list
1295 if(list_entry(i, yaffs_Object,hashLink)->objectId == n)
1303 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1308 void yaffs_HashObject(yaffs_Object *in)
1310 int bucket = yaffs_HashFunction(in->objectId);
1311 yaffs_Device *dev = in->myDev;
1313 if(!list_empty(&in->hashLink))
1319 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1320 dev->objectBucket[bucket].count++;
1324 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,int number)
1326 int bucket = yaffs_HashFunction(number);
1327 struct list_head *i;
1330 list_for_each(i,&dev->objectBucket[bucket].list)
1332 // Look if it is in the list
1333 in = list_entry(i, yaffs_Object,hashLink);
1334 if(in->objectId == number)
1345 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1348 yaffs_Object *theObject;
1352 number = yaffs_CreateNewObjectNumber(dev);
1355 theObject = yaffs_AllocateEmptyObject(dev);
1359 theObject->fake = 0;
1360 theObject->renameAllowed = 1;
1361 theObject->unlinkAllowed = 1;
1362 theObject->objectId = number;
1363 yaffs_HashObject(theObject);
1364 theObject->variantType = type;
1365 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1369 case YAFFS_OBJECT_TYPE_FILE:
1370 theObject->variant.fileVariant.fileSize = 0;
1371 theObject->variant.fileVariant.scannedFileSize = 0;
1372 theObject->variant.fileVariant.topLevel = 0;
1373 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1375 case YAFFS_OBJECT_TYPE_DIRECTORY:
1376 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1378 case YAFFS_OBJECT_TYPE_SYMLINK:
1379 // No action required
1381 case YAFFS_OBJECT_TYPE_HARDLINK:
1382 // No action required
1384 case YAFFS_OBJECT_TYPE_SPECIAL:
1385 // No action required
1387 case YAFFS_OBJECT_TYPE_UNKNOWN:
1388 // todo this should not happen
1396 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1398 yaffs_Object *theObject = NULL;
1402 theObject = yaffs_FindObjectByNumber(dev,number);
1407 theObject = yaffs_CreateNewObject(dev,number,type);
1414 char *yaffs_CloneString(const char *str)
1416 char *newStr = NULL;
1420 newStr = YMALLOC(strlen(str) + 1);
1429 // Mknod (create) a new object.
1430 // equivalentObject only has meaning for a hard link;
1431 // aliasString only has meaning for a sumlink.
1432 // rdev only has meaning for devices (a subset of special objects)
1433 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1434 yaffs_Object *parent,
1439 yaffs_Object *equivalentObject,
1440 const char *aliasString,
1445 yaffs_Device *dev = parent->myDev;
1447 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1448 if(yaffs_FindObjectByName(parent,name))
1453 in = yaffs_CreateNewObject(dev,-1,type);
1459 in->variantType = type;
1465 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1467 in->nDataChunks = 0;
1469 in->sum = yaffs_CalcNameSum(name);
1472 yaffs_AddObjectToDirectory(parent,in);
1474 in->myDev = parent->myDev;
1479 case YAFFS_OBJECT_TYPE_SYMLINK:
1480 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1482 case YAFFS_OBJECT_TYPE_HARDLINK:
1483 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1484 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1485 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1487 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1488 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1489 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1490 case YAFFS_OBJECT_TYPE_UNKNOWN:
1494 if(yaffs_GetNumberOfFreeChunks(dev) <= 0 ||
1495 yaffs_UpdateObjectHeader(in,name,0) < 0)
1497 // Could not create the object header, fail the creation
1498 yaffs_UnlinkWorker(in);
1507 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1509 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1512 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1514 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1517 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1519 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1522 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1524 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1527 // NB yaffs_Link returns the object id of the equivalent object.
1528 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1530 // Get the real object in case we were fed a hard link as an equivalent object
1531 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1533 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1535 return equivalentObject;
1545 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName)
1551 newDir = obj->parent; // use the old directory
1554 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1556 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1557 // duplicate names are allowed.
1558 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1560 (!yaffs_FindObjectByName(newDir,newName) &&
1561 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY))
1563 obj->sum = yaffs_CalcNameSum(newName);
1566 yaffs_AddObjectToDirectory(newDir,obj);
1568 if(unlinkOp) obj->unlinked = 1;
1571 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1580 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1584 obj = yaffs_FindObjectByName(oldDir,oldName);
1585 if(obj && obj->renameAllowed)
1587 return yaffs_ChangeObjectName(obj,newDir,newName);
1594 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1596 // Scan the buckets and check that the lists
1597 // have as many members as the count says there are
1600 struct list_head *j;
1603 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1607 list_for_each(j,&dev->objectBucket[bucket].list)
1612 if(countEm != dev->objectBucket[bucket].count)
1614 YALERT("Inode hash inconsistency");
1622 void yaffs_ObjectTest(yaffs_Device *dev)
1624 yaffs_Object *in[1000];
1626 yaffs_Object *inold[1000];
1630 memset(in,0,1000*sizeof(yaffs_Object *));
1631 memset(inold,0,1000*sizeof(yaffs_Object *));
1633 yaffs_CheckObjectHashSanity(dev);
1635 for(j = 0; j < 10; j++)
1639 for(i = 0; i < 1000; i++)
1641 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1644 YINFO("No more inodes");
1648 inNo[i] = in[i]->objectId;
1652 for(i = 0; i < 1000; i++)
1654 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1656 //T(("Differnce in look up test\n"));
1660 // T(("Look up ok\n"));
1664 yaffs_CheckObjectHashSanity(dev);
1666 for(i = 0; i < 1000; i+=3)
1668 yaffs_FreeObject(in[i]);
1673 yaffs_CheckObjectHashSanity(dev);
1680 /////////////////////////// Block Management and Page Allocation ///////////////////
1683 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1685 dev->allocationBlock = -1; // force it to get a new one
1686 //Todo we're assuming the malloc will pass.
1687 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1690 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1697 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1699 YFREE(dev->blockInfo);
1702 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1703 // for garbage collection.
1705 static int yaffs_FindDirtiestBlock(yaffs_Device *dev)
1708 int b = dev->currentDirtyChecker;
1712 int pagesInUse = 100; // silly big number
1713 yaffs_BlockInfo *bi;
1715 for(i = dev->startBlock; i <= dev->endBlock && pagesInUse > 2 ; i++)
1718 if (b > dev->endBlock)
1720 b = dev->startBlock;
1723 bi = yaffs_GetBlockInfo(dev,b);
1725 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1726 bi->pagesInUse < pagesInUse)
1729 pagesInUse = bi->pagesInUse;
1733 dev->currentDirtyChecker = b;
1739 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
1741 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
1745 // If the block is still healthy erase it and mark as clean.
1746 // If the block has had a data failure, then retire it.
1747 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1749 if(!bi->needsRetiring)
1751 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
1754 T((TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
1760 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1761 dev->nErasedBlocks++;
1765 T((TSTR("Erased block %d" TENDSTR),blockNo));
1769 yaffs_RetireBlock(dev,blockNo);
1770 T((TSTR("**>> Block %d retired" TENDSTR),blockNo));
1775 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
1778 yaffs_BlockInfo *bi;
1780 if(dev->nErasedBlocks < 1)
1782 // Hoosterman we've got a problem.
1783 // Can't get space to gc
1787 // Find an empty block.
1789 for(i = dev->startBlock; i <= dev->endBlock; i++)
1791 bi = yaffs_GetBlockInfo(dev,i);
1792 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
1794 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1795 dev->nErasedBlocks--;
1805 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
1808 yaffs_BlockInfo *bi;
1810 if(dev->allocationBlock < 0)
1812 // Get next block to allocate off
1813 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
1814 dev->allocationPage = 0;
1817 if(!useReserve && dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
1819 // Not enough space to allocate unless we're allowed to use the reserve.
1823 // Next page please....
1824 if(dev->allocationBlock >= 0)
1826 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
1828 retVal = (dev->allocationBlock * YAFFS_CHUNKS_PER_BLOCK) +
1829 dev->allocationPage;
1831 bi->pageBits |= (1 << (dev->allocationPage));
1833 dev->allocationPage++;
1837 // If the block is full set the state to full
1838 if(dev->allocationPage >= YAFFS_CHUNKS_PER_BLOCK)
1840 bi->blockState = YAFFS_BLOCK_STATE_FULL;
1841 dev->allocationBlock = -1;
1848 T((TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
1854 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
1863 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
1865 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
1867 yaffs_Object *object;
1869 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
1871 for(mask = 1,oldChunk = block * YAFFS_CHUNKS_PER_BLOCK;
1872 mask && bi->pageBits;
1873 mask <<= 1, oldChunk++ )
1875 if(bi->pageBits & mask)
1878 // This page is in use and needs to be copied off
1882 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
1884 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
1886 yaffs_GetTagsFromSpare(dev,&spare,&tags);
1888 tags.serialNumber++;
1889 yaffs_LoadTagsIntoSpare(&spare,&tags);
1892 newChunk = yaffs_AllocatePage(dev,1);
1898 yaffs_WriteChunkToNAND(dev,newChunk, buffer, &spare);
1901 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
1908 object = yaffs_FindObjectByNumber(dev,tags.objectId);
1910 // Ok, now fix up the Tnodes etc.
1912 if(tags.chunkId == 0)
1915 object->chunkId = newChunk;
1919 // It's a data chunk
1920 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
1924 yaffs_DeleteChunk(dev,oldChunk);
1933 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
1935 // todo find a file to delete
1936 struct list_head *i;
1940 // To the free chunks add the chunks that are in the deleted unlinked files.
1941 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
1943 l = list_entry(i, yaffs_Object,siblings);
1952 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
1954 // This does background deletion on unlinked files.. only deleted ones.
1955 // If we don't have a file we're working on then find one
1956 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
1958 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
1961 // OK, we're working on a file...
1962 if(dev->unlinkedDeletion)
1964 yaffs_Object *obj = dev->unlinkedDeletion;
1967 limit = 50; // Max number of chunks to delete in a file. NB this can be exceeded, but not by much.
1968 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
1970 if(obj->nDataChunks == 0)
1972 // Done all the deleting of data chunks.
1973 // Now dump the header and clean up
1974 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
1975 yaffs_DoGenericObjectDeletion(obj);
1976 dev->nDeletedFiles--;
1977 dev->nUnlinkedFiles--;
1978 dev->nBackgroundDeletions++;
1979 dev->unlinkedDeletion = NULL;
1984 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
1988 yaffs_DoUnlinkedFileDeletion(dev);
1990 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + YAFFS_GARBAGE_COLLECT_LOW_WATER))
1992 dev->garbageCollectionRequired = 1;
1995 if(dev->garbageCollectionRequired)
1997 dev->garbageCollections++;
1998 dev->garbageCollectionRequired = 0;
1999 if(dev->blockSelectedForGC >= 0)
2001 block = dev->blockSelectedForGC;
2005 block = yaffs_FindDirtiestBlock(dev);
2010 return yaffs_GarbageCollectBlock(dev,block);
2022 //////////////////////////// TAGS ///////////////////////////////////////
2024 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2026 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2028 yaffs_CalcTagsECC(tagsPtr);
2030 sparePtr->tagByte0 = tu->asBytes[0];
2031 sparePtr->tagByte1 = tu->asBytes[1];
2032 sparePtr->tagByte2 = tu->asBytes[2];
2033 sparePtr->tagByte3 = tu->asBytes[3];
2034 sparePtr->tagByte4 = tu->asBytes[4];
2035 sparePtr->tagByte5 = tu->asBytes[5];
2036 sparePtr->tagByte6 = tu->asBytes[6];
2037 sparePtr->tagByte7 = tu->asBytes[7];
2040 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2042 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2045 tu->asBytes[0]= sparePtr->tagByte0;
2046 tu->asBytes[1]= sparePtr->tagByte1;
2047 tu->asBytes[2]= sparePtr->tagByte2;
2048 tu->asBytes[3]= sparePtr->tagByte3;
2049 tu->asBytes[4]= sparePtr->tagByte4;
2050 tu->asBytes[5]= sparePtr->tagByte5;
2051 tu->asBytes[6]= sparePtr->tagByte6;
2052 tu->asBytes[7]= sparePtr->tagByte7;
2054 result = yaffs_CheckECCOnTags(tagsPtr);
2057 dev->tagsEccFixed++;
2061 dev->tagsEccUnfixed++;
2065 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2067 memset(spare,0xFF,sizeof(yaffs_Spare));
2070 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2075 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2077 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2078 yaffs_GetTagsFromSpare(dev,&spare,tags);
2091 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2093 // NB There must be tags, data is optional
2094 // If there is data, then an ECC is calculated on it.
2103 yaffs_SpareInitialise(&spare);
2108 yaffs_CalcECC(buffer,&spare);
2111 yaffs_LoadTagsIntoSpare(&spare,tags);
2113 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2119 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2121 // NB There must be tags, data is optional
2122 // If there is data, then an ECC is calculated on it.
2131 yaffs_SpareInitialise(&spare);
2136 yaffs_CalcECC(buffer,&spare);
2139 yaffs_LoadTagsIntoSpare(&spare,tags);
2141 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2145 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2147 return ( tags->chunkId == chunkInObject &&
2148 tags->objectId == objectId &&
2149 !chunkDeleted) ? 1 : 0;
2155 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2157 //Get the Tnode, then get the level 0 offset chunk offset
2160 yaffs_Tags localTags;
2165 yaffs_Device *dev = in->myDev;
2170 // Passed a NULL, so use our own tags space
2174 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2178 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2180 // Now we need to do the shifting etc and search for it
2181 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2183 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2184 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2195 return found ? theChunk : -1;
2198 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2200 //Get the Tnode, then get the level 0 offset chunk offset
2203 yaffs_Tags localTags;
2206 yaffs_Device *dev = in->myDev;
2211 // Passed a NULL, so use our own tags space
2215 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2220 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2222 // Now we need to do the shifting etc and search for it
2223 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2225 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2226 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2237 // Delete the entry in the filestructure
2240 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2245 //T(("No level 0 found for %d\n", chunkInInode));
2250 //T(("Could not find %d to delete\n",chunkInInode));
2252 return found ? theChunk : -1;
2258 static int yaffs_CheckFileSanity(yaffs_Object *in)
2266 yaffs_Tags localTags;
2267 yaffs_Tags *tags = &localTags;
2272 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2274 //T(("Object not a file\n"));
2278 objId = in->objectId;
2279 fSize = in->variant.fileVariant.fileSize;
2280 nChunks = (fSize + YAFFS_BYTES_PER_CHUNK -1)/YAFFS_BYTES_PER_CHUNK;
2282 for(chunk = 1; chunk <= nChunks; chunk++)
2284 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2289 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2292 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2293 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2300 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2301 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2310 //T(("No level 0 found for %d\n", chunk));
2314 return failed ? YAFFS_FAIL : YAFFS_OK;
2319 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2322 yaffs_Device *dev = in->myDev;
2324 yaffs_Tags existingTags;
2326 unsigned existingSerial, newSerial;
2328 int newChunkDeleted;
2331 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2337 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2341 // If we're scanning then we need to test for duplicates
2342 // NB This does not need to be efficient since it should only ever
2343 // happen when the power fails during a write, then only one
2344 // chunk should ever be affected.
2347 if(existingChunk != 0)
2349 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2350 // thus we have to do a FindChunkInFile to get the real chunk id.
2352 // We have a duplicate now we need to decide which one to use
2353 // To do this we get both sets of tags and compare serial numbers.
2354 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2358 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2360 if(existingChunk <=0)
2362 //Hoosterman - how did this happen?
2367 // NB The deleted flags should be false, otherwise the chunks will
2368 // not be loaded during a scan
2370 newSerial = newTags.serialNumber;
2371 existingSerial = existingTags.serialNumber;
2373 if( existingChunk <= 0 ||
2374 ((existingSerial+1) & 3) == newSerial)
2377 // Delete the old one and drop through to update the tnode
2378 yaffs_DeleteChunk(dev,existingChunk);
2383 // Delete the new one and return early so that the tnode isn't changed
2384 yaffs_DeleteChunk(dev,chunkInNAND);
2391 if(existingChunk == 0)
2396 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2403 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2405 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2407 if(chunkInNAND >= 0)
2409 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2419 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId)
2424 yaffs_BlockInfo *bi;
2426 if(chunkId <= 0) return;
2428 block = chunkId / YAFFS_CHUNKS_PER_BLOCK;
2429 page = chunkId % YAFFS_CHUNKS_PER_BLOCK;
2430 yaffs_SpareInitialise(&spare);
2432 spare.pageStatus = 0; // To mark it as deleted.
2435 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2436 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2437 bi = yaffs_GetBlockInfo(dev,block);
2440 // Pull out of the management area.
2441 // If the whole block became dirty, this will kick off an erasure.
2442 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2443 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2447 bi->pageBits &= ~(1 << page);
2450 if(bi->pagesInUse == 0 &&
2451 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2453 yaffs_BlockBecameDirty(dev,block);
2459 // T(("Bad news deleting chunk %d\n",chunkId));
2467 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2469 // Find old chunk Need to do this to get serial number
2470 // Write new one and patch into tree.
2471 // Invalidate old tags.
2474 yaffs_Tags prevTags;
2479 yaffs_Device *dev = in->myDev;
2481 yaffs_CheckGarbageCollection(dev);
2483 // Get the previous chunk at this location in the file if it exists
2484 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2487 newTags.chunkId = chunkInInode;
2488 newTags.objectId = in->objectId;
2489 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2490 newTags.byteCount = nBytes;
2491 newTags.unusedStuff = 0xFFFFFFFF;
2493 yaffs_CalcTagsECC(&newTags);
2497 // Create new chunk in NAND
2498 newChunkId = yaffs_AllocatePage(dev,useReserve);
2505 yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,buffer,&newTags);
2507 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId);
2510 if(prevChunkId >= 0)
2512 yaffs_DeleteChunk(dev,prevChunkId);
2516 yaffs_CheckFileSanity(in);
2525 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2528 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2531 if(prevChunkId >= 0)
2533 yaffs_DeleteChunk(dev,prevChunkId);
2537 yaffs_CheckFileSanity(in);
2548 // UpdateObjectHeader updates the header on NAND for an object.
2549 // If name is not NULL, then that new name is used.
2551 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2554 yaffs_Device *dev = in->myDev;
2560 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2561 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2563 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2564 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2566 yaffs_INVALIDATECHUNKCACHE(in);
2568 if(!in->fake || force)
2571 yaffs_CheckGarbageCollection(dev);
2573 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2575 prevChunkId = in->chunkId;
2577 if(prevChunkId >= 0)
2579 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2583 oh->type = in->variantType;
2585 oh->st_mode = in->st_mode;
2586 oh->st_uid = in->st_uid;
2587 oh->st_gid = in->st_gid;
2588 oh->st_atime = in->st_atime;
2589 oh->st_mtime = in->st_mtime;
2590 oh->st_ctime = in->st_ctime;
2591 oh->st_rdev = in->st_rdev;
2595 oh->parentObjectId = in->parent->objectId;
2599 oh->parentObjectId = 0;
2605 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2606 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
2608 else if(prevChunkId)
2610 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
2614 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2617 switch(in->variantType)
2619 case YAFFS_OBJECT_TYPE_UNKNOWN:
2620 // Should not happen
2622 case YAFFS_OBJECT_TYPE_FILE:
2623 oh->fileSize = in->variant.fileVariant.fileSize;
2625 case YAFFS_OBJECT_TYPE_HARDLINK:
2626 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
2628 case YAFFS_OBJECT_TYPE_SPECIAL:
2631 case YAFFS_OBJECT_TYPE_DIRECTORY:
2634 case YAFFS_OBJECT_TYPE_SYMLINK:
2635 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
2636 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2642 newTags.chunkId = 0;
2643 newTags.objectId = in->objectId;
2644 newTags.serialNumber = in->serial;
2645 newTags.byteCount = 0xFFFFFFFF;
2646 newTags.unusedStuff = 0xFFFFFFFF;
2648 yaffs_CalcTagsECC(&newTags);
2653 // Create new chunk in NAND
2654 newChunkId = yaffs_AllocatePage(dev,1);
2659 yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,bufferNew,&newTags);
2661 in->chunkId = newChunkId;
2663 if(prevChunkId >= 0)
2665 yaffs_DeleteChunk(dev,prevChunkId);
2674 // Create new chunk in NAND
2675 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags,1);
2680 in->chunkId = newChunkId;
2682 if(prevChunkId >= 0)
2684 yaffs_DeleteChunk(dev,prevChunkId);
2698 /////////////////////// Short Read Cache ////////////////////////////////
2699 // In many siturations where there is no high level buffering a lot of
2700 // reads might be short sequential reads. eg. scanning a jpeg file.
2701 // In these cases, a shoprt read cache can provide a huge perfomance benefit
2702 // with dumb-as-a-rock code.
2703 // There are a limited number (~10) of cache chunks per device
2706 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2708 // Invalidate all the cache pages associated with this object
2709 // Do this whenever ther file is modified... dumb as a rock remember!
2710 static void yaffs_InvalidateChunkCache(yaffs_Object *in)
2713 yaffs_Device *dev = in->myDev;
2714 int id = in->objectId;
2716 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2718 if(dev->srCache[i].objectId == id)
2720 dev->srCache[i].objectId = 0;
2726 // Grab us a chunk for use.
2727 // First look for an empty one.
2728 // Then look for the least recently used one.
2729 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
2735 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2737 if(dev->srCache[i].objectId == 0)
2739 //T(("Grabbing empty %d\n",i));
2741 return &dev->srCache[i];
2746 usage = dev->srCache[i].lastUse;
2749 for(i = 1; i < YAFFS_N_CACHE_CHUNKS; i++)
2751 if(dev->srCache[i].lastUse < usage)
2753 usage = dev->srCache[i].lastUse;
2758 //T(("Grabbing non-empty %d\n",theOne));
2759 return &dev->srCache[theOne];
2764 // Find a cached chunk
2765 static yaffs_ChunkCache *yaffs_FindChunkCache(yaffs_Device *dev, int objectId, int chunkId)
2770 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2772 if(dev->srCache[i].objectId == objectId &&
2773 dev->srCache[i].chunkId == chunkId)
2777 return &dev->srCache[i];
2784 // Mark the chunk for the least recently used algorithym
2785 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache)
2787 if( dev->srLastUse < 0 ||
2788 dev->srLastUse > 1000000)
2790 // Reset the cache usages
2792 for(i = 1; i < YAFFS_N_CACHE_CHUNKS; i++)
2794 dev->srCache[i].lastUse = 0;
2801 cache->lastUse = dev->srLastUse;
2811 ///////////////////////// File read/write ///////////////////////////////
2812 // Read and write have very similar structures.
2813 // In general the read/write has three parts to it
2814 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
2815 // * Some complete chunks
2816 // * An incomplete chunk to end off with
2818 // Curve-balls: the first chunk might also be the last chunk.
2820 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
2823 // yaffs_Device *dev = in->myDev;
2825 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2826 yaffs_ChunkCache *cache;
2829 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2839 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
2840 start = offset % YAFFS_BYTES_PER_CHUNK;
2842 // OK now check for the curveball where the start and end are in
2844 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
2850 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
2853 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
2855 // An incomplete start or end chunk (or maybe both start and end chunk)
2856 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2857 // If we can't find the data in the cache, then load it up.
2858 cache = yaffs_FindChunkCache(in->myDev,in->objectId,chunk);
2861 cache = yaffs_GrabChunkCache(in->myDev);
2862 cache->objectId = in->objectId;
2863 cache->chunkId = chunk;
2864 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
2867 yaffs_UseChunkCache(in->myDev,cache);
2869 memcpy(buffer,&cache->data[start],nToCopy);
2871 // Read into the local buffer then copy...
2872 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2873 memcpy(buffer,&localBuffer[start],nToCopy);
2879 // Under WinCE can't do direct transfer. Need to use a local buffer.
2880 // This is because we otherwise screw up WinCE's memory mapper
2881 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2882 memcpy(buffer,localBuffer,YAFFS_BYTES_PER_CHUNK);
2884 // A full chunk. Read directly into the supplied buffer.
2885 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
2900 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
2902 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2910 int endOfWrite = offset+nBytes;
2911 int chunkWritten = 0;
2913 yaffs_INVALIDATECHUNKCACHE(in);
2915 while(n > 0 && chunkWritten >= 0)
2917 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
2918 start = offset % YAFFS_BYTES_PER_CHUNK;
2921 // OK now check for the curveball where the start and end are in
2923 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
2926 nToWriteBack = (start + n);
2930 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
2931 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
2934 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
2936 // An incomplete start or end chunk (or maybe both start and end chunk)
2937 // Read into the local buffer then copy, then copy over and write back.
2939 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2941 memcpy(&localBuffer[start],buffer,nToCopy);
2943 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,nToWriteBack,0);
2945 //T(("Write with readback to chunk %d %d\n",chunk,chunkWritten));
2952 // Under WinCE can't do direct transfer. Need to use a local buffer.
2953 // This is because we otherwise screw up WinCE's memory mapper
2954 memcpy(localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
2955 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,YAFFS_BYTES_PER_CHUNK,0);
2957 // A full chunk. Write directly from the supplied buffer.
2958 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
2960 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
2963 if(chunkWritten >= 0)
2973 // Update file object
2975 if(endOfWrite > in->variant.fileVariant.fileSize)
2977 in->variant.fileVariant.fileSize = endOfWrite;
2981 /*in->st_mtime = CURRENT_TIME; only update in flush*/
2987 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
2991 int oldFileSize = in->variant.fileVariant.fileSize;
2992 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
2994 yaffs_Device *dev = in->myDev;
2996 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2998 yaffs_INVALIDATECHUNKCACHE(in);
3000 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3002 return yaffs_GetFileSize(in);
3005 if(newSize < oldFileSize)
3008 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3010 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3011 YAFFS_BYTES_PER_CHUNK;
3013 // Delete backwards so that we don't end up with holes if
3014 // power is lost part-way through the operation.
3015 for(i = lastDel; i >= startDel; i--)
3017 // NB this could be optimised somewhat,
3018 // eg. could retrieve the tags and write them without
3019 // using yaffs_DeleteChunk
3021 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3022 if(chunkId <= 0 || chunkId >= (dev->endBlock * 32))
3024 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3029 yaffs_DeleteChunk(dev,chunkId);
3034 if(sizeOfPartialChunk != 0)
3036 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3038 // Got to read and rewrite the last chunk with its new size.
3039 yaffs_ReadChunkDataFromObject(in,lastChunk,localBuffer);
3041 yaffs_WriteChunkDataToObject(in,lastChunk,localBuffer,sizeOfPartialChunk,1);
3045 in->variant.fileVariant.fileSize = newSize;
3047 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3059 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3061 obj = yaffs_GetEquivalentObject(obj);
3063 switch(obj->variantType)
3065 case YAFFS_OBJECT_TYPE_FILE:
3066 return obj->variant.fileVariant.fileSize;
3067 case YAFFS_OBJECT_TYPE_SYMLINK:
3068 return strlen(obj->variant.symLinkVariant.alias);
3076 // yaffs_FlushFile() updates the file's
3079 int yaffs_FlushFile(yaffs_Object *in)
3084 //T(("flushing object header\n"));
3086 in->st_mtime = CURRENT_TIME;
3088 retVal = yaffs_UpdateObjectHeader(in,NULL,0);
3100 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3102 yaffs_INVALIDATECHUNKCACHE(in);
3103 yaffs_RemoveObjectFromDirectory(in);
3104 yaffs_DeleteChunk(in->myDev,in->chunkId);
3108 in->myInode->u.generic_ip = NULL;
3112 yaffs_FreeObject(in);
3117 // yaffs_DeleteFile deletes the whole file data
3118 // and the inode associated with the file.
3119 // It does not delete the links associated with the file.
3120 static int yaffs_UnlinkFile(yaffs_Object *in)
3123 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3124 // Delete the file data & tnodes
3126 yaffs_ResizeFile(in,0);
3128 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3132 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3134 return yaffs_DoGenericObjectDeletion(in);
3137 int immediateDeletion=0;
3138 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL);
3139 if(retVal == YAFFS_OK)
3142 //in->myDev->nUnlinkedFiles++;
3143 //in->renameAllowed = 0;
3147 immediateDeletion = 1;
3154 immediateDeletion = 1;
3159 if(immediateDeletion)
3161 T((TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3163 in->myDev->nDeletedFiles++;
3173 int yaffs_DeleteFile(yaffs_Object *in)
3175 int retVal = YAFFS_OK;
3178 retVal = yaffs_UnlinkFile(in);
3180 if(retVal == YAFFS_OK &&
3185 in->myDev->nDeletedFiles++;
3187 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3190 static int yaffs_DeleteDirectory(yaffs_Object *in)
3192 //First check that the directory is empty.
3193 if(list_empty(&in->variant.directoryVariant.children))
3195 return yaffs_DoGenericObjectDeletion(in);
3202 static int yaffs_DeleteSymLink(yaffs_Object *in)
3204 YFREE(in->variant.symLinkVariant.alias);
3206 return yaffs_DoGenericObjectDeletion(in);
3209 static int yaffs_DeleteHardLink(yaffs_Object *in)
3211 // remove this hardlink from the list assocaited with the equivalent
3213 list_del(&in->hardLinks);
3214 return yaffs_DoGenericObjectDeletion(in);
3218 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3222 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3224 return yaffs_DeleteHardLink(obj);
3226 else if(!list_empty(&obj->hardLinks))
3229 // Curve ball: We're unlinking an object that has a hardlink.
3230 // Therefore we can't really delete the object.
3231 // Instead, we do the following:
3232 // - Select a hardlink.
3233 // - Re-type a hardlink as the equivalent object and populate the fields, including the
3234 // objectId. Updating the object id is important so that all the hardlinks do not need
3236 // - Update the equivalet object pointers.
3237 // - Delete all object.
3240 struct list_head *i;
3243 yaffs_RemoveObjectFromDirectory(obj);
3247 hl = list_entry(obj->hardLinks.next, yaffs_Object,hardLinks);
3250 hl->st_mode = obj->st_mode;
3251 hl->st_uid = obj->st_uid;
3252 hl->st_gid = obj->st_gid;
3253 hl->st_atime = obj->st_atime;
3254 hl->st_mtime = obj->st_mtime;
3255 hl->st_ctime = obj->st_ctime;
3256 hl->st_rdev = obj->st_rdev;
3258 hl->variantType = obj->variantType;
3260 switch(hl->variantType)
3262 case YAFFS_OBJECT_TYPE_FILE:
3263 case YAFFS_OBJECT_TYPE_SYMLINK:
3264 case YAFFS_OBJECT_TYPE_SPECIAL:
3265 // These types are OK to just copy across.
3266 hl->variant = obj->variant;
3268 case YAFFS_OBJECT_TYPE_DIRECTORY:
3270 list_add(&hl->variant.directoryVariant.children,
3271 &obj->variant.directoryVariant.children);
3272 list_del(&obj->variant.directoryVariant.children);
3274 // Now change all the directory children to point to the new parent.
3275 list_for_each(i,&hl->variant.directoryVariant.children)
3277 list_entry(i,yaffs_Object,siblings)->parent = hl;
3281 case YAFFS_OBJECT_TYPE_HARDLINK:
3282 case YAFFS_OBJECT_TYPE_UNKNOWN:
3283 // Should not be either of these types.
3286 // Now fix up the hardlink chain
3287 list_del(&obj->hardLinks);
3289 list_for_each(i,&hl->hardLinks)
3291 list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObject = hl;
3292 list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObjectId = hl->objectId;
3295 // Now fix up the hash links.
3296 yaffs_UnhashObject(hl);
3297 hl->objectId = obj->objectId;
3298 yaffs_HashObject(hl);
3300 // Update the hardlink which has become an object
3301 yaffs_UpdateObjectHeader(hl,NULL,0);
3303 // Finally throw away the deleted object
3304 yaffs_DeleteChunk(obj->myDev,obj->chunkId);
3305 yaffs_FreeObject(obj);
3309 // Curve ball: We're unlinking an object that has a hardlink.
3311 // This problem arises because we are not strictly following
3312 // The Linux link/inode model.
3314 // We can't really delete the object.
3315 // Instead, we do the following:
3316 // - Select a hardlink.
3317 // - Unhook it from the hard links
3318 // - Unhook it from its parent directory (so that the rename can work)
3319 // - Rename the object to the hardlink's name.
3320 // - Delete the hardlink
3325 char name[YAFFS_MAX_NAME_LENGTH+1];
3327 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3329 list_del_init(&hl->hardLinks);
3330 list_del_init(&hl->siblings);
3332 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3334 retVal = yaffs_ChangeObjectName(obj, hl->parent, name);
3336 if(retVal == YAFFS_OK)
3338 retVal = yaffs_DoGenericObjectDeletion(hl);
3348 switch(obj->variantType)
3350 case YAFFS_OBJECT_TYPE_FILE:
3351 return yaffs_UnlinkFile(obj);
3353 case YAFFS_OBJECT_TYPE_DIRECTORY:
3354 return yaffs_DeleteDirectory(obj);
3356 case YAFFS_OBJECT_TYPE_SYMLINK:
3357 return yaffs_DeleteSymLink(obj);
3359 case YAFFS_OBJECT_TYPE_HARDLINK:
3360 case YAFFS_OBJECT_TYPE_UNKNOWN:
3367 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3371 obj = yaffs_FindObjectByName(dir,name);
3373 if(obj && obj->unlinkAllowed)
3375 return yaffs_UnlinkWorker(obj);
3382 //////////////// Initialisation Scanning /////////////////
3386 // For now we use the SmartMedia check.
3387 // We look at the blockStatus byte in the first two chunks
3388 // These must be 0xFF to pass as OK.
3389 // todo: this function needs to be modifyable foir different NAND types
3390 // and different chunk sizes. Suggest make this into a per-device configurable
3392 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3396 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK,NULL,&spare,1);
3398 if(yaffs_CountBits(spare.blockStatus) < 7)
3403 if(spare.blockStatus != 0xFF)
3408 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK + 1,NULL,&spare,1);
3411 if(yaffs_CountBits(spare.blockStatus) < 7)
3416 if(spare.blockStatus != 0xFF)
3426 static int yaffs_Scan(yaffs_Device *dev)
3434 yaffs_BlockState state;
3435 yaffs_Object *hardList = NULL;
3437 yaffs_BlockInfo *bi;
3440 yaffs_ObjectHeader *oh;
3442 yaffs_Object *parent;
3444 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
3447 // Scan all the blocks...
3449 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
3452 bi = yaffs_GetBlockInfo(dev,blk);
3455 state = YAFFS_BLOCK_STATE_SCANNING;
3458 if(yaffs_IsBlockBad(dev,blk))
3460 state = YAFFS_BLOCK_STATE_DEAD;
3461 T((TSTR("block %d is bad" TENDSTR),blk));
3464 // Read each chunk in the block.
3466 for(c = 0; c < YAFFS_CHUNKS_PER_BLOCK &&
3467 state == YAFFS_BLOCK_STATE_SCANNING; c++)
3469 // Read the spare area and decide what to do
3470 chunk = blk * YAFFS_CHUNKS_PER_BLOCK + c;
3472 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
3475 // This block looks ok, now what's in this chunk?
3476 yaffs_GetTagsFromSpare(dev,&spare,&tags);
3478 if(yaffs_CountBits(spare.pageStatus) < 6)
3482 dev->nFreeChunks ++;
3483 //T((" %d %d deleted\n",blk,c));
3485 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
3487 // An unassigned chunk in the block
3488 // This means that either the block is empty or
3489 // this is the one being allocated from
3493 // the block is unused
3494 state = YAFFS_BLOCK_STATE_EMPTY;
3495 dev->nErasedBlocks++;
3499 // this is the block being allocated from
3500 T((TSTR(" Allocating from %d %d" TENDSTR),blk,c));
3501 state = YAFFS_BLOCK_STATE_ALLOCATING;
3502 dev->allocationBlock = blk;
3503 dev->allocationPage = c;
3506 dev->nFreeChunks += (YAFFS_CHUNKS_PER_BLOCK - c);
3508 else if(tags.chunkId > 0)
3512 bi->pageBits |= (1 << c);
3515 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
3516 // PutChunkIntoFIle checks for a clash (two data chunks with
3517 // the same chunkId).
3518 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
3519 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
3520 if(in->variant.fileVariant.scannedFileSize <endpos)
3522 in->variant.fileVariant.scannedFileSize = endpos;
3523 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3524 in->variant.fileVariant.fileSize =
3525 in->variant.fileVariant.scannedFileSize;
3529 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
3533 // chunkId == 0, so it is an ObjectHeader.
3534 // Thus, we read in the object header and make the object
3535 bi->pageBits |= (1 << c);
3538 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
3540 oh = (yaffs_ObjectHeader *)chunkData;
3542 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
3546 // We have already filled this one. We have a duplicate and need to resolve it.
3548 unsigned existingSerial = in->serial;
3549 unsigned newSerial = tags.serialNumber;
3551 if(((existingSerial+1) & 3) == newSerial)
3553 // Use new one - destroy the exisiting one
3554 yaffs_DeleteChunk(dev,in->chunkId);
3559 // Use existing - destroy this one.
3560 yaffs_DeleteChunk(dev,chunk);
3565 (tags.objectId == YAFFS_OBJECTID_ROOT ||
3566 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
3568 // We only load some info, don't fiddle with directory structure
3570 in->variantType = oh->type;
3572 in->st_mode = oh->st_mode;
3573 in->st_uid = oh->st_uid;
3574 in->st_gid = oh->st_gid;
3575 in->st_atime = oh->st_atime;
3576 in->st_mtime = oh->st_mtime;
3577 in->st_ctime = oh->st_ctime;
3578 in->st_rdev = oh->st_rdev;
3579 in->chunkId = chunk;
3584 // we need to load this info
3587 in->variantType = oh->type;
3589 in->st_mode = oh->st_mode;
3590 in->st_uid = oh->st_uid;
3591 in->st_gid = oh->st_gid;
3592 in->st_atime = oh->st_atime;
3593 in->st_mtime = oh->st_mtime;
3594 in->st_ctime = oh->st_ctime;
3595 in->st_rdev = oh->st_rdev;
3596 in->chunkId = chunk;
3601 // directory stuff...
3602 // hook up to parent
3604 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
3605 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
3607 // Set up as a directory
3608 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
3609 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
3611 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
3613 // Hoosterman, another problem....
3614 // We're trying to use a non-directory as a directory
3618 yaffs_AddObjectToDirectory(parent,in);
3619 if(parent == dev->unlinkedDir)
3621 in->deleted = 1; // If it is unlinked at start up then it wants deleting
3622 dev->nDeletedFiles++;
3625 // Note re hardlinks.
3626 // Since we might scan a hardlink before its equivalent object is scanned
3627 // we put them all in a list.
3628 // After scanning is complete, we should have all the objects, so we run through this
3629 // list and fix up all the chains.
3631 switch(in->variantType)
3633 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
3635 case YAFFS_OBJECT_TYPE_FILE:
3636 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3637 in->variant.fileVariant.fileSize = oh->fileSize;
3640 case YAFFS_OBJECT_TYPE_HARDLINK:
3641 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
3642 (yaffs_Object *)(in->hardLinks.next) = hardList;
3645 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
3647 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
3649 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
3650 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
3653 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
3658 if(state == YAFFS_BLOCK_STATE_SCANNING)
3660 // If we got this far while scanning, then the block is fully allocated.
3661 state = YAFFS_BLOCK_STATE_FULL;
3664 bi->blockState = state;
3666 // Now let's see if it was dirty
3667 if( bi->pagesInUse == 0 &&
3668 bi->blockState == YAFFS_BLOCK_STATE_FULL)
3670 yaffs_BlockBecameDirty(dev,blk);
3675 // Fix up the hard link chains.
3676 // We should now have scanned all the objects, now it's time to add these
3681 hardList = (yaffs_Object *)(hardList->hardLinks.next);
3683 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
3687 // Add the hardlink pointers
3688 hl->variant.hardLinkVariant.equivalentObject=in;
3689 list_add(&hl->hardLinks,&in->hardLinks);
3693 //Todo Need to report/handle this better.
3694 // Got a problem... hardlink to a non-existant object
3695 hl->variant.hardLinkVariant.equivalentObject=NULL;
3696 INIT_LIST_HEAD(&hl->hardLinks);
3708 ////////////////////////// Directory Functions /////////////////////////
3711 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
3714 if(obj->siblings.prev == NULL)
3717 INIT_LIST_HEAD(&obj->siblings);
3720 else if(!list_empty(&obj->siblings))
3722 // If it is holed up somewhere else, un hook it
3723 list_del_init(&obj->siblings);
3726 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
3727 obj->parent = directory;
3729 if(directory == obj->myDev->unlinkedDir)
3732 obj->myDev->nUnlinkedFiles++;
3733 obj->renameAllowed = 0;
3737 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
3739 list_del_init(&obj->siblings);
3743 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
3747 struct list_head *i;
3748 char buffer[YAFFS_MAX_NAME_LENGTH+1];
3752 sum = yaffs_CalcNameSum(name);
3754 list_for_each(i,&directory->variant.directoryVariant.children)
3756 l = list_entry(i, yaffs_Object,siblings);
3758 // Special case for lost-n-found
3759 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
3761 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
3766 else if(yaffs_SumCompare(l->sum, sum))
3769 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
3770 if(yaffs_strcmp(name,buffer) == 0)
3783 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
3785 struct list_head *i;
3789 list_for_each(i,&theDir->variant.directoryVariant.children)
3791 l = list_entry(i, yaffs_Object,siblings);
3803 // GetEquivalentObject dereferences any hard links to get to the
3806 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
3808 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3810 // We want the object id of the equivalent object, not this one
3811 obj = obj->variant.hardLinkVariant.equivalentObject;
3817 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
3819 memset(name,0,buffSize);
3821 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
3823 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
3825 else if(obj->chunkId <= 0)
3829 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
3830 strncpy(name,locName,buffSize - 1);
3835 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
3836 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
3838 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
3840 if(obj->chunkId >= 0)
3842 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
3844 strncpy(name,oh->name,buffSize - 1);
3847 return strlen(name);
3850 int yaffs_GetObjectFileLength(yaffs_Object *obj)
3853 // Dereference any hard linking
3854 obj = yaffs_GetEquivalentObject(obj);
3856 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3858 return obj->variant.fileVariant.fileSize;
3860 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
3862 return strlen(obj->variant.symLinkVariant.alias);
3866 // Only a directory should drop through to here
3867 return YAFFS_BYTES_PER_CHUNK;
3871 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
3874 struct list_head *i;
3878 count++; // the object itself
3880 list_for_each(i,&obj->hardLinks)
3882 count++; // add the hard links;
3889 int yaffs_GetObjectInode(yaffs_Object *obj)
3891 obj = yaffs_GetEquivalentObject(obj);
3893 return obj->objectId;
3896 unsigned yaffs_GetObjectType(yaffs_Object *obj)
3898 obj = yaffs_GetEquivalentObject(obj);
3900 switch(obj->variantType)
3902 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
3903 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
3904 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
3905 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
3906 case YAFFS_OBJECT_TYPE_SPECIAL:
3907 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
3908 if(S_ISCHR(obj->st_mode)) return DT_CHR;
3909 if(S_ISBLK(obj->st_mode)) return DT_BLK;
3910 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
3911 default: return DT_REG; break;
3915 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
3917 obj = yaffs_GetEquivalentObject(obj);
3918 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
3920 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
3924 return yaffs_CloneString("");
3929 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
3931 unsigned int valid = attr->ia_valid;
3933 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
3934 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
3935 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
3937 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
3938 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
3939 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
3941 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
3943 yaffs_UpdateObjectHeader(obj,NULL,1);
3948 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
3950 unsigned int valid = 0;
3952 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
3953 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
3954 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
3956 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
3957 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
3958 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
3960 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
3962 attr->ia_valid = valid;
3970 int yaffs_DumpObject(yaffs_Object *obj)
3972 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
3974 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
3976 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
3978 // if(obj->chunkId >= 0)
3980 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
3983 yaffs_GetObjectName(obj,name,256);
3985 YPRINTF(("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d type %d size %d\n",
3986 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
3987 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
3990 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
3991 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
3992 obj->sum, obj->chunkId));
3993 switch(obj->variantType)
3995 case YAFFS_OBJECT_TYPE_FILE:
3996 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
3998 case YAFFS_OBJECT_TYPE_DIRECTORY:
3999 YPRINTF((" DIRECTORY\n"));
4001 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4002 case YAFFS_OBJECT_TYPE_SYMLINK:
4003 case YAFFS_OBJECT_TYPE_UNKNOWN:
4012 ///////////////////////// Initialisation code ///////////////////////////
4016 int yaffs_GutsInitialise(yaffs_Device *dev)
4025 if(!yaffs_CheckStructures())
4027 YPRINTF(("yaffs_CheckStructures failed\n"));
4031 if(dev->startBlock <= 0 ||
4032 (dev->endBlock - dev->startBlock) < 10)
4034 YPRINTF(("startBlock %d or endBlock %d invalid\n",
4035 dev->startBlock, dev->endBlock));
4039 nBlocks = dev->endBlock - dev->startBlock + 1;
4043 // OK now calculate a few things for the device
4044 // Calculate chunkGroupBits.
4045 // We need to find the next power of 2 > than endBlock
4047 x = YAFFS_CHUNKS_PER_BLOCK * (dev->endBlock+1);
4049 for(bits = extraBits = 0; x > 1; bits++)
4051 if(x & 1) extraBits++;
4055 if(extraBits > 0) bits++;
4058 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4059 // chunk range we're using is greater than 16 we need
4060 // to figure out chunk shift and chunkGroupSize
4063 dev->chunkGroupBits = 0;
4067 dev->chunkGroupBits = bits - 16;
4069 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4072 // More device initialisation
4073 dev->garbageCollectionRequired = 0;
4074 dev->garbageCollections = 0;
4075 dev->currentDirtyChecker = 0;
4076 dev->bufferedBlock = -1;
4077 dev->doingBufferedBlockRewrite = 0;
4078 dev->blockSelectedForGC = -1;
4079 dev->nDeletedFiles = 0;
4080 dev->nBackgroundDeletions=0;
4081 dev->nUnlinkedFiles = 0;
4084 dev->tagsEccFixed=0;
4085 dev->tagsEccUnfixed=0;
4087 yaffs_InitialiseBlocks(dev,nBlocks);
4089 yaffs_InitialiseTnodes(dev);
4091 yaffs_InitialiseObjects(dev);
4093 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
4096 for(i=0; i < YAFFS_N_CACHE_CHUNKS; i++)
4098 dev->srCache[i].objectId = 0;
4099 dev->srCache[i].lastUse = 0;
4108 // Initialise the unlinked, root and lost and found directories
4109 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4111 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4113 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4114 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4115 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4118 // Now scan the flash.
4122 dev->nPageReads = 0;
4123 dev->nPageWrites = 0;
4124 dev->nBlockErasures = 0;
4126 dev->nRetriedWrites = 0;
4127 dev->nRetiredBlocks = 0;
4134 void yaffs_Deinitialise(yaffs_Device *dev)
4136 yaffs_DeinitialiseBlocks(dev);
4137 yaffs_DeinitialiseTnodes(dev);
4138 yaffs_DeinitialiseObjects(dev);
4142 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4144 int nFree = dev->nFreeChunks - (YAFFS_CHUNKS_PER_BLOCK * YAFFS_RESERVED_BLOCKS);
4146 struct list_head *i;
4150 // To the free chunks add the chunks that are in the deleted unlinked files.
4151 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4153 l = list_entry(i, yaffs_Object,siblings);
4157 nFree += l->nDataChunks;
4162 return (nFree < 0) ? 0 : nFree;
4167 /////////////////// YAFFS test code //////////////////////////////////
4169 #define yaffs_CheckStruct(structure,syze, name) \
4170 if(sizeof(structure) != syze) \
4171 { YPRINTF(("%s should be %d but is %d\n",name,syze,sizeof(structure))); \
4172 return YAFFS_FAIL; \
4176 static int yaffs_CheckStructures(void)
4178 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4179 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4180 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4181 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4182 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4188 void yaffs_GutsTest(yaffs_Device *dev)
4191 if(yaffs_CheckStructures() != YAFFS_OK)
4193 YPRINTF(("One or more structures malformed-- aborting\n"));
4198 YPRINTF(("Structures OK\n"));
4201 yaffs_TnodeTest(dev);
4202 yaffs_ObjectTest(dev);