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.11 2002-10-02 02:11:25 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 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
113 static void yaffs_InvalidateChunkCache(yaffs_Device *dev, int objectId, int chunkId);
116 static __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
118 if(blk < dev->startBlock || blk > dev->endBlock)
122 return &dev->blockInfo[blk - dev->startBlock];
126 static __inline__ int yaffs_HashFunction(int n)
128 return (n % YAFFS_NOBJECT_BUCKETS);
132 yaffs_Object *yaffs_Root(yaffs_Device *dev)
137 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
139 return dev->lostNFoundDir;
143 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
146 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
150 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, __u8 *data, yaffs_Spare *spare,int doErrorCorrection)
154 yaffs_Spare localSpare;
155 int eccResult1,eccResult2;
161 // If we don't have a real spare, then we use a local one.
162 // Need this for the calculation of the ecc
166 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
167 if(data && doErrorCorrection)
170 //Todo handle any errors
171 nand_calculate_ecc(data,calcEcc);
172 eccResult1 = nand_correct_data (data,spare->ecc1, calcEcc);
173 nand_calculate_ecc(&data[256],calcEcc);
174 eccResult2 = nand_correct_data (&data[256],spare->ecc2, calcEcc);
178 T((TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
181 else if(eccResult1<0)
183 T((TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
189 T((TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
192 else if(eccResult2<0)
194 T((TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
198 if(eccResult1 || eccResult2)
200 // Hoosterman, we had a data problem on this page
201 yaffs_HandleReadDataError(dev,chunkInNAND);
208 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
212 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
213 static __u8 data[YAFFS_BYTES_PER_CHUNK];
214 static __u8 spare[16];
217 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
223 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
227 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL;
228 if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
237 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
239 dev->nBlockErasures++;
240 return dev->eraseBlockInNAND(dev,blockInNAND);
243 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
245 return dev->initialiseNAND(dev);
248 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
255 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
259 chunk = yaffs_AllocateChunk(dev,useReserve);
264 // First check this chunk is erased...
265 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
266 writeOk = yaffs_CheckChunkErased(dev,chunk);
270 T((TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
274 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
280 // If verify fails, then delete this chunk and try again
281 // To verify we compare everything except the block and
282 // page status bytes.
283 // NB We check a raw read without ECC correction applied
284 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
286 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
287 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
290 T((TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
299 // Copy the data into the write buffer.
300 // NB We do this at the end to prevent duplicates in the case of a write error.
302 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
306 yaffs_HandleWriteChunkError(dev,chunk);
310 } while(chunk >= 0 && ! writeOk);
314 T((TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
315 dev->nRetriedWrites+= (attempts - 1);
322 // Functions for robustisizing
326 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
328 // Ding the blockStatus in the first two pages of the block.
332 memset(&spare, 0xff,sizeof(yaffs_Spare));
334 spare.blockStatus = 0;
336 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK, NULL , &spare);
337 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK + 1, NULL , &spare);
339 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
340 dev->nRetiredBlocks++;
345 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
347 dev->doingBufferedBlockRewrite = 1;
349 // Remove erased chunks
350 // Rewrite existing chunks to a new block
351 // Set current write block to the new block
353 dev->doingBufferedBlockRewrite = 0;
359 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
361 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
363 // Mark the block for retirement
364 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
365 T((TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
369 // Just do a garbage collection on the affected block then retire the block
374 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
378 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare)
382 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare)
386 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
388 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
390 // Mark the block for retirement
391 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
393 yaffs_DeleteChunk(dev,chunkInNAND);
399 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1)
403 if( memcmp(d0,d1,YAFFS_BYTES_PER_CHUNK) != 0 ||
404 s0->tagByte0 != s1->tagByte0 ||
405 s0->tagByte1 != s1->tagByte1 ||
406 s0->tagByte2 != s1->tagByte2 ||
407 s0->tagByte3 != s1->tagByte3 ||
408 s0->tagByte4 != s1->tagByte4 ||
409 s0->tagByte5 != s1->tagByte5 ||
410 s0->tagByte6 != s1->tagByte6 ||
411 s0->tagByte7 != s1->tagByte7 ||
412 s0->ecc1[0] != s1->ecc1[0] ||
413 s0->ecc1[1] != s1->ecc1[1] ||
414 s0->ecc1[2] != s1->ecc1[2] ||
415 s0->ecc2[0] != s1->ecc2[0] ||
416 s0->ecc2[1] != s1->ecc2[1] ||
417 s0->ecc2[2] != s1->ecc2[2] )
426 ///////////////////////// Object management //////////////////
427 // List of spare objects
428 // The list is hooked together using the first pointer
431 // static yaffs_Object *yaffs_freeObjects = NULL;
433 // static int yaffs_nFreeObjects;
435 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
437 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
440 static __u16 yaffs_CalcNameSum(const char *name)
445 __u8 *bname = (__u8 *)name;
459 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
461 nand_calculate_ecc (data , spare->ecc1);
462 nand_calculate_ecc (&data[256] , spare->ecc2);
465 void yaffs_CalcTagsECC(yaffs_Tags *tags)
469 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
476 for(i = 0; i < 8; i++)
478 for(j = 1; j &0xff; j<<=1)
493 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
495 unsigned ecc = tags->ecc;
497 yaffs_CalcTagsECC(tags);
503 // TODO: Handle the failure better. Retire?
504 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
508 b[ecc / 8] ^= (1 << (ecc & 7));
510 // Now recvalc the ecc
511 yaffs_CalcTagsECC(tags);
513 return 1; // recovered error
517 // Wierd ecc failure value
518 // TODO Need to do somethiong here
519 return -1; //unrecovered error
526 ///////////////////////// TNODES ///////////////////////
528 // List of spare tnodes
529 // The list is hooked together using the first pointer
532 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
534 // static int yaffs_nFreeTnodes;
536 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
540 // yaffs_CreateTnodes creates a bunch more tnodes and
541 // adds them to the tnode free list.
542 // Don't use this function directly
544 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
547 yaffs_Tnode *newTnodes;
548 yaffs_TnodeList *tnl;
550 if(nTnodes < 1) return YAFFS_OK;
554 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
558 YALERT("Could not malloc tnodes");
562 // Hook them into the free list
563 for(i = 0; i < nTnodes - 1; i++)
565 newTnodes[i].internal[0] = &newTnodes[i+1];
568 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
569 dev->freeTnodes = newTnodes;
570 dev->nFreeTnodes+= nTnodes;
571 dev->nTnodesCreated += nTnodes;
573 // Now add this bunch of tnodes to a list for freeing up.
575 tnl = YMALLOC(sizeof(yaffs_TnodeList));
578 YALERT("Could not add tnodes to management list");
582 tnl->tnodes = newTnodes;
583 tnl->next = dev->allocatedTnodeList;
584 dev->allocatedTnodeList = tnl;
588 YINFO("Tnodes created");
595 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
596 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
598 yaffs_Tnode *tn = NULL;
600 // If there are none left make more
603 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
608 tn = dev->freeTnodes;
609 dev->freeTnodes = dev->freeTnodes->internal[0];
612 memset(tn,0,sizeof(yaffs_Tnode));
620 // FreeTnode frees up a tnode and puts it back on the free list
621 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
623 tn->internal[0] = dev->freeTnodes;
624 dev->freeTnodes = tn;
629 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
631 // Free the list of allocated tnodes
633 while(dev->allocatedTnodeList)
635 YFREE(dev->allocatedTnodeList->tnodes);
636 dev->allocatedTnodeList = dev->allocatedTnodeList->next;
639 dev->freeTnodes = NULL;
640 dev->nFreeTnodes = 0;
643 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
645 dev->allocatedTnodeList = NULL;
646 dev->freeTnodes = NULL;
647 dev->nFreeTnodes = 0;
648 dev->nTnodesCreated = 0;
652 void yaffs_TnodeTest(yaffs_Device *dev)
657 yaffs_Tnode *tn[1000];
659 YINFO("Testing TNodes");
661 for(j = 0; j < 50; j++)
663 for(i = 0; i < 1000; i++)
665 tn[i] = yaffs_GetTnode(dev);
668 YALERT("Getting tnode failed");
671 for(i = 0; i < 1000; i+=3)
673 yaffs_FreeTnode(dev,tn[i]);
680 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
682 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
683 // The look up tree is represented by the top tnode and the number of topLevel
684 // in the tree. 0 means only the level 0 tnode is in the tree.
687 // FindLevel0Tnode finds the level 0 tnode, if one exists.
688 // Used when reading.....
689 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
692 yaffs_Tnode *tn = fStruct->top;
694 int requiredTallness;
695 int level = fStruct->topLevel;
697 // Check sane level and chunk Id
698 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
701 sprintf(str,"Bad level %d",level);
706 if(chunkId > YAFFS_MAX_CHUNK_ID)
709 sprintf(str,"Bad chunkId %d",chunkId);
714 // First check we're tall enough (ie enough topLevel)
716 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
717 requiredTallness = 0;
720 i >>= YAFFS_TNODES_INTERNAL_BITS;
725 if(requiredTallness > fStruct->topLevel)
727 // Not tall enough, so we can't find it, return NULL.
732 // Traverse down to level 0
733 while (level > 0 && tn)
735 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
736 YAFFS_TNODES_INTERNAL_MASK];
744 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
745 // This happens in two steps:
746 // 1. If the tree isn't tall enough, then make it taller.
747 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
749 // Used when modifying the tree.
751 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
756 int requiredTallness;
762 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
764 // Check sane level and page Id
765 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
768 sprintf(str,"Bad level %d",fStruct->topLevel);
773 if(chunkId > YAFFS_MAX_CHUNK_ID)
776 sprintf(str,"Bad chunkId %d",chunkId);
781 // First check we're tall enough (ie enough topLevel)
783 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
784 requiredTallness = 0;
787 i >>= YAFFS_TNODES_INTERNAL_BITS;
791 //T((TSTR(" required=%d"),requiredTallness));
794 if(requiredTallness > fStruct->topLevel)
796 // Not tall enough,gotta make the tree taller
797 for(i = fStruct->topLevel; i < requiredTallness; i++)
799 //T((TSTR(" add new top")));
801 tn = yaffs_GetTnode(dev);
805 tn->internal[0] = fStruct->top;
810 YALERT("No more tnodes");
814 fStruct->topLevel = requiredTallness;
818 // Traverse down to level 0, adding anything we need
820 l = fStruct->topLevel;
824 i = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
825 YAFFS_TNODES_INTERNAL_MASK;
827 //T((TSTR(" [%d:%d]"),l,i));
831 //T((TSTR(" added")));
833 tn->internal[i] = yaffs_GetTnode(dev);
836 tn = tn->internal[i];
846 // DeleteWorker scans backwards through the tnode tree and deletes all the
847 // chunks and tnodes in the file
848 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
850 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
866 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
870 if(limit && (*limit) < 0)
876 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
877 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
881 yaffs_FreeTnode(in->myDev,tn->internal[i]);
882 tn->internal[i] = NULL;
887 return (allDone) ? 1 : 0;
891 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0; i--) //NB Don't apply the limit here, always delete a whole level0
897 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
899 theChunk = tn->level0[i] << in->myDev->chunkGroupBits;
901 // Now we need to search for it
902 for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
904 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
905 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
919 yaffs_DeleteChunk(in->myDev,theChunk);
946 // Pruning removes any part of the file structure tree that is beyond the
947 // bounds of the file (ie that does not point to chunks).
949 // A file should only get pruned when its size is reduced.
951 // Before pruning, the chunks must be pulled from the tree and the
952 // level 0 tnode entries must be zeroed out.
953 // Could also use this for file deletion, but that's probably better handled
954 // by a special case.
956 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
958 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
967 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
969 if(tn->internal[i] && level > 0)
971 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
980 if(hasData == 0 && del0)
982 // Free and return NULL
984 yaffs_FreeTnode(dev,tn);
994 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1001 if(fStruct->topLevel > 0)
1003 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1005 // Now we have a tree with all the non-zero branches NULL but the height
1006 // is the same as it was.
1007 // Let's see if we can trim internal tnodes to shorten the tree.
1008 // We can do this if only the 0th element in the tnode is in use
1009 // (ie all the non-zero are NULL)
1011 while(fStruct->topLevel && !done)
1016 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1026 fStruct->top = tn->internal[0];
1027 fStruct->topLevel--;
1028 yaffs_FreeTnode(dev,tn);
1043 /////////////////////// End of File Structure functions. /////////////////
1045 // yaffs_CreateFreeObjects creates a bunch more objects and
1046 // adds them to the object free list.
1047 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1050 yaffs_Object *newObjects;
1051 yaffs_ObjectList *list;
1053 if(nObjects < 1) return YAFFS_OK;
1055 // make these things
1057 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1061 YALERT("Could not allocate more objects");
1065 // Hook them into the free list
1066 for(i = 0; i < nObjects - 1; i++)
1068 (yaffs_Object *)newObjects[i].siblings.next = &newObjects[i+1];
1071 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1072 dev->freeObjects = newObjects;
1073 dev->nFreeObjects+= nObjects;
1074 dev->nObjectsCreated+= nObjects;
1076 // Now add this bunch of Objects to a list for freeing up.
1078 list = YMALLOC(sizeof(yaffs_ObjectList));
1081 YALERT("Could not add Objects to management list");
1085 list->objects = newObjects;
1086 list->next = dev->allocatedObjectList;
1087 dev->allocatedObjectList = list;
1091 YINFO("Objects created");
1098 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1099 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1101 yaffs_Object *tn = NULL;
1103 // If there are none left make more
1104 if(!dev->freeObjects)
1106 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1109 if(dev->freeObjects)
1111 tn = dev->freeObjects;
1112 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1113 dev->nFreeObjects--;
1115 // Now sweeten it up...
1117 memset(tn,0,sizeof(yaffs_Object));
1120 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1121 INIT_LIST_HEAD(&(tn->hardLinks));
1122 INIT_LIST_HEAD(&(tn->hashLink));
1123 INIT_LIST_HEAD(&tn->siblings);
1125 // Add it to the lost and found directory.
1126 // NB Can't put root or lostNFound in lostNFound so
1127 // check if lostNFound exists first
1128 if(dev->lostNFoundDir)
1130 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1138 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1141 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1144 obj->fake = 1; // it is fake so it has no NAND presence...
1145 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1146 obj->unlinkAllowed= 0; // ... or unlink it
1149 obj->st_mode = mode;
1151 obj->chunkId = 0; // Not a valid chunk.
1159 static void yaffs_UnhashObject(yaffs_Object *tn)
1162 yaffs_Device *dev = tn->myDev;
1165 // If it is still linked into the bucket list, free from the list
1166 if(!list_empty(&tn->hashLink))
1168 list_del_init(&tn->hashLink);
1169 bucket = yaffs_HashFunction(tn->objectId);
1170 dev->objectBucket[bucket].count--;
1176 // FreeObject frees up a Object and puts it back on the free list
1177 static void yaffs_FreeObject(yaffs_Object *tn)
1180 yaffs_Device *dev = tn->myDev;
1182 yaffs_UnhashObject(tn);
1184 // Link into the free list.
1185 (yaffs_Object *)(tn->siblings.next) = dev->freeObjects;
1186 dev->freeObjects = tn;
1187 dev->nFreeObjects++;
1193 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1195 // Free the list of allocated Objects
1197 while( dev->allocatedObjectList)
1199 YFREE(dev->allocatedObjectList->objects);
1200 dev->allocatedObjectList = dev->allocatedObjectList->next;
1203 dev->freeObjects = NULL;
1204 dev->nFreeObjects = 0;
1207 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1211 dev->allocatedObjectList = NULL;
1212 dev->freeObjects = NULL;
1213 dev->nFreeObjects = 0;
1215 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1217 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1218 dev->objectBucket[i].count = 0;
1228 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1233 int lowest = 999999;
1236 // First let's see if we can find one that's empty.
1238 for(i = 0; i < 10 && lowest > 0; i++)
1241 x %= YAFFS_NOBJECT_BUCKETS;
1242 if(dev->objectBucket[x].count < lowest)
1244 lowest = dev->objectBucket[x].count;
1250 // If we didn't find an empty list, then try
1251 // looking a bit further for a short one
1253 for(i = 0; i < 10 && lowest > 3; i++)
1256 x %= YAFFS_NOBJECT_BUCKETS;
1257 if(dev->objectBucket[x].count < lowest)
1259 lowest = dev->objectBucket[x].count;
1268 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1270 int bucket = yaffs_FindNiceObjectBucket(dev);
1272 // Now find an object value that has not already been taken
1273 // by scanning the list.
1276 struct list_head *i;
1280 //yaffs_CheckObjectHashSanity();
1285 n += YAFFS_NOBJECT_BUCKETS;
1286 if(1 ||dev->objectBucket[bucket].count > 0)
1288 list_for_each(i,&dev->objectBucket[bucket].list)
1290 // If there is already one in the list
1291 if(list_entry(i, yaffs_Object,hashLink)->objectId == n)
1299 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1304 void yaffs_HashObject(yaffs_Object *in)
1306 int bucket = yaffs_HashFunction(in->objectId);
1307 yaffs_Device *dev = in->myDev;
1309 if(!list_empty(&in->hashLink))
1315 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1316 dev->objectBucket[bucket].count++;
1320 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,int number)
1322 int bucket = yaffs_HashFunction(number);
1323 struct list_head *i;
1326 list_for_each(i,&dev->objectBucket[bucket].list)
1328 // Look if it is in the list
1329 in = list_entry(i, yaffs_Object,hashLink);
1330 if(in->objectId == number)
1341 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1344 yaffs_Object *theObject;
1348 number = yaffs_CreateNewObjectNumber(dev);
1351 theObject = yaffs_AllocateEmptyObject(dev);
1355 theObject->fake = 0;
1356 theObject->renameAllowed = 1;
1357 theObject->unlinkAllowed = 1;
1358 theObject->objectId = number;
1359 yaffs_HashObject(theObject);
1360 theObject->variantType = type;
1361 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1365 case YAFFS_OBJECT_TYPE_FILE:
1366 theObject->variant.fileVariant.fileSize = 0;
1367 theObject->variant.fileVariant.scannedFileSize = 0;
1368 theObject->variant.fileVariant.topLevel = 0;
1369 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1371 case YAFFS_OBJECT_TYPE_DIRECTORY:
1372 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1374 case YAFFS_OBJECT_TYPE_SYMLINK:
1375 // No action required
1377 case YAFFS_OBJECT_TYPE_HARDLINK:
1378 // No action required
1380 case YAFFS_OBJECT_TYPE_SPECIAL:
1381 // No action required
1383 case YAFFS_OBJECT_TYPE_UNKNOWN:
1384 // todo this should not happen
1392 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1394 yaffs_Object *theObject = NULL;
1398 theObject = yaffs_FindObjectByNumber(dev,number);
1403 theObject = yaffs_CreateNewObject(dev,number,type);
1410 char *yaffs_CloneString(const char *str)
1412 char *newStr = NULL;
1416 newStr = YMALLOC(strlen(str) + 1);
1425 // Mknod (create) a new object.
1426 // equivalentObject only has meaning for a hard link;
1427 // aliasString only has meaning for a sumlink.
1428 // rdev only has meaning for devices (a subset of special objects)
1429 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1430 yaffs_Object *parent,
1435 yaffs_Object *equivalentObject,
1436 const char *aliasString,
1441 yaffs_Device *dev = parent->myDev;
1443 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1444 if(yaffs_FindObjectByName(parent,name))
1449 in = yaffs_CreateNewObject(dev,-1,type);
1455 in->variantType = type;
1461 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1463 in->nDataChunks = 0;
1465 in->sum = yaffs_CalcNameSum(name);
1468 yaffs_AddObjectToDirectory(parent,in);
1470 in->myDev = parent->myDev;
1475 case YAFFS_OBJECT_TYPE_SYMLINK:
1476 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1478 case YAFFS_OBJECT_TYPE_HARDLINK:
1479 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1480 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1481 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1483 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1484 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1485 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1486 case YAFFS_OBJECT_TYPE_UNKNOWN:
1490 if(yaffs_GetNumberOfFreeChunks(dev) <= 0 ||
1491 yaffs_UpdateObjectHeader(in,name,0) < 0)
1493 // Could not create the object header, fail the creation
1494 yaffs_UnlinkWorker(in);
1503 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1505 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1508 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1510 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1513 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1515 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1518 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1520 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1523 // NB yaffs_Link returns the object id of the equivalent object.
1524 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1526 // Get the real object in case we were fed a hard link as an equivalent object
1527 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1529 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1531 return equivalentObject;
1541 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1547 newDir = obj->parent; // use the old directory
1550 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1552 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1553 // duplicate names are allowed.
1554 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1557 !yaffs_FindObjectByName(newDir,newName)) &&
1558 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1560 obj->sum = yaffs_CalcNameSum(newName);
1563 yaffs_AddObjectToDirectory(newDir,obj);
1565 if(unlinkOp) obj->unlinked = 1;
1568 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1577 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1583 // Special case for WinCE.
1584 // While look-up is case insensitive, the name isn't.
1585 // THerefore we might want to change x.txt to X.txt
1586 if(oldDir == newDir && stricmp(oldName,newName) == 0)
1592 obj = yaffs_FindObjectByName(oldDir,oldName);
1593 if(obj && obj->renameAllowed)
1595 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1602 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1604 // Scan the buckets and check that the lists
1605 // have as many members as the count says there are
1608 struct list_head *j;
1611 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1615 list_for_each(j,&dev->objectBucket[bucket].list)
1620 if(countEm != dev->objectBucket[bucket].count)
1622 YALERT("Inode hash inconsistency");
1630 void yaffs_ObjectTest(yaffs_Device *dev)
1632 yaffs_Object *in[1000];
1634 yaffs_Object *inold[1000];
1638 memset(in,0,1000*sizeof(yaffs_Object *));
1639 memset(inold,0,1000*sizeof(yaffs_Object *));
1641 yaffs_CheckObjectHashSanity(dev);
1643 for(j = 0; j < 10; j++)
1647 for(i = 0; i < 1000; i++)
1649 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1652 YINFO("No more inodes");
1656 inNo[i] = in[i]->objectId;
1660 for(i = 0; i < 1000; i++)
1662 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1664 //T(("Differnce in look up test\n"));
1668 // T(("Look up ok\n"));
1672 yaffs_CheckObjectHashSanity(dev);
1674 for(i = 0; i < 1000; i+=3)
1676 yaffs_FreeObject(in[i]);
1681 yaffs_CheckObjectHashSanity(dev);
1688 /////////////////////////// Block Management and Page Allocation ///////////////////
1691 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1693 dev->allocationBlock = -1; // force it to get a new one
1694 //Todo we're assuming the malloc will pass.
1695 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1698 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1705 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1707 YFREE(dev->blockInfo);
1710 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1711 // for garbage collection.
1713 static int yaffs_FindDirtiestBlock(yaffs_Device *dev)
1716 int b = dev->currentDirtyChecker;
1720 int pagesInUse = 100; // silly big number
1721 yaffs_BlockInfo *bi;
1723 for(i = dev->startBlock; i <= dev->endBlock && pagesInUse > 2 ; i++)
1726 if (b > dev->endBlock)
1728 b = dev->startBlock;
1731 bi = yaffs_GetBlockInfo(dev,b);
1733 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1734 bi->pagesInUse < pagesInUse)
1737 pagesInUse = bi->pagesInUse;
1741 dev->currentDirtyChecker = b;
1747 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
1749 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
1753 // If the block is still healthy erase it and mark as clean.
1754 // If the block has had a data failure, then retire it.
1755 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1757 if(!bi->needsRetiring)
1759 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
1762 T((TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
1768 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1769 dev->nErasedBlocks++;
1773 T((TSTR("Erased block %d" TENDSTR),blockNo));
1777 yaffs_RetireBlock(dev,blockNo);
1778 T((TSTR("**>> Block %d retired" TENDSTR),blockNo));
1783 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
1786 yaffs_BlockInfo *bi;
1788 if(dev->nErasedBlocks < 1)
1790 // Hoosterman we've got a problem.
1791 // Can't get space to gc
1795 // Find an empty block.
1797 for(i = dev->startBlock; i <= dev->endBlock; i++)
1799 bi = yaffs_GetBlockInfo(dev,i);
1800 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
1802 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1803 dev->nErasedBlocks--;
1813 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
1816 yaffs_BlockInfo *bi;
1818 if(dev->allocationBlock < 0)
1820 // Get next block to allocate off
1821 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
1822 dev->allocationPage = 0;
1825 if(!useReserve && dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
1827 // Not enough space to allocate unless we're allowed to use the reserve.
1831 // Next page please....
1832 if(dev->allocationBlock >= 0)
1834 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
1836 retVal = (dev->allocationBlock * YAFFS_CHUNKS_PER_BLOCK) +
1837 dev->allocationPage;
1839 bi->pageBits |= (1 << (dev->allocationPage));
1841 dev->allocationPage++;
1845 // If the block is full set the state to full
1846 if(dev->allocationPage >= YAFFS_CHUNKS_PER_BLOCK)
1848 bi->blockState = YAFFS_BLOCK_STATE_FULL;
1849 dev->allocationBlock = -1;
1856 T((TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
1862 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
1871 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
1873 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
1875 yaffs_Object *object;
1877 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
1879 for(mask = 1,oldChunk = block * YAFFS_CHUNKS_PER_BLOCK;
1880 mask && bi->pageBits;
1881 mask <<= 1, oldChunk++ )
1883 if(bi->pageBits & mask)
1886 // This page is in use and needs to be copied off
1890 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
1892 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
1894 yaffs_GetTagsFromSpare(dev,&spare,&tags);
1896 tags.serialNumber++;
1897 yaffs_LoadTagsIntoSpare(&spare,&tags);
1900 newChunk = yaffs_AllocatePage(dev,1);
1906 yaffs_WriteChunkToNAND(dev,newChunk, buffer, &spare);
1909 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
1916 object = yaffs_FindObjectByNumber(dev,tags.objectId);
1918 // Ok, now fix up the Tnodes etc.
1920 if(tags.chunkId == 0)
1923 object->chunkId = newChunk;
1927 // It's a data chunk
1928 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
1932 yaffs_DeleteChunk(dev,oldChunk);
1941 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
1943 // todo find a file to delete
1944 struct list_head *i;
1948 // To the free chunks add the chunks that are in the deleted unlinked files.
1949 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
1951 l = list_entry(i, yaffs_Object,siblings);
1960 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
1962 // This does background deletion on unlinked files.. only deleted ones.
1963 // If we don't have a file we're working on then find one
1964 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
1966 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
1969 // OK, we're working on a file...
1970 if(dev->unlinkedDeletion)
1972 yaffs_Object *obj = dev->unlinkedDeletion;
1974 int limit; // Number of chunks to delete in a file.
1975 // NB this can be exceeded, but not by much.
1977 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + YAFFS_GARBAGE_COLLECT_LOW_WATER))
1979 limit = 50; // Doing GC soon, so dig deeper
1986 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
1988 if(obj->nDataChunks == 0)
1990 // Done all the deleting of data chunks.
1991 // Now dump the header and clean up
1992 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
1993 yaffs_DoGenericObjectDeletion(obj);
1994 dev->nDeletedFiles--;
1995 dev->nUnlinkedFiles--;
1996 dev->nBackgroundDeletions++;
1997 dev->unlinkedDeletion = NULL;
2002 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2006 yaffs_DoUnlinkedFileDeletion(dev);
2008 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2010 dev->garbageCollectionRequired = 1;
2013 if(dev->garbageCollectionRequired)
2015 dev->garbageCollections++;
2016 dev->garbageCollectionRequired = 0;
2017 if(dev->blockSelectedForGC >= 0)
2019 block = dev->blockSelectedForGC;
2023 block = yaffs_FindDirtiestBlock(dev);
2028 return yaffs_GarbageCollectBlock(dev,block);
2040 //////////////////////////// TAGS ///////////////////////////////////////
2042 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2044 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2046 yaffs_CalcTagsECC(tagsPtr);
2048 sparePtr->tagByte0 = tu->asBytes[0];
2049 sparePtr->tagByte1 = tu->asBytes[1];
2050 sparePtr->tagByte2 = tu->asBytes[2];
2051 sparePtr->tagByte3 = tu->asBytes[3];
2052 sparePtr->tagByte4 = tu->asBytes[4];
2053 sparePtr->tagByte5 = tu->asBytes[5];
2054 sparePtr->tagByte6 = tu->asBytes[6];
2055 sparePtr->tagByte7 = tu->asBytes[7];
2058 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2060 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2063 tu->asBytes[0]= sparePtr->tagByte0;
2064 tu->asBytes[1]= sparePtr->tagByte1;
2065 tu->asBytes[2]= sparePtr->tagByte2;
2066 tu->asBytes[3]= sparePtr->tagByte3;
2067 tu->asBytes[4]= sparePtr->tagByte4;
2068 tu->asBytes[5]= sparePtr->tagByte5;
2069 tu->asBytes[6]= sparePtr->tagByte6;
2070 tu->asBytes[7]= sparePtr->tagByte7;
2072 result = yaffs_CheckECCOnTags(tagsPtr);
2075 dev->tagsEccFixed++;
2079 dev->tagsEccUnfixed++;
2083 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2085 memset(spare,0xFF,sizeof(yaffs_Spare));
2088 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2093 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2095 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2096 yaffs_GetTagsFromSpare(dev,&spare,tags);
2109 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2111 // NB There must be tags, data is optional
2112 // If there is data, then an ECC is calculated on it.
2121 yaffs_SpareInitialise(&spare);
2126 yaffs_CalcECC(buffer,&spare);
2129 yaffs_LoadTagsIntoSpare(&spare,tags);
2131 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2137 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2139 // NB There must be tags, data is optional
2140 // If there is data, then an ECC is calculated on it.
2149 yaffs_SpareInitialise(&spare);
2154 yaffs_CalcECC(buffer,&spare);
2157 yaffs_LoadTagsIntoSpare(&spare,tags);
2159 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2163 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2165 return ( tags->chunkId == chunkInObject &&
2166 tags->objectId == objectId &&
2167 !chunkDeleted) ? 1 : 0;
2173 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2175 //Get the Tnode, then get the level 0 offset chunk offset
2178 yaffs_Tags localTags;
2183 yaffs_Device *dev = in->myDev;
2188 // Passed a NULL, so use our own tags space
2192 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2196 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2198 // Now we need to do the shifting etc and search for it
2199 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2201 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2202 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2213 return found ? theChunk : -1;
2216 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2218 //Get the Tnode, then get the level 0 offset chunk offset
2221 yaffs_Tags localTags;
2224 yaffs_Device *dev = in->myDev;
2229 // Passed a NULL, so use our own tags space
2233 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2238 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2240 // Now we need to do the shifting etc and search for it
2241 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2243 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2244 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2255 // Delete the entry in the filestructure
2258 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2263 //T(("No level 0 found for %d\n", chunkInInode));
2268 //T(("Could not find %d to delete\n",chunkInInode));
2270 return found ? theChunk : -1;
2276 static int yaffs_CheckFileSanity(yaffs_Object *in)
2284 yaffs_Tags localTags;
2285 yaffs_Tags *tags = &localTags;
2290 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2292 //T(("Object not a file\n"));
2296 objId = in->objectId;
2297 fSize = in->variant.fileVariant.fileSize;
2298 nChunks = (fSize + YAFFS_BYTES_PER_CHUNK -1)/YAFFS_BYTES_PER_CHUNK;
2300 for(chunk = 1; chunk <= nChunks; chunk++)
2302 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2307 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2310 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2311 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2318 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2319 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2328 //T(("No level 0 found for %d\n", chunk));
2332 return failed ? YAFFS_FAIL : YAFFS_OK;
2337 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2340 yaffs_Device *dev = in->myDev;
2342 yaffs_Tags existingTags;
2344 unsigned existingSerial, newSerial;
2346 int newChunkDeleted;
2349 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2355 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2359 // If we're scanning then we need to test for duplicates
2360 // NB This does not need to be efficient since it should only ever
2361 // happen when the power fails during a write, then only one
2362 // chunk should ever be affected.
2365 if(existingChunk != 0)
2367 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2368 // thus we have to do a FindChunkInFile to get the real chunk id.
2370 // We have a duplicate now we need to decide which one to use
2371 // To do this we get both sets of tags and compare serial numbers.
2372 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2376 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2378 if(existingChunk <=0)
2380 //Hoosterman - how did this happen?
2385 // NB The deleted flags should be false, otherwise the chunks will
2386 // not be loaded during a scan
2388 newSerial = newTags.serialNumber;
2389 existingSerial = existingTags.serialNumber;
2391 if( existingChunk <= 0 ||
2392 ((existingSerial+1) & 3) == newSerial)
2395 // Delete the old one and drop through to update the tnode
2396 yaffs_DeleteChunk(dev,existingChunk);
2401 // Delete the new one and return early so that the tnode isn't changed
2402 yaffs_DeleteChunk(dev,chunkInNAND);
2409 if(existingChunk == 0)
2414 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2421 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2423 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2425 if(chunkInNAND >= 0)
2427 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2437 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId)
2442 yaffs_BlockInfo *bi;
2444 if(chunkId <= 0) return;
2446 block = chunkId / YAFFS_CHUNKS_PER_BLOCK;
2447 page = chunkId % YAFFS_CHUNKS_PER_BLOCK;
2448 yaffs_SpareInitialise(&spare);
2450 spare.pageStatus = 0; // To mark it as deleted.
2453 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2454 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2455 bi = yaffs_GetBlockInfo(dev,block);
2458 // Pull out of the management area.
2459 // If the whole block became dirty, this will kick off an erasure.
2460 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2461 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2465 bi->pageBits &= ~(1 << page);
2468 if(bi->pagesInUse == 0 &&
2469 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2471 yaffs_BlockBecameDirty(dev,block);
2477 // T(("Bad news deleting chunk %d\n",chunkId));
2485 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2487 // Find old chunk Need to do this to get serial number
2488 // Write new one and patch into tree.
2489 // Invalidate old tags.
2492 yaffs_Tags prevTags;
2497 yaffs_Device *dev = in->myDev;
2499 yaffs_CheckGarbageCollection(dev);
2501 // Get the previous chunk at this location in the file if it exists
2502 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2505 newTags.chunkId = chunkInInode;
2506 newTags.objectId = in->objectId;
2507 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2508 newTags.byteCount = nBytes;
2509 newTags.unusedStuff = 0xFFFFFFFF;
2511 yaffs_CalcTagsECC(&newTags);
2515 // Create new chunk in NAND
2516 newChunkId = yaffs_AllocatePage(dev,useReserve);
2523 yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,buffer,&newTags);
2525 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId);
2528 if(prevChunkId >= 0)
2530 yaffs_DeleteChunk(dev,prevChunkId);
2534 yaffs_CheckFileSanity(in);
2543 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2546 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2549 if(prevChunkId >= 0)
2551 yaffs_DeleteChunk(dev,prevChunkId);
2555 yaffs_CheckFileSanity(in);
2566 // UpdateObjectHeader updates the header on NAND for an object.
2567 // If name is not NULL, then that new name is used.
2569 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2572 yaffs_Device *dev = in->myDev;
2578 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2579 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2581 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2582 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2584 yaffs_InvalidateWholeChunkCache(in);
2586 if(!in->fake || force)
2589 yaffs_CheckGarbageCollection(dev);
2591 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2593 prevChunkId = in->chunkId;
2595 if(prevChunkId >= 0)
2597 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2601 oh->type = in->variantType;
2603 oh->st_mode = in->st_mode;
2604 oh->st_uid = in->st_uid;
2605 oh->st_gid = in->st_gid;
2606 oh->st_atime = in->st_atime;
2607 oh->st_mtime = in->st_mtime;
2608 oh->st_ctime = in->st_ctime;
2609 oh->st_rdev = in->st_rdev;
2613 oh->parentObjectId = in->parent->objectId;
2617 oh->parentObjectId = 0;
2623 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2624 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
2626 else if(prevChunkId)
2628 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
2632 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2635 switch(in->variantType)
2637 case YAFFS_OBJECT_TYPE_UNKNOWN:
2638 // Should not happen
2640 case YAFFS_OBJECT_TYPE_FILE:
2641 oh->fileSize = in->variant.fileVariant.fileSize;
2643 case YAFFS_OBJECT_TYPE_HARDLINK:
2644 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
2646 case YAFFS_OBJECT_TYPE_SPECIAL:
2649 case YAFFS_OBJECT_TYPE_DIRECTORY:
2652 case YAFFS_OBJECT_TYPE_SYMLINK:
2653 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
2654 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2660 newTags.chunkId = 0;
2661 newTags.objectId = in->objectId;
2662 newTags.serialNumber = in->serial;
2663 newTags.byteCount = 0xFFFFFFFF;
2664 newTags.unusedStuff = 0xFFFFFFFF;
2666 yaffs_CalcTagsECC(&newTags);
2671 // Create new chunk in NAND
2672 newChunkId = yaffs_AllocatePage(dev,1);
2677 yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,bufferNew,&newTags);
2679 in->chunkId = newChunkId;
2681 if(prevChunkId >= 0)
2683 yaffs_DeleteChunk(dev,prevChunkId);
2692 // Create new chunk in NAND
2693 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags,1);
2698 in->chunkId = newChunkId;
2700 if(prevChunkId >= 0)
2702 yaffs_DeleteChunk(dev,prevChunkId);
2716 /////////////////////// Short Read Cache ////////////////////////////////
2717 // In many siturations where there is no high level buffering a lot of
2718 // reads might be short sequential reads. eg. scanning a jpeg file.
2719 // In these cases, a shoprt read cache can provide a huge perfomance benefit
2720 // with dumb-as-a-rock code.
2721 // There are a limited number (~10) of cache chunks per device
2724 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2727 // Grab us a chunk for use.
2728 // First look for an empty one.
2729 // Then look for the least recently used one.
2730 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
2736 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2738 if(dev->srCache[i].objectId == 0)
2740 //T(("Grabbing empty %d\n",i));
2742 return &dev->srCache[i];
2747 usage = dev->srCache[i].lastUse;
2750 for(i = 1; i < YAFFS_N_CACHE_CHUNKS; i++)
2752 if(dev->srCache[i].lastUse < usage)
2754 usage = dev->srCache[i].lastUse;
2759 //T(("Grabbing non-empty %d\n",theOne));
2760 return &dev->srCache[theOne];
2765 // Find a cached chunk
2766 static yaffs_ChunkCache *yaffs_FindChunkCache(yaffs_Device *dev, int objectId, int chunkId)
2771 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2773 if(dev->srCache[i].objectId == objectId &&
2774 dev->srCache[i].chunkId == chunkId)
2778 return &dev->srCache[i];
2785 // Mark the chunk for the least recently used algorithym
2786 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache)
2788 if( dev->srLastUse < 0 ||
2789 dev->srLastUse > 1000000)
2791 // Reset the cache usages
2793 for(i = 1; i < YAFFS_N_CACHE_CHUNKS; i++)
2795 dev->srCache[i].lastUse = 0;
2802 cache->lastUse = dev->srLastUse;
2806 // Invalidate a single cache page
2807 static void yaffs_InvalidateChunkCache(yaffs_Device *dev, int objectId, int chunkId)
2809 yaffs_ChunkCache *cache = yaffs_FindChunkCache(dev,objectId,chunkId);
2813 cache->objectId = 0;
2818 // Invalidate all the cache pages associated with this object
2819 // Do this whenever ther file is modified... dumb as a rock remember!
2820 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
2823 yaffs_Device *dev = in->myDev;
2824 int id = in->objectId;
2826 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2828 if(dev->srCache[i].objectId == id)
2830 dev->srCache[i].objectId = 0;
2838 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
2844 static yaffs_ChunkCache *yaffs_FindChunkCache(yaffs_Device *dev, int objectId, int chunkId)
2849 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache)
2853 static void yaffs_InvalidateChunkCache(yaffs_Device *dev, int objectId, int chunkId)
2857 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
2867 ///////////////////////// File read/write ///////////////////////////////
2868 // Read and write have very similar structures.
2869 // In general the read/write has three parts to it
2870 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
2871 // * Some complete chunks
2872 // * An incomplete chunk to end off with
2874 // Curve-balls: the first chunk might also be the last chunk.
2876 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
2879 // yaffs_Device *dev = in->myDev;
2881 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2882 yaffs_ChunkCache *cache;
2885 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2896 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
2897 start = offset % YAFFS_BYTES_PER_CHUNK;
2899 // OK now check for the curveball where the start and end are in
2901 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
2907 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
2910 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
2912 // An incomplete start or end chunk (or maybe both start and end chunk)
2913 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2914 // If we can't find the data in the cache, then load it up.
2915 cache = yaffs_FindChunkCache(in->myDev,in->objectId,chunk);
2918 cache = yaffs_GrabChunkCache(in->myDev);
2919 cache->objectId = in->objectId;
2920 cache->chunkId = chunk;
2921 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
2924 yaffs_UseChunkCache(in->myDev,cache);
2926 memcpy(buffer,&cache->data[start],nToCopy);
2928 // Read into the local buffer then copy...
2929 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2930 memcpy(buffer,&localBuffer[start],nToCopy);
2936 // Under WinCE can't do direct transfer. Need to use a local buffer.
2937 // This is because we otherwise screw up WinCE's memory mapper
2938 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2939 memcpy(buffer,localBuffer,YAFFS_BYTES_PER_CHUNK);
2941 // A full chunk. Read directly into the supplied buffer.
2942 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
2957 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
2959 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2967 int endOfWrite = offset+nBytes;
2968 int chunkWritten = 0;
2971 yaffs_InvalidateWholeChunkCache(in);
2974 while(n > 0 && chunkWritten >= 0)
2976 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
2977 start = offset % YAFFS_BYTES_PER_CHUNK;
2980 // OK now check for the curveball where the start and end are in
2983 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
2987 // Now folks, to calculate how many bytes to write back....
2988 // If we're overwriting and not writing to then end of file then
2989 // we need to write back as much as was there before.
2991 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
2993 if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
2995 nBytesRead = YAFFS_BYTES_PER_CHUNK;
2997 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3002 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3003 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3006 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3008 // An incomplete start or end chunk (or maybe both start and end chunk)
3009 // Read into the local buffer then copy, then copy over and write back.
3011 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3013 memcpy(&localBuffer[start],buffer,nToCopy);
3015 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,nToWriteBack,0);
3017 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3024 // Under WinCE can't do direct transfer. Need to use a local buffer.
3025 // This is because we otherwise screw up WinCE's memory mapper
3026 memcpy(localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3027 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3029 // A full chunk. Write directly from the supplied buffer.
3030 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3032 // Since we've overwritten the cached data, we better invalidate it.
3033 yaffs_InvalidateChunkCache(in->myDev,in->objectId,chunk);
3034 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3037 if(chunkWritten >= 0)
3047 // Update file object
3049 if(endOfWrite > in->variant.fileVariant.fileSize)
3051 in->variant.fileVariant.fileSize = endOfWrite;
3055 /*in->st_mtime = CURRENT_TIME; only update in flush*/
3061 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3065 int oldFileSize = in->variant.fileVariant.fileSize;
3066 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3068 yaffs_Device *dev = in->myDev;
3070 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
3072 yaffs_InvalidateWholeChunkCache(in);
3074 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3076 return yaffs_GetFileSize(in);
3079 if(newSize < oldFileSize)
3082 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3084 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3085 YAFFS_BYTES_PER_CHUNK;
3087 // Delete backwards so that we don't end up with holes if
3088 // power is lost part-way through the operation.
3089 for(i = lastDel; i >= startDel; i--)
3091 // NB this could be optimised somewhat,
3092 // eg. could retrieve the tags and write them without
3093 // using yaffs_DeleteChunk
3095 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3096 if(chunkId <= 0 || chunkId >= (dev->endBlock * 32))
3098 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3103 yaffs_DeleteChunk(dev,chunkId);
3108 if(sizeOfPartialChunk != 0)
3110 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3112 // Got to read and rewrite the last chunk with its new size.
3113 yaffs_ReadChunkDataFromObject(in,lastChunk,localBuffer);
3115 yaffs_WriteChunkDataToObject(in,lastChunk,localBuffer,sizeOfPartialChunk,1);
3119 in->variant.fileVariant.fileSize = newSize;
3121 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3133 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3135 obj = yaffs_GetEquivalentObject(obj);
3137 switch(obj->variantType)
3139 case YAFFS_OBJECT_TYPE_FILE:
3140 return obj->variant.fileVariant.fileSize;
3141 case YAFFS_OBJECT_TYPE_SYMLINK:
3142 return strlen(obj->variant.symLinkVariant.alias);
3150 // yaffs_FlushFile() updates the file's
3153 int yaffs_FlushFile(yaffs_Object *in)
3158 //T(("flushing object header\n"));
3160 in->st_mtime = CURRENT_TIME;
3162 retVal = yaffs_UpdateObjectHeader(in,NULL,0);
3174 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3176 yaffs_InvalidateWholeChunkCache(in);
3177 yaffs_RemoveObjectFromDirectory(in);
3178 yaffs_DeleteChunk(in->myDev,in->chunkId);
3182 in->myInode->u.generic_ip = NULL;
3186 yaffs_FreeObject(in);
3191 // yaffs_DeleteFile deletes the whole file data
3192 // and the inode associated with the file.
3193 // It does not delete the links associated with the file.
3194 static int yaffs_UnlinkFile(yaffs_Object *in)
3197 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3198 // Delete the file data & tnodes
3200 yaffs_ResizeFile(in,0);
3202 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3206 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3208 return yaffs_DoGenericObjectDeletion(in);
3211 int immediateDeletion=0;
3212 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3213 if(retVal == YAFFS_OK)
3216 //in->myDev->nUnlinkedFiles++;
3217 //in->renameAllowed = 0;
3221 immediateDeletion = 1;
3228 immediateDeletion = 1;
3233 if(immediateDeletion)
3235 T((TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3237 in->myDev->nDeletedFiles++;
3247 int yaffs_DeleteFile(yaffs_Object *in)
3249 int retVal = YAFFS_OK;
3252 retVal = yaffs_UnlinkFile(in);
3254 if(retVal == YAFFS_OK &&
3259 in->myDev->nDeletedFiles++;
3261 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3264 static int yaffs_DeleteDirectory(yaffs_Object *in)
3266 //First check that the directory is empty.
3267 if(list_empty(&in->variant.directoryVariant.children))
3269 return yaffs_DoGenericObjectDeletion(in);
3276 static int yaffs_DeleteSymLink(yaffs_Object *in)
3278 YFREE(in->variant.symLinkVariant.alias);
3280 return yaffs_DoGenericObjectDeletion(in);
3283 static int yaffs_DeleteHardLink(yaffs_Object *in)
3285 // remove this hardlink from the list assocaited with the equivalent
3287 list_del(&in->hardLinks);
3288 return yaffs_DoGenericObjectDeletion(in);
3292 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3296 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3298 return yaffs_DeleteHardLink(obj);
3300 else if(!list_empty(&obj->hardLinks))
3303 // Curve ball: We're unlinking an object that has a hardlink.
3304 // Therefore we can't really delete the object.
3305 // Instead, we do the following:
3306 // - Select a hardlink.
3307 // - Re-type a hardlink as the equivalent object and populate the fields, including the
3308 // objectId. Updating the object id is important so that all the hardlinks do not need
3310 // - Update the equivalet object pointers.
3311 // - Delete all object.
3314 struct list_head *i;
3317 yaffs_RemoveObjectFromDirectory(obj);
3321 hl = list_entry(obj->hardLinks.next, yaffs_Object,hardLinks);
3324 hl->st_mode = obj->st_mode;
3325 hl->st_uid = obj->st_uid;
3326 hl->st_gid = obj->st_gid;
3327 hl->st_atime = obj->st_atime;
3328 hl->st_mtime = obj->st_mtime;
3329 hl->st_ctime = obj->st_ctime;
3330 hl->st_rdev = obj->st_rdev;
3332 hl->variantType = obj->variantType;
3334 switch(hl->variantType)
3336 case YAFFS_OBJECT_TYPE_FILE:
3337 case YAFFS_OBJECT_TYPE_SYMLINK:
3338 case YAFFS_OBJECT_TYPE_SPECIAL:
3339 // These types are OK to just copy across.
3340 hl->variant = obj->variant;
3342 case YAFFS_OBJECT_TYPE_DIRECTORY:
3344 list_add(&hl->variant.directoryVariant.children,
3345 &obj->variant.directoryVariant.children);
3346 list_del(&obj->variant.directoryVariant.children);
3348 // Now change all the directory children to point to the new parent.
3349 list_for_each(i,&hl->variant.directoryVariant.children)
3351 list_entry(i,yaffs_Object,siblings)->parent = hl;
3355 case YAFFS_OBJECT_TYPE_HARDLINK:
3356 case YAFFS_OBJECT_TYPE_UNKNOWN:
3357 // Should not be either of these types.
3360 // Now fix up the hardlink chain
3361 list_del(&obj->hardLinks);
3363 list_for_each(i,&hl->hardLinks)
3365 list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObject = hl;
3366 list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObjectId = hl->objectId;
3369 // Now fix up the hash links.
3370 yaffs_UnhashObject(hl);
3371 hl->objectId = obj->objectId;
3372 yaffs_HashObject(hl);
3374 // Update the hardlink which has become an object
3375 yaffs_UpdateObjectHeader(hl,NULL,0);
3377 // Finally throw away the deleted object
3378 yaffs_DeleteChunk(obj->myDev,obj->chunkId);
3379 yaffs_FreeObject(obj);
3383 // Curve ball: We're unlinking an object that has a hardlink.
3385 // This problem arises because we are not strictly following
3386 // The Linux link/inode model.
3388 // We can't really delete the object.
3389 // Instead, we do the following:
3390 // - Select a hardlink.
3391 // - Unhook it from the hard links
3392 // - Unhook it from its parent directory (so that the rename can work)
3393 // - Rename the object to the hardlink's name.
3394 // - Delete the hardlink
3399 char name[YAFFS_MAX_NAME_LENGTH+1];
3401 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3403 list_del_init(&hl->hardLinks);
3404 list_del_init(&hl->siblings);
3406 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3408 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3410 if(retVal == YAFFS_OK)
3412 retVal = yaffs_DoGenericObjectDeletion(hl);
3422 switch(obj->variantType)
3424 case YAFFS_OBJECT_TYPE_FILE:
3425 return yaffs_UnlinkFile(obj);
3427 case YAFFS_OBJECT_TYPE_DIRECTORY:
3428 return yaffs_DeleteDirectory(obj);
3430 case YAFFS_OBJECT_TYPE_SYMLINK:
3431 return yaffs_DeleteSymLink(obj);
3433 case YAFFS_OBJECT_TYPE_HARDLINK:
3434 case YAFFS_OBJECT_TYPE_UNKNOWN:
3441 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3445 obj = yaffs_FindObjectByName(dir,name);
3447 if(obj && obj->unlinkAllowed)
3449 return yaffs_UnlinkWorker(obj);
3456 //////////////// Initialisation Scanning /////////////////
3460 // For now we use the SmartMedia check.
3461 // We look at the blockStatus byte in the first two chunks
3462 // These must be 0xFF to pass as OK.
3463 // todo: this function needs to be modifyable foir different NAND types
3464 // and different chunk sizes. Suggest make this into a per-device configurable
3466 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3470 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK,NULL,&spare,1);
3472 if(yaffs_CountBits(spare.blockStatus) < 7)
3477 if(spare.blockStatus != 0xFF)
3482 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK + 1,NULL,&spare,1);
3485 if(yaffs_CountBits(spare.blockStatus) < 7)
3490 if(spare.blockStatus != 0xFF)
3500 static int yaffs_Scan(yaffs_Device *dev)
3508 yaffs_BlockState state;
3509 yaffs_Object *hardList = NULL;
3511 yaffs_BlockInfo *bi;
3514 yaffs_ObjectHeader *oh;
3516 yaffs_Object *parent;
3518 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
3521 // Scan all the blocks...
3523 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
3526 bi = yaffs_GetBlockInfo(dev,blk);
3529 state = YAFFS_BLOCK_STATE_SCANNING;
3532 if(yaffs_IsBlockBad(dev,blk))
3534 state = YAFFS_BLOCK_STATE_DEAD;
3535 T((TSTR("block %d is bad" TENDSTR),blk));
3538 // Read each chunk in the block.
3540 for(c = 0; c < YAFFS_CHUNKS_PER_BLOCK &&
3541 state == YAFFS_BLOCK_STATE_SCANNING; c++)
3543 // Read the spare area and decide what to do
3544 chunk = blk * YAFFS_CHUNKS_PER_BLOCK + c;
3546 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
3549 // This block looks ok, now what's in this chunk?
3550 yaffs_GetTagsFromSpare(dev,&spare,&tags);
3552 if(yaffs_CountBits(spare.pageStatus) < 6)
3556 dev->nFreeChunks ++;
3557 //T((" %d %d deleted\n",blk,c));
3559 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
3561 // An unassigned chunk in the block
3562 // This means that either the block is empty or
3563 // this is the one being allocated from
3567 // the block is unused
3568 state = YAFFS_BLOCK_STATE_EMPTY;
3569 dev->nErasedBlocks++;
3573 // this is the block being allocated from
3574 T((TSTR(" Allocating from %d %d" TENDSTR),blk,c));
3575 state = YAFFS_BLOCK_STATE_ALLOCATING;
3576 dev->allocationBlock = blk;
3577 dev->allocationPage = c;
3580 dev->nFreeChunks += (YAFFS_CHUNKS_PER_BLOCK - c);
3582 else if(tags.chunkId > 0)
3586 bi->pageBits |= (1 << c);
3589 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
3590 // PutChunkIntoFIle checks for a clash (two data chunks with
3591 // the same chunkId).
3592 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
3593 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
3594 if(in->variant.fileVariant.scannedFileSize <endpos)
3596 in->variant.fileVariant.scannedFileSize = endpos;
3597 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3598 in->variant.fileVariant.fileSize =
3599 in->variant.fileVariant.scannedFileSize;
3603 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
3607 // chunkId == 0, so it is an ObjectHeader.
3608 // Thus, we read in the object header and make the object
3609 bi->pageBits |= (1 << c);
3612 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
3614 oh = (yaffs_ObjectHeader *)chunkData;
3616 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
3620 // We have already filled this one. We have a duplicate and need to resolve it.
3622 unsigned existingSerial = in->serial;
3623 unsigned newSerial = tags.serialNumber;
3625 if(((existingSerial+1) & 3) == newSerial)
3627 // Use new one - destroy the exisiting one
3628 yaffs_DeleteChunk(dev,in->chunkId);
3633 // Use existing - destroy this one.
3634 yaffs_DeleteChunk(dev,chunk);
3639 (tags.objectId == YAFFS_OBJECTID_ROOT ||
3640 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
3642 // We only load some info, don't fiddle with directory structure
3644 in->variantType = oh->type;
3646 in->st_mode = oh->st_mode;
3647 in->st_uid = oh->st_uid;
3648 in->st_gid = oh->st_gid;
3649 in->st_atime = oh->st_atime;
3650 in->st_mtime = oh->st_mtime;
3651 in->st_ctime = oh->st_ctime;
3652 in->st_rdev = oh->st_rdev;
3653 in->chunkId = chunk;
3658 // we need to load this info
3661 in->variantType = oh->type;
3663 in->st_mode = oh->st_mode;
3664 in->st_uid = oh->st_uid;
3665 in->st_gid = oh->st_gid;
3666 in->st_atime = oh->st_atime;
3667 in->st_mtime = oh->st_mtime;
3668 in->st_ctime = oh->st_ctime;
3669 in->st_rdev = oh->st_rdev;
3670 in->chunkId = chunk;
3675 // directory stuff...
3676 // hook up to parent
3678 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
3679 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
3681 // Set up as a directory
3682 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
3683 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
3685 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
3687 // Hoosterman, another problem....
3688 // We're trying to use a non-directory as a directory
3692 yaffs_AddObjectToDirectory(parent,in);
3693 if(parent == dev->unlinkedDir)
3695 in->deleted = 1; // If it is unlinked at start up then it wants deleting
3696 dev->nDeletedFiles++;
3699 // Note re hardlinks.
3700 // Since we might scan a hardlink before its equivalent object is scanned
3701 // we put them all in a list.
3702 // After scanning is complete, we should have all the objects, so we run through this
3703 // list and fix up all the chains.
3705 switch(in->variantType)
3707 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
3709 case YAFFS_OBJECT_TYPE_FILE:
3710 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3711 in->variant.fileVariant.fileSize = oh->fileSize;
3714 case YAFFS_OBJECT_TYPE_HARDLINK:
3715 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
3716 (yaffs_Object *)(in->hardLinks.next) = hardList;
3719 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
3721 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
3723 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
3724 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
3727 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
3732 if(state == YAFFS_BLOCK_STATE_SCANNING)
3734 // If we got this far while scanning, then the block is fully allocated.
3735 state = YAFFS_BLOCK_STATE_FULL;
3738 bi->blockState = state;
3740 // Now let's see if it was dirty
3741 if( bi->pagesInUse == 0 &&
3742 bi->blockState == YAFFS_BLOCK_STATE_FULL)
3744 yaffs_BlockBecameDirty(dev,blk);
3749 // Fix up the hard link chains.
3750 // We should now have scanned all the objects, now it's time to add these
3755 hardList = (yaffs_Object *)(hardList->hardLinks.next);
3757 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
3761 // Add the hardlink pointers
3762 hl->variant.hardLinkVariant.equivalentObject=in;
3763 list_add(&hl->hardLinks,&in->hardLinks);
3767 //Todo Need to report/handle this better.
3768 // Got a problem... hardlink to a non-existant object
3769 hl->variant.hardLinkVariant.equivalentObject=NULL;
3770 INIT_LIST_HEAD(&hl->hardLinks);
3782 ////////////////////////// Directory Functions /////////////////////////
3785 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
3788 if(obj->siblings.prev == NULL)
3791 INIT_LIST_HEAD(&obj->siblings);
3794 else if(!list_empty(&obj->siblings))
3796 // If it is holed up somewhere else, un hook it
3797 list_del_init(&obj->siblings);
3800 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
3801 obj->parent = directory;
3803 if(directory == obj->myDev->unlinkedDir)
3806 obj->myDev->nUnlinkedFiles++;
3807 obj->renameAllowed = 0;
3811 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
3813 list_del_init(&obj->siblings);
3817 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
3821 struct list_head *i;
3822 char buffer[YAFFS_MAX_NAME_LENGTH+1];
3826 sum = yaffs_CalcNameSum(name);
3828 list_for_each(i,&directory->variant.directoryVariant.children)
3830 l = list_entry(i, yaffs_Object,siblings);
3832 // Special case for lost-n-found
3833 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
3835 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
3840 else if(yaffs_SumCompare(l->sum, sum))
3843 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
3844 if(yaffs_strcmp(name,buffer) == 0)
3857 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
3859 struct list_head *i;
3863 list_for_each(i,&theDir->variant.directoryVariant.children)
3865 l = list_entry(i, yaffs_Object,siblings);
3877 // GetEquivalentObject dereferences any hard links to get to the
3880 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
3882 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3884 // We want the object id of the equivalent object, not this one
3885 obj = obj->variant.hardLinkVariant.equivalentObject;
3891 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
3893 memset(name,0,buffSize);
3895 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
3897 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
3899 else if(obj->chunkId <= 0)
3903 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
3904 strncpy(name,locName,buffSize - 1);
3909 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
3910 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
3912 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
3914 if(obj->chunkId >= 0)
3916 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
3918 strncpy(name,oh->name,buffSize - 1);
3921 return strlen(name);
3924 int yaffs_GetObjectFileLength(yaffs_Object *obj)
3927 // Dereference any hard linking
3928 obj = yaffs_GetEquivalentObject(obj);
3930 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3932 return obj->variant.fileVariant.fileSize;
3934 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
3936 return strlen(obj->variant.symLinkVariant.alias);
3940 // Only a directory should drop through to here
3941 return YAFFS_BYTES_PER_CHUNK;
3945 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
3948 struct list_head *i;
3952 count++; // the object itself
3954 list_for_each(i,&obj->hardLinks)
3956 count++; // add the hard links;
3963 int yaffs_GetObjectInode(yaffs_Object *obj)
3965 obj = yaffs_GetEquivalentObject(obj);
3967 return obj->objectId;
3970 unsigned yaffs_GetObjectType(yaffs_Object *obj)
3972 obj = yaffs_GetEquivalentObject(obj);
3974 switch(obj->variantType)
3976 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
3977 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
3978 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
3979 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
3980 case YAFFS_OBJECT_TYPE_SPECIAL:
3981 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
3982 if(S_ISCHR(obj->st_mode)) return DT_CHR;
3983 if(S_ISBLK(obj->st_mode)) return DT_BLK;
3984 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
3985 default: return DT_REG; break;
3989 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
3991 obj = yaffs_GetEquivalentObject(obj);
3992 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
3994 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
3998 return yaffs_CloneString("");
4003 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4005 unsigned int valid = attr->ia_valid;
4007 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4008 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4009 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4011 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
4012 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
4013 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
4015 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4017 yaffs_UpdateObjectHeader(obj,NULL,1);
4022 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4024 unsigned int valid = 0;
4026 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
4027 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
4028 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
4030 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
4031 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
4032 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
4034 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4036 attr->ia_valid = valid;
4044 int yaffs_DumpObject(yaffs_Object *obj)
4046 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4048 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4050 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4052 // if(obj->chunkId >= 0)
4054 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4057 yaffs_GetObjectName(obj,name,256);
4059 YPRINTF(("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d type %d size %d\n",
4060 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
4061 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4064 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4065 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
4066 obj->sum, obj->chunkId));
4067 switch(obj->variantType)
4069 case YAFFS_OBJECT_TYPE_FILE:
4070 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4072 case YAFFS_OBJECT_TYPE_DIRECTORY:
4073 YPRINTF((" DIRECTORY\n"));
4075 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4076 case YAFFS_OBJECT_TYPE_SYMLINK:
4077 case YAFFS_OBJECT_TYPE_UNKNOWN:
4086 ///////////////////////// Initialisation code ///////////////////////////
4090 int yaffs_GutsInitialise(yaffs_Device *dev)
4099 if(!yaffs_CheckStructures())
4101 YPRINTF(("yaffs_CheckStructures failed\n"));
4105 if(dev->startBlock <= 0 ||
4106 (dev->endBlock - dev->startBlock) < 10)
4108 YPRINTF(("startBlock %d or endBlock %d invalid\n",
4109 dev->startBlock, dev->endBlock));
4113 nBlocks = dev->endBlock - dev->startBlock + 1;
4117 // OK now calculate a few things for the device
4118 // Calculate chunkGroupBits.
4119 // We need to find the next power of 2 > than endBlock
4121 x = YAFFS_CHUNKS_PER_BLOCK * (dev->endBlock+1);
4123 for(bits = extraBits = 0; x > 1; bits++)
4125 if(x & 1) extraBits++;
4129 if(extraBits > 0) bits++;
4132 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4133 // chunk range we're using is greater than 16 we need
4134 // to figure out chunk shift and chunkGroupSize
4137 dev->chunkGroupBits = 0;
4141 dev->chunkGroupBits = bits - 16;
4143 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4146 // More device initialisation
4147 dev->garbageCollectionRequired = 0;
4148 dev->garbageCollections = 0;
4149 dev->currentDirtyChecker = 0;
4150 dev->bufferedBlock = -1;
4151 dev->doingBufferedBlockRewrite = 0;
4152 dev->blockSelectedForGC = -1;
4153 dev->nDeletedFiles = 0;
4154 dev->nBackgroundDeletions=0;
4155 dev->nUnlinkedFiles = 0;
4158 dev->tagsEccFixed=0;
4159 dev->tagsEccUnfixed=0;
4161 yaffs_InitialiseBlocks(dev,nBlocks);
4163 yaffs_InitialiseTnodes(dev);
4165 yaffs_InitialiseObjects(dev);
4167 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
4170 for(i=0; i < YAFFS_N_CACHE_CHUNKS; i++)
4172 dev->srCache[i].objectId = 0;
4173 dev->srCache[i].lastUse = 0;
4182 // Initialise the unlinked, root and lost and found directories
4183 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4185 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4187 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4188 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4189 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4192 // Now scan the flash.
4196 dev->nPageReads = 0;
4197 dev->nPageWrites = 0;
4198 dev->nBlockErasures = 0;
4200 dev->nRetriedWrites = 0;
4201 dev->nRetiredBlocks = 0;
4208 void yaffs_Deinitialise(yaffs_Device *dev)
4210 yaffs_DeinitialiseBlocks(dev);
4211 yaffs_DeinitialiseTnodes(dev);
4212 yaffs_DeinitialiseObjects(dev);
4216 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4218 int nFree = dev->nFreeChunks - (YAFFS_CHUNKS_PER_BLOCK * YAFFS_RESERVED_BLOCKS);
4220 struct list_head *i;
4224 // To the free chunks add the chunks that are in the deleted unlinked files.
4225 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4227 l = list_entry(i, yaffs_Object,siblings);
4231 nFree += l->nDataChunks;
4236 return (nFree < 0) ? 0 : nFree;
4241 /////////////////// YAFFS test code //////////////////////////////////
4243 #define yaffs_CheckStruct(structure,syze, name) \
4244 if(sizeof(structure) != syze) \
4245 { YPRINTF(("%s should be %d but is %d\n",name,syze,sizeof(structure))); \
4246 return YAFFS_FAIL; \
4250 static int yaffs_CheckStructures(void)
4252 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4253 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4254 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4255 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4256 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4262 void yaffs_GutsTest(yaffs_Device *dev)
4265 if(yaffs_CheckStructures() != YAFFS_OK)
4267 YPRINTF(("One or more structures malformed-- aborting\n"));
4272 YPRINTF(("Structures OK\n"));
4275 yaffs_TnodeTest(dev);
4276 yaffs_ObjectTest(dev);