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.
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
23 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
26 // External functions for ECC on data
27 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
28 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
31 // countBits is a quick way of counting the number of bits in a byte.
32 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
34 static const char yaffs_countBitsTable[256] =
36 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
37 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
38 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
39 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
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 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
43 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
44 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
45 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
46 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
47 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
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 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
51 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
54 static int yaffs_CountBits(__u8 x)
57 retVal = yaffs_countBitsTable[x];
64 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
65 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
66 static void yaffs_GetTagsFromSpare(yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
67 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
71 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force);
72 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
81 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
82 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
83 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
84 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare);
85 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare);
87 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
89 static int yaffs_UnlinkWorker(yaffs_Object *obj);
92 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1);
96 loff_t yaffs_GetFileSize(yaffs_Object *obj);
98 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
99 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
102 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
104 #ifdef YAFFS_PARANOID
105 static int yaffs_CheckFileSanity(yaffs_Object *in);
107 #define yaffs_CheckFileSanity(in)
110 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
111 static void yaffs_InvalidateChunkCache(yaffs_Object *in);
112 #define yaffs_INVALIDATECHUNKCACHE(in) yaffs_InvalidateChunkCache(in)
114 #define yaffs_INVALIDATECHUNKCACHE(in)
118 static __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
120 if(blk < dev->startBlock || blk > dev->endBlock)
124 return &dev->blockInfo[blk - dev->startBlock];
128 static __inline__ int yaffs_HashFunction(int n)
130 return (n % YAFFS_NOBJECT_BUCKETS);
134 yaffs_Object *yaffs_Root(yaffs_Device *dev)
139 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
141 return dev->lostNFoundDir;
145 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
148 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
152 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, __u8 *data, yaffs_Spare *spare,int doErrorCorrection)
156 yaffs_Spare localSpare;
157 int eccResult1,eccResult2;
163 // If we don't have a real spare, then we use a local one.
164 // Need this for the calculation of the ecc
168 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
169 if(data && doErrorCorrection)
172 //Todo handle any errors
173 nand_calculate_ecc(data,calcEcc);
174 eccResult1 = nand_correct_data (data,spare->ecc1, calcEcc);
175 nand_calculate_ecc(&data[256],calcEcc);
176 eccResult2 = nand_correct_data (&data[256],spare->ecc2, calcEcc);
180 T((TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
182 else if(eccResult1<0)
184 T((TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
189 T((TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
191 else if(eccResult2<0)
193 T((TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
196 if(eccResult1 || eccResult2)
198 // Hoosterman, we had a data problem on this page
199 yaffs_HandleReadDataError(dev,chunkInNAND);
206 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
210 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
211 static __u8 data[YAFFS_BYTES_PER_CHUNK];
212 static __u8 spare[16];
215 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
221 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
225 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL;
226 if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
235 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
237 dev->nBlockErasures++;
238 return dev->eraseBlockInNAND(dev,blockInNAND);
241 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
243 return dev->initialiseNAND(dev);
246 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
253 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
257 chunk = yaffs_AllocateChunk(dev,useReserve);
262 // First check this chunk is erased...
263 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
264 writeOk = yaffs_CheckChunkErased(dev,chunk);
268 T((TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
272 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
278 // If verify fails, then delete this chunk and try again
279 // To verify we compare everything except the block and
280 // page status bytes.
281 // NB We check a raw read without ECC correction applied
282 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
284 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
285 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
288 T((TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
297 // Copy the data into the write buffer.
298 // NB We do this at the end to prevent duplicates in the case of a write error.
300 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
304 yaffs_HandleWriteChunkError(dev,chunk);
308 } while(chunk >= 0 && ! writeOk);
312 T((TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
313 dev->nRetriedWrites+= (attempts - 1);
320 // Functions for robustisizing
324 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
326 // Ding the blockStatus in the first two pages of the block.
330 memset(&spare, 0xff,sizeof(yaffs_Spare));
332 spare.blockStatus = 0;
334 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK, NULL , &spare);
335 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK + 1, NULL , &spare);
337 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
338 dev->nRetiredBlocks++;
343 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
345 dev->doingBufferedBlockRewrite = 1;
347 // Remove erased chunks
348 // Rewrite existing chunks to a new block
349 // Set current write block to the new block
351 dev->doingBufferedBlockRewrite = 0;
357 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
359 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
361 // Mark the block for retirement
362 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
363 T((TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
367 // Just do a garbage collection on the affected block then retire the block
372 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
376 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare)
380 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare)
384 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
386 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
388 // Mark the block for retirement
389 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
391 yaffs_DeleteChunk(dev,chunkInNAND);
397 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1)
401 if( memcmp(d0,d1,YAFFS_BYTES_PER_CHUNK) != 0 ||
402 s0->tagByte0 != s1->tagByte0 ||
403 s0->tagByte1 != s1->tagByte1 ||
404 s0->tagByte2 != s1->tagByte2 ||
405 s0->tagByte3 != s1->tagByte3 ||
406 s0->tagByte4 != s1->tagByte4 ||
407 s0->tagByte5 != s1->tagByte5 ||
408 s0->tagByte6 != s1->tagByte6 ||
409 s0->tagByte7 != s1->tagByte7 ||
410 s0->ecc1[0] != s1->ecc1[0] ||
411 s0->ecc1[1] != s1->ecc1[1] ||
412 s0->ecc1[2] != s1->ecc1[2] ||
413 s0->ecc2[0] != s1->ecc2[0] ||
414 s0->ecc2[1] != s1->ecc2[1] ||
415 s0->ecc2[2] != s1->ecc2[2] )
424 ///////////////////////// Object management //////////////////
425 // List of spare objects
426 // The list is hooked together using the first pointer
429 // static yaffs_Object *yaffs_freeObjects = NULL;
431 // static int yaffs_nFreeObjects;
433 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
435 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
438 static __u16 yaffs_CalcNameSum(const char *name)
443 __u8 *bname = (__u8 *)name;
457 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
459 nand_calculate_ecc (data , spare->ecc1);
460 nand_calculate_ecc (&data[256] , spare->ecc2);
463 void yaffs_CalcTagsECC(yaffs_Tags *tags)
467 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
474 for(i = 0; i < 8; i++)
476 for(j = 1; j &0xff; j<<=1)
491 void yaffs_CheckECCOnTags(yaffs_Tags *tags)
493 unsigned ecc = tags->ecc;
495 yaffs_CalcTagsECC(tags);
502 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
506 b[ecc / 8] ^= (1 << (ecc & 7));
508 // Now recvalc the ecc
509 yaffs_CalcTagsECC(tags);
514 ///////////////////////// TNODES ///////////////////////
516 // List of spare tnodes
517 // The list is hooked together using the first pointer
520 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
522 // static int yaffs_nFreeTnodes;
524 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
528 // yaffs_CreateTnodes creates a bunch more tnodes and
529 // adds them to the tnode free list.
530 // Don't use this function directly
532 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
535 yaffs_Tnode *newTnodes;
536 yaffs_TnodeList *tnl;
538 if(nTnodes < 1) return YAFFS_OK;
542 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
546 YALERT("Could not malloc tnodes");
550 // Hook them into the free list
551 for(i = 0; i < nTnodes - 1; i++)
553 newTnodes[i].internal[0] = &newTnodes[i+1];
556 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
557 dev->freeTnodes = newTnodes;
558 dev->nFreeTnodes+= nTnodes;
559 dev->nTnodesCreated += nTnodes;
561 // Now add this bunch of tnodes to a list for freeing up.
563 tnl = YMALLOC(sizeof(yaffs_TnodeList));
566 YALERT("Could not add tnodes to management list");
570 tnl->tnodes = newTnodes;
571 tnl->next = dev->allocatedTnodeList;
572 dev->allocatedTnodeList = tnl;
576 YINFO("Tnodes created");
583 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
584 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
586 yaffs_Tnode *tn = NULL;
588 // If there are none left make more
591 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
596 tn = dev->freeTnodes;
597 dev->freeTnodes = dev->freeTnodes->internal[0];
600 memset(tn,0,sizeof(yaffs_Tnode));
608 // FreeTnode frees up a tnode and puts it back on the free list
609 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
611 tn->internal[0] = dev->freeTnodes;
612 dev->freeTnodes = tn;
617 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
619 // Free the list of allocated tnodes
621 while(dev->allocatedTnodeList)
623 YFREE(dev->allocatedTnodeList->tnodes);
624 dev->allocatedTnodeList = dev->allocatedTnodeList->next;
627 dev->freeTnodes = NULL;
628 dev->nFreeTnodes = 0;
631 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
633 dev->allocatedTnodeList = NULL;
634 dev->freeTnodes = NULL;
635 dev->nFreeTnodes = 0;
636 dev->nTnodesCreated = 0;
640 void yaffs_TnodeTest(yaffs_Device *dev)
645 yaffs_Tnode *tn[1000];
647 YINFO("Testing TNodes");
649 for(j = 0; j < 50; j++)
651 for(i = 0; i < 1000; i++)
653 tn[i] = yaffs_GetTnode(dev);
656 YALERT("Getting tnode failed");
659 for(i = 0; i < 1000; i+=3)
661 yaffs_FreeTnode(dev,tn[i]);
668 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
670 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
671 // The look up tree is represented by the top tnode and the number of topLevel
672 // in the tree. 0 means only the level 0 tnode is in the tree.
675 // FindLevel0Tnode finds the level 0 tnode, if one exists.
676 // Used when reading.....
677 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
680 yaffs_Tnode *tn = fStruct->top;
682 int requiredTallness;
683 int level = fStruct->topLevel;
685 // Check sane level and chunk Id
686 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
689 sprintf(str,"Bad level %d",level);
694 if(chunkId > YAFFS_MAX_CHUNK_ID)
697 sprintf(str,"Bad chunkId %d",chunkId);
702 // First check we're tall enough (ie enough topLevel)
704 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
705 requiredTallness = 0;
708 i >>= YAFFS_TNODES_INTERNAL_BITS;
713 if(requiredTallness > fStruct->topLevel)
715 // Not tall enough, so we can't find it, return NULL.
720 // Traverse down to level 0
721 while (level > 0 && tn)
723 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
724 YAFFS_TNODES_INTERNAL_MASK];
732 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
733 // This happens in two steps:
734 // 1. If the tree isn't tall enough, then make it taller.
735 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
737 // Used when modifying the tree.
739 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
744 int requiredTallness;
750 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
752 // Check sane level and page Id
753 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
756 sprintf(str,"Bad level %d",fStruct->topLevel);
761 if(chunkId > YAFFS_MAX_CHUNK_ID)
764 sprintf(str,"Bad chunkId %d",chunkId);
769 // First check we're tall enough (ie enough topLevel)
771 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
772 requiredTallness = 0;
775 i >>= YAFFS_TNODES_INTERNAL_BITS;
779 //T((TSTR(" required=%d"),requiredTallness));
782 if(requiredTallness > fStruct->topLevel)
784 // Not tall enough,gotta make the tree taller
785 for(i = fStruct->topLevel; i < requiredTallness; i++)
787 //T((TSTR(" add new top")));
789 tn = yaffs_GetTnode(dev);
793 tn->internal[0] = fStruct->top;
798 YALERT("No more tnodes");
802 fStruct->topLevel = requiredTallness;
806 // Traverse down to level 0, adding anything we need
808 l = fStruct->topLevel;
812 i = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
813 YAFFS_TNODES_INTERNAL_MASK;
815 //T((TSTR(" [%d:%d]"),l,i));
819 //T((TSTR(" added")));
821 tn->internal[i] = yaffs_GetTnode(dev);
824 tn = tn->internal[i];
834 // DeleteWorker scans backwards through the tnode tree and deletes all the
835 // chunks and tnodes in the file
836 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
838 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
854 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
858 if(limit && (*limit) < 0)
864 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
865 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
869 yaffs_FreeTnode(in->myDev,tn->internal[i]);
870 tn->internal[i] = NULL;
875 return (allDone) ? 1 : 0;
879 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0; i--) //NB Don't apply the limit here, always delete a whole level0
885 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
887 theChunk = tn->level0[i] << in->myDev->chunkGroupBits;
889 // Now we need to search for it
890 for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
892 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
893 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
907 yaffs_DeleteChunk(in->myDev,theChunk);
934 // Pruning removes any part of the file structure tree that is beyond the
935 // bounds of the file (ie that does not point to chunks).
937 // A file should only get pruned when its size is reduced.
939 // Before pruning, the chunks must be pulled from the tree and the
940 // level 0 tnode entries must be zeroed out.
941 // Could also use this for file deletion, but that's probably better handled
942 // by a special case.
944 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
946 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
955 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
957 if(tn->internal[i] && level > 0)
959 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
968 if(hasData == 0 && del0)
970 // Free and return NULL
972 yaffs_FreeTnode(dev,tn);
982 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
989 if(fStruct->topLevel > 0)
991 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
993 // Now we have a tree with all the non-zero branches NULL but the height
994 // is the same as it was.
995 // Let's see if we can trim internal tnodes to shorten the tree.
996 // We can do this if only the 0th element in the tnode is in use
997 // (ie all the non-zero are NULL)
999 while(fStruct->topLevel && !done)
1004 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1014 fStruct->top = tn->internal[0];
1015 fStruct->topLevel--;
1016 yaffs_FreeTnode(dev,tn);
1031 /////////////////////// End of File Structure functions. /////////////////
1033 // yaffs_CreateFreeObjects creates a bunch more objects and
1034 // adds them to the object free list.
1035 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1038 yaffs_Object *newObjects;
1039 yaffs_ObjectList *list;
1041 if(nObjects < 1) return YAFFS_OK;
1043 // make these things
1045 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1049 YALERT("Could not allocate more objects");
1053 // Hook them into the free list
1054 for(i = 0; i < nObjects - 1; i++)
1056 (yaffs_Object *)newObjects[i].siblings.next = &newObjects[i+1];
1059 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1060 dev->freeObjects = newObjects;
1061 dev->nFreeObjects+= nObjects;
1062 dev->nObjectsCreated+= nObjects;
1064 // Now add this bunch of Objects to a list for freeing up.
1066 list = YMALLOC(sizeof(yaffs_ObjectList));
1069 YALERT("Could not add Objects to management list");
1073 list->objects = newObjects;
1074 list->next = dev->allocatedObjectList;
1075 dev->allocatedObjectList = list;
1079 YINFO("Objects created");
1086 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1087 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1089 yaffs_Object *tn = NULL;
1091 // If there are none left make more
1092 if(!dev->freeObjects)
1094 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1097 if(dev->freeObjects)
1099 tn = dev->freeObjects;
1100 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1101 dev->nFreeObjects--;
1103 // Now sweeten it up...
1105 memset(tn,0,sizeof(yaffs_Object));
1108 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1109 INIT_LIST_HEAD(&(tn->hardLinks));
1110 INIT_LIST_HEAD(&(tn->hashLink));
1111 INIT_LIST_HEAD(&tn->siblings);
1113 // Add it to the lost and found directory.
1114 // NB Can't put root or lostNFound in lostNFound so
1115 // check if lostNFound exists first
1116 if(dev->lostNFoundDir)
1118 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1126 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1129 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1132 obj->fake = 1; // it is fake so it has no NAND presence...
1133 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1134 obj->unlinkAllowed= 0; // ... or unlink it
1137 obj->st_mode = mode;
1139 obj->chunkId = 0; // Not a valid chunk.
1147 static void yaffs_UnhashObject(yaffs_Object *tn)
1150 yaffs_Device *dev = tn->myDev;
1153 // If it is still linked into the bucket list, free from the list
1154 if(!list_empty(&tn->hashLink))
1156 list_del_init(&tn->hashLink);
1157 bucket = yaffs_HashFunction(tn->objectId);
1158 dev->objectBucket[bucket].count--;
1164 // FreeObject frees up a Object and puts it back on the free list
1165 static void yaffs_FreeObject(yaffs_Object *tn)
1168 yaffs_Device *dev = tn->myDev;
1170 yaffs_UnhashObject(tn);
1172 // Link into the free list.
1173 (yaffs_Object *)(tn->siblings.next) = dev->freeObjects;
1174 dev->freeObjects = tn;
1175 dev->nFreeObjects++;
1181 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1183 // Free the list of allocated Objects
1185 while( dev->allocatedObjectList)
1187 YFREE(dev->allocatedObjectList->objects);
1188 dev->allocatedObjectList = dev->allocatedObjectList->next;
1191 dev->freeObjects = NULL;
1192 dev->nFreeObjects = 0;
1195 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1199 dev->allocatedObjectList = NULL;
1200 dev->freeObjects = NULL;
1201 dev->nFreeObjects = 0;
1203 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1205 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1206 dev->objectBucket[i].count = 0;
1216 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1221 int lowest = 999999;
1224 // First let's see if we can find one that's empty.
1226 for(i = 0; i < 10 && lowest > 0; i++)
1229 x %= YAFFS_NOBJECT_BUCKETS;
1230 if(dev->objectBucket[x].count < lowest)
1232 lowest = dev->objectBucket[x].count;
1238 // If we didn't find an empty list, then try
1239 // looking a bit further for a short one
1241 for(i = 0; i < 10 && lowest > 3; i++)
1244 x %= YAFFS_NOBJECT_BUCKETS;
1245 if(dev->objectBucket[x].count < lowest)
1247 lowest = dev->objectBucket[x].count;
1256 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1258 int bucket = yaffs_FindNiceObjectBucket(dev);
1260 // Now find an object value that has not already been taken
1261 // by scanning the list.
1264 struct list_head *i;
1268 //yaffs_CheckObjectHashSanity();
1273 n += YAFFS_NOBJECT_BUCKETS;
1274 if(1 ||dev->objectBucket[bucket].count > 0)
1276 list_for_each(i,&dev->objectBucket[bucket].list)
1278 // If there is already one in the list
1279 if(list_entry(i, yaffs_Object,hashLink)->objectId == n)
1287 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1292 void yaffs_HashObject(yaffs_Object *in)
1294 int bucket = yaffs_HashFunction(in->objectId);
1295 yaffs_Device *dev = in->myDev;
1297 if(!list_empty(&in->hashLink))
1303 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1304 dev->objectBucket[bucket].count++;
1308 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,int number)
1310 int bucket = yaffs_HashFunction(number);
1311 struct list_head *i;
1314 list_for_each(i,&dev->objectBucket[bucket].list)
1316 // Look if it is in the list
1317 in = list_entry(i, yaffs_Object,hashLink);
1318 if(in->objectId == number)
1329 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1332 yaffs_Object *theObject;
1336 number = yaffs_CreateNewObjectNumber(dev);
1339 theObject = yaffs_AllocateEmptyObject(dev);
1343 theObject->fake = 0;
1344 theObject->renameAllowed = 1;
1345 theObject->unlinkAllowed = 1;
1346 theObject->objectId = number;
1347 yaffs_HashObject(theObject);
1348 theObject->variantType = type;
1349 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1353 case YAFFS_OBJECT_TYPE_FILE:
1354 theObject->variant.fileVariant.fileSize = 0;
1355 theObject->variant.fileVariant.scannedFileSize = 0;
1356 theObject->variant.fileVariant.topLevel = 0;
1357 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1359 case YAFFS_OBJECT_TYPE_DIRECTORY:
1360 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1362 case YAFFS_OBJECT_TYPE_SYMLINK:
1363 // No action required
1365 case YAFFS_OBJECT_TYPE_HARDLINK:
1366 // No action required
1368 case YAFFS_OBJECT_TYPE_SPECIAL:
1369 // No action required
1371 case YAFFS_OBJECT_TYPE_UNKNOWN:
1372 // todo this should not happen
1380 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1382 yaffs_Object *theObject = NULL;
1386 theObject = yaffs_FindObjectByNumber(dev,number);
1391 theObject = yaffs_CreateNewObject(dev,number,type);
1398 char *yaffs_CloneString(const char *str)
1400 char *newStr = NULL;
1404 newStr = YMALLOC(strlen(str) + 1);
1413 // Mknod (create) a new object.
1414 // equivalentObject only has meaning for a hard link;
1415 // aliasString only has meaning for a sumlink.
1416 // rdev only has meaning for devices (a subset of special objects)
1417 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1418 yaffs_Object *parent,
1423 yaffs_Object *equivalentObject,
1424 const char *aliasString,
1429 yaffs_Device *dev = parent->myDev;
1431 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1432 if(yaffs_FindObjectByName(parent,name))
1437 in = yaffs_CreateNewObject(dev,-1,type);
1443 in->variantType = type;
1449 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1451 in->nDataChunks = 0;
1453 in->sum = yaffs_CalcNameSum(name);
1456 yaffs_AddObjectToDirectory(parent,in);
1458 in->myDev = parent->myDev;
1463 case YAFFS_OBJECT_TYPE_SYMLINK:
1464 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1466 case YAFFS_OBJECT_TYPE_HARDLINK:
1467 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1468 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1469 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1471 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1472 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1473 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1474 case YAFFS_OBJECT_TYPE_UNKNOWN:
1478 if(yaffs_GetNumberOfFreeChunks(dev) <= 0 ||
1479 yaffs_UpdateObjectHeader(in,name,0) < 0)
1481 // Could not create the object header, fail the creation
1482 yaffs_UnlinkWorker(in);
1491 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1493 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1496 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1498 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1501 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1503 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1506 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1508 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1511 // NB yaffs_Link returns the object id of the equivalent object.
1512 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1514 // Get the real object in case we were fed a hard link as an equivalent object
1515 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1517 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1519 return equivalentObject;
1529 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName)
1535 newDir = obj->parent; // use the old directory
1538 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1540 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1541 // duplicate names are allowed.
1542 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1544 (!yaffs_FindObjectByName(newDir,newName) &&
1545 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY))
1547 obj->sum = yaffs_CalcNameSum(newName);
1550 yaffs_AddObjectToDirectory(newDir,obj);
1552 if(unlinkOp) obj->unlinked = 1;
1555 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1564 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1568 obj = yaffs_FindObjectByName(oldDir,oldName);
1569 if(obj && obj->renameAllowed)
1571 return yaffs_ChangeObjectName(obj,newDir,newName);
1578 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1580 // Scan the buckets and check that the lists
1581 // have as many members as the count says there are
1584 struct list_head *j;
1587 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1591 list_for_each(j,&dev->objectBucket[bucket].list)
1596 if(countEm != dev->objectBucket[bucket].count)
1598 YALERT("Inode hash inconsistency");
1606 void yaffs_ObjectTest(yaffs_Device *dev)
1608 yaffs_Object *in[1000];
1610 yaffs_Object *inold[1000];
1614 memset(in,0,1000*sizeof(yaffs_Object *));
1615 memset(inold,0,1000*sizeof(yaffs_Object *));
1617 yaffs_CheckObjectHashSanity(dev);
1619 for(j = 0; j < 10; j++)
1623 for(i = 0; i < 1000; i++)
1625 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1628 YINFO("No more inodes");
1632 inNo[i] = in[i]->objectId;
1636 for(i = 0; i < 1000; i++)
1638 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1640 //T(("Differnce in look up test\n"));
1644 // T(("Look up ok\n"));
1648 yaffs_CheckObjectHashSanity(dev);
1650 for(i = 0; i < 1000; i+=3)
1652 yaffs_FreeObject(in[i]);
1657 yaffs_CheckObjectHashSanity(dev);
1664 /////////////////////////// Block Management and Page Allocation ///////////////////
1667 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1669 dev->allocationBlock = -1; // force it to get a new one
1670 //Todo we're assuming the malloc will pass.
1671 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1674 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1681 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1683 YFREE(dev->blockInfo);
1686 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1687 // for garbage collection.
1689 static int yaffs_FindDirtiestBlock(yaffs_Device *dev)
1692 int b = dev->currentDirtyChecker;
1696 int pagesInUse = 100; // silly big number
1697 yaffs_BlockInfo *bi;
1699 for(i = dev->startBlock; i <= dev->endBlock && pagesInUse > 2 ; i++)
1702 if (b > dev->endBlock)
1704 b = dev->startBlock;
1707 bi = yaffs_GetBlockInfo(dev,b);
1709 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1710 bi->pagesInUse < pagesInUse)
1713 pagesInUse = bi->pagesInUse;
1717 dev->currentDirtyChecker = b;
1723 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
1725 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
1729 // If the block is still healthy erase it and mark as clean.
1730 // If the block has had a data failure, then retire it.
1731 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1733 if(!bi->needsRetiring)
1735 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
1738 T((TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
1744 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1745 dev->nErasedBlocks++;
1749 T((TSTR("Erased block %d" TENDSTR),blockNo));
1753 yaffs_RetireBlock(dev,blockNo);
1754 T((TSTR("**>> Block %d retired" TENDSTR),blockNo));
1759 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
1762 yaffs_BlockInfo *bi;
1764 if(dev->nErasedBlocks < 1)
1766 // Hoosterman we've got a problem.
1767 // Can't get space to gc
1771 // Find an empty block.
1773 for(i = dev->startBlock; i <= dev->endBlock; i++)
1775 bi = yaffs_GetBlockInfo(dev,i);
1776 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
1778 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1779 dev->nErasedBlocks--;
1789 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
1792 yaffs_BlockInfo *bi;
1794 if(dev->allocationBlock < 0)
1796 // Get next block to allocate off
1797 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
1798 dev->allocationPage = 0;
1801 if(!useReserve && dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
1803 // Not enough space to allocate unless we're allowed to use the reserve.
1807 // Next page please....
1808 if(dev->allocationBlock >= 0)
1810 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
1812 retVal = (dev->allocationBlock * YAFFS_CHUNKS_PER_BLOCK) +
1813 dev->allocationPage;
1815 bi->pageBits |= (1 << (dev->allocationPage));
1817 dev->allocationPage++;
1821 // If the block is full set the state to full
1822 if(dev->allocationPage >= YAFFS_CHUNKS_PER_BLOCK)
1824 bi->blockState = YAFFS_BLOCK_STATE_FULL;
1825 dev->allocationBlock = -1;
1832 T((TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
1838 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
1847 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
1849 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
1851 yaffs_Object *object;
1853 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
1855 for(mask = 1,oldChunk = block * YAFFS_CHUNKS_PER_BLOCK;
1856 mask && bi->pageBits;
1857 mask <<= 1, oldChunk++ )
1859 if(bi->pageBits & mask)
1862 // This page is in use and needs to be copied off
1866 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
1868 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
1870 yaffs_GetTagsFromSpare(&spare,&tags);
1871 tags.serialNumber++;
1872 yaffs_LoadTagsIntoSpare(&spare,&tags);
1875 newChunk = yaffs_AllocatePage(dev,1);
1881 yaffs_WriteChunkToNAND(dev,newChunk, buffer, &spare);
1884 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
1891 object = yaffs_FindObjectByNumber(dev,tags.objectId);
1893 // Ok, now fix up the Tnodes etc.
1895 if(tags.chunkId == 0)
1898 object->chunkId = newChunk;
1902 // It's a data chunk
1903 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
1907 yaffs_DeleteChunk(dev,oldChunk);
1916 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
1918 // todo find a file to delete
1919 struct list_head *i;
1923 // To the free chunks add the chunks that are in the deleted unlinked files.
1924 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
1926 l = list_entry(i, yaffs_Object,siblings);
1935 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
1937 // This does background deletion on unlinked files.. only deleted ones.
1938 // If we don't have a file we're working on then find one
1939 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
1941 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
1944 // OK, we're working on a file...
1945 if(dev->unlinkedDeletion)
1947 yaffs_Object *obj = dev->unlinkedDeletion;
1950 limit = 50; // Max number of chunks to delete in a file. NB this can be exceeded, but not by much.
1951 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
1953 if(obj->nDataChunks == 0)
1955 // Done all the deleting of data chunks.
1956 // Now dump the header and clean up
1957 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
1958 yaffs_DoGenericObjectDeletion(obj);
1959 dev->nDeletedFiles--;
1960 dev->nUnlinkedFiles--;
1961 dev->nBackgroundDeletions++;
1962 dev->unlinkedDeletion = NULL;
1967 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
1971 yaffs_DoUnlinkedFileDeletion(dev);
1973 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + YAFFS_GARBAGE_COLLECT_LOW_WATER))
1975 dev->garbageCollectionRequired = 1;
1978 if(dev->garbageCollectionRequired)
1980 dev->garbageCollections++;
1981 dev->garbageCollectionRequired = 0;
1982 if(dev->blockSelectedForGC >= 0)
1984 block = dev->blockSelectedForGC;
1988 block = yaffs_FindDirtiestBlock(dev);
1993 return yaffs_GarbageCollectBlock(dev,block);
2005 //////////////////////////// TAGS ///////////////////////////////////////
2007 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2009 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2011 yaffs_CalcTagsECC(tagsPtr);
2013 sparePtr->tagByte0 = tu->asBytes[0];
2014 sparePtr->tagByte1 = tu->asBytes[1];
2015 sparePtr->tagByte2 = tu->asBytes[2];
2016 sparePtr->tagByte3 = tu->asBytes[3];
2017 sparePtr->tagByte4 = tu->asBytes[4];
2018 sparePtr->tagByte5 = tu->asBytes[5];
2019 sparePtr->tagByte6 = tu->asBytes[6];
2020 sparePtr->tagByte7 = tu->asBytes[7];
2023 static void yaffs_GetTagsFromSpare(yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2025 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2027 tu->asBytes[0]= sparePtr->tagByte0;
2028 tu->asBytes[1]= sparePtr->tagByte1;
2029 tu->asBytes[2]= sparePtr->tagByte2;
2030 tu->asBytes[3]= sparePtr->tagByte3;
2031 tu->asBytes[4]= sparePtr->tagByte4;
2032 tu->asBytes[5]= sparePtr->tagByte5;
2033 tu->asBytes[6]= sparePtr->tagByte6;
2034 tu->asBytes[7]= sparePtr->tagByte7;
2036 yaffs_CheckECCOnTags(tagsPtr);
2039 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2041 memset(spare,0xFF,sizeof(yaffs_Spare));
2044 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2049 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2051 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2052 yaffs_GetTagsFromSpare(&spare,tags);
2065 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2067 // NB There must be tags, data is optional
2068 // If there is data, then an ECC is calculated on it.
2077 yaffs_SpareInitialise(&spare);
2082 yaffs_CalcECC(buffer,&spare);
2085 yaffs_LoadTagsIntoSpare(&spare,tags);
2087 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2093 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2095 // NB There must be tags, data is optional
2096 // If there is data, then an ECC is calculated on it.
2105 yaffs_SpareInitialise(&spare);
2110 yaffs_CalcECC(buffer,&spare);
2113 yaffs_LoadTagsIntoSpare(&spare,tags);
2115 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2119 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2121 return ( tags->chunkId == chunkInObject &&
2122 tags->objectId == objectId &&
2123 !chunkDeleted) ? 1 : 0;
2129 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2131 //Get the Tnode, then get the level 0 offset chunk offset
2134 yaffs_Tags localTags;
2139 yaffs_Device *dev = in->myDev;
2144 // Passed a NULL, so use our own tags space
2148 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2152 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2154 // Now we need to do the shifting etc and search for it
2155 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2157 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2158 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2169 return found ? theChunk : -1;
2172 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2174 //Get the Tnode, then get the level 0 offset chunk offset
2177 yaffs_Tags localTags;
2180 yaffs_Device *dev = in->myDev;
2185 // Passed a NULL, so use our own tags space
2189 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2194 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2196 // Now we need to do the shifting etc and search for it
2197 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2199 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2200 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2211 // Delete the entry in the filestructure
2214 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2219 //T(("No level 0 found for %d\n", chunkInInode));
2224 //T(("Could not find %d to delete\n",chunkInInode));
2226 return found ? theChunk : -1;
2232 static int yaffs_CheckFileSanity(yaffs_Object *in)
2240 yaffs_Tags localTags;
2241 yaffs_Tags *tags = &localTags;
2246 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2248 //T(("Object not a file\n"));
2252 objId = in->objectId;
2253 fSize = in->variant.fileVariant.fileSize;
2254 nChunks = (fSize + YAFFS_BYTES_PER_CHUNK -1)/YAFFS_BYTES_PER_CHUNK;
2256 for(chunk = 1; chunk <= nChunks; chunk++)
2258 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2263 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2266 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2267 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2274 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2275 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2284 //T(("No level 0 found for %d\n", chunk));
2288 return failed ? YAFFS_FAIL : YAFFS_OK;
2293 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2296 yaffs_Device *dev = in->myDev;
2298 yaffs_Tags existingTags;
2300 unsigned existingSerial, newSerial;
2302 int newChunkDeleted;
2305 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2311 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2315 // If we're scanning then we need to test for duplicates
2316 // NB This does not need to be efficient since it should only ever
2317 // happen when the power fails during a write, then only one
2318 // chunk should ever be affected.
2321 if(existingChunk != 0)
2323 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2324 // thus we have to do a FindChunkInFile to get the real chunk id.
2326 // We have a duplicate now we need to decide which one to use
2327 // To do this we get both sets of tags and compare serial numbers.
2328 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2332 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2334 if(existingChunk <=0)
2336 //Hoosterman - how did this happen?
2341 // NB The deleted flags should be false, otherwise the chunks will
2342 // not be loaded during a scan
2344 newSerial = newTags.serialNumber;
2345 existingSerial = existingTags.serialNumber;
2347 if( existingChunk <= 0 ||
2348 ((existingSerial+1) & 3) == newSerial)
2351 // Delete the old one and drop through to update the tnode
2352 yaffs_DeleteChunk(dev,existingChunk);
2357 // Delete the new one and return early so that the tnode isn't changed
2358 yaffs_DeleteChunk(dev,chunkInNAND);
2365 if(existingChunk == 0)
2370 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2377 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2379 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2381 if(chunkInNAND >= 0)
2383 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2393 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId)
2398 yaffs_BlockInfo *bi;
2400 if(chunkId <= 0) return;
2402 block = chunkId / YAFFS_CHUNKS_PER_BLOCK;
2403 page = chunkId % YAFFS_CHUNKS_PER_BLOCK;
2404 yaffs_SpareInitialise(&spare);
2406 spare.pageStatus = 0; // To mark it as deleted.
2409 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2410 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2411 bi = yaffs_GetBlockInfo(dev,block);
2414 // Pull out of the management area.
2415 // If the whole block became dirty, this will kick off an erasure.
2416 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2417 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2421 bi->pageBits &= ~(1 << page);
2424 if(bi->pagesInUse == 0 &&
2425 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2427 yaffs_BlockBecameDirty(dev,block);
2433 // T(("Bad news deleting chunk %d\n",chunkId));
2441 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2443 // Find old chunk Need to do this to get serial number
2444 // Write new one and patch into tree.
2445 // Invalidate old tags.
2448 yaffs_Tags prevTags;
2453 yaffs_Device *dev = in->myDev;
2455 yaffs_CheckGarbageCollection(dev);
2457 // Get the previous chunk at this location in the file if it exists
2458 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2461 newTags.chunkId = chunkInInode;
2462 newTags.objectId = in->objectId;
2463 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2464 newTags.byteCount = nBytes;
2465 newTags.unusedStuff = 0xFFFFFFFF;
2467 yaffs_CalcTagsECC(&newTags);
2471 // Create new chunk in NAND
2472 newChunkId = yaffs_AllocatePage(dev,useReserve);
2479 yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,buffer,&newTags);
2481 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId);
2484 if(prevChunkId >= 0)
2486 yaffs_DeleteChunk(dev,prevChunkId);
2490 yaffs_CheckFileSanity(in);
2499 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2502 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2505 if(prevChunkId >= 0)
2507 yaffs_DeleteChunk(dev,prevChunkId);
2511 yaffs_CheckFileSanity(in);
2522 // UpdateObjectHeader updates the header on NAND for an object.
2523 // If name is not NULL, then that new name is used.
2525 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2528 yaffs_Device *dev = in->myDev;
2534 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2535 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2537 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2538 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2540 yaffs_INVALIDATECHUNKCACHE(in);
2542 if(!in->fake || force)
2545 yaffs_CheckGarbageCollection(dev);
2547 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2549 prevChunkId = in->chunkId;
2551 if(prevChunkId >= 0)
2553 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2557 oh->type = in->variantType;
2559 oh->st_mode = in->st_mode;
2560 oh->st_uid = in->st_uid;
2561 oh->st_gid = in->st_gid;
2562 oh->st_atime = in->st_atime;
2563 oh->st_mtime = in->st_mtime;
2564 oh->st_ctime = in->st_ctime;
2565 oh->st_rdev = in->st_rdev;
2569 oh->parentObjectId = in->parent->objectId;
2573 oh->parentObjectId = 0;
2579 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2580 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
2582 else if(prevChunkId)
2584 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
2588 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2591 switch(in->variantType)
2593 case YAFFS_OBJECT_TYPE_UNKNOWN:
2594 // Should not happen
2596 case YAFFS_OBJECT_TYPE_FILE:
2597 oh->fileSize = in->variant.fileVariant.fileSize;
2599 case YAFFS_OBJECT_TYPE_HARDLINK:
2600 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
2602 case YAFFS_OBJECT_TYPE_SPECIAL:
2605 case YAFFS_OBJECT_TYPE_DIRECTORY:
2608 case YAFFS_OBJECT_TYPE_SYMLINK:
2609 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
2610 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2616 newTags.chunkId = 0;
2617 newTags.objectId = in->objectId;
2618 newTags.serialNumber = in->serial;
2619 newTags.byteCount = 0xFFFFFFFF;
2620 newTags.unusedStuff = 0xFFFFFFFF;
2622 yaffs_CalcTagsECC(&newTags);
2627 // Create new chunk in NAND
2628 newChunkId = yaffs_AllocatePage(dev,1);
2633 yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,bufferNew,&newTags);
2635 in->chunkId = newChunkId;
2637 if(prevChunkId >= 0)
2639 yaffs_DeleteChunk(dev,prevChunkId);
2648 // Create new chunk in NAND
2649 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags,1);
2654 in->chunkId = newChunkId;
2656 if(prevChunkId >= 0)
2658 yaffs_DeleteChunk(dev,prevChunkId);
2672 /////////////////////// Short Read Cache ////////////////////////////////
2673 // In many siturations where there is no high level buffering a lot of
2674 // reads might be short sequential reads. eg. scanning a jpeg file.
2675 // In these cases, a shoprt read cache can provide a huge perfomance benefit
2676 // with dumb-as-a-rock code.
2677 // There are a limited number (~10) of cache chunks per device
2680 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2682 // Invalidate all the cache pages associated with this object
2683 // Do this whenever ther file is modified... dumb as a rock remember!
2684 static void yaffs_InvalidateChunkCache(yaffs_Object *in)
2687 yaffs_Device *dev = in->myDev;
2688 int id = in->objectId;
2690 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2692 if(dev->srCache[i].objectId == id)
2694 dev->srCache[i].objectId = 0;
2700 // Grab us a chunk for use.
2701 // First look for an empty one.
2702 // Then look for the least recently used one.
2703 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
2709 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2711 if(dev->srCache[i].objectId == 0)
2713 //T(("Grabbing empty %d\n",i));
2715 return &dev->srCache[i];
2720 usage = dev->srCache[i].lastUse;
2723 for(i = 1; i < YAFFS_N_CACHE_CHUNKS; i++)
2725 if(dev->srCache[i].lastUse < usage)
2727 usage = dev->srCache[i].lastUse;
2732 //T(("Grabbing non-empty %d\n",theOne));
2733 return &dev->srCache[theOne];
2738 // Find a cached chunk
2739 static yaffs_ChunkCache *yaffs_FindChunkCache(yaffs_Device *dev, int objectId, int chunkId)
2744 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2746 if(dev->srCache[i].objectId == objectId &&
2747 dev->srCache[i].chunkId == chunkId)
2751 return &dev->srCache[i];
2758 // Mark the chunk for the least recently used algorithym
2759 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache)
2761 if( dev->srLastUse < 0 ||
2762 dev->srLastUse > 1000000)
2764 // Reset the cache usages
2766 for(i = 1; i < YAFFS_N_CACHE_CHUNKS; i++)
2768 dev->srCache[i].lastUse = 0;
2775 cache->lastUse = dev->srLastUse;
2785 ///////////////////////// File read/write ///////////////////////////////
2786 // Read and write have very similar structures.
2787 // In general the read/write has three parts to it
2788 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
2789 // * Some complete chunks
2790 // * An incomplete chunk to end off with
2792 // Curve-balls: the first chunk might also be the last chunk.
2794 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
2797 // yaffs_Device *dev = in->myDev;
2799 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2800 yaffs_ChunkCache *cache;
2802 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2813 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
2814 start = offset % YAFFS_BYTES_PER_CHUNK;
2816 // OK now check for the curveball where the start and end are in
2818 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
2824 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
2827 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
2829 // An incomplete start or end chunk (or maybe both start and end chunk)
2830 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2831 // If we can't find the data in the cache, then load it up.
2832 cache = yaffs_FindChunkCache(in->myDev,in->objectId,chunk);
2835 cache = yaffs_GrabChunkCache(in->myDev);
2836 cache->objectId = in->objectId;
2837 cache->chunkId = chunk;
2838 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
2841 yaffs_UseChunkCache(in->myDev,cache);
2843 memcpy(buffer,&cache->data[start],nToCopy);
2845 // Read into the local buffer then copy...
2846 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2847 memcpy(buffer,&localBuffer[start],nToCopy);
2852 // A full chunk. Read directly into the supplied buffer.
2853 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
2867 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
2869 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2877 int endOfWrite = offset+nBytes;
2878 int chunkWritten = 0;
2880 yaffs_INVALIDATECHUNKCACHE(in);
2882 while(n > 0 && chunkWritten >= 0)
2884 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
2885 start = offset % YAFFS_BYTES_PER_CHUNK;
2888 // OK now check for the curveball where the start and end are in
2890 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
2893 nToWriteBack = (start + n);
2897 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
2898 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
2901 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
2903 // An incomplete start or end chunk (or maybe both start and end chunk)
2904 // Read into the local buffer then copy, then copy over and write back.
2906 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2908 memcpy(&localBuffer[start],buffer,nToCopy);
2910 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,nToWriteBack,0);
2912 //T(("Write with readback to chunk %d %d\n",chunk,chunkWritten));
2917 // A full chunk. Write directly from the supplied buffer.
2918 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
2919 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
2922 if(chunkWritten >= 0)
2932 // Update file object
2934 if(endOfWrite > in->variant.fileVariant.fileSize)
2936 in->variant.fileVariant.fileSize = endOfWrite;
2940 /*in->st_mtime = CURRENT_TIME; only update in flush*/
2946 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
2950 int oldFileSize = in->variant.fileVariant.fileSize;
2951 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
2953 yaffs_Device *dev = in->myDev;
2955 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2957 yaffs_INVALIDATECHUNKCACHE(in);
2959 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2961 return yaffs_GetFileSize(in);
2964 if(newSize < oldFileSize)
2967 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
2969 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
2970 YAFFS_BYTES_PER_CHUNK;
2972 // Delete backwards so that we don't end up with holes if
2973 // power is lost part-way through the operation.
2974 for(i = lastDel; i >= startDel; i--)
2976 // NB this could be optimised somewhat,
2977 // eg. could retrieve the tags and write them without
2978 // using yaffs_DeleteChunk
2980 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
2981 if(chunkId <= 0 || chunkId >= (dev->endBlock * 32))
2983 //T(("Found daft chunkId %d for %d\n",chunkId,i));
2988 yaffs_DeleteChunk(dev,chunkId);
2993 if(sizeOfPartialChunk != 0)
2995 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
2997 // Got to read and rewrite the last chunk with its new size.
2998 yaffs_ReadChunkDataFromObject(in,lastChunk,localBuffer);
3000 yaffs_WriteChunkDataToObject(in,lastChunk,localBuffer,sizeOfPartialChunk,1);
3004 in->variant.fileVariant.fileSize = newSize;
3006 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3018 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3020 obj = yaffs_GetEquivalentObject(obj);
3022 switch(obj->variantType)
3024 case YAFFS_OBJECT_TYPE_FILE:
3025 return obj->variant.fileVariant.fileSize;
3026 case YAFFS_OBJECT_TYPE_SYMLINK:
3027 return strlen(obj->variant.symLinkVariant.alias);
3035 // yaffs_FlushFile() updates the file's
3038 int yaffs_FlushFile(yaffs_Object *in)
3043 //T(("flushing object header\n"));
3045 in->st_mtime = CURRENT_TIME;
3047 retVal = yaffs_UpdateObjectHeader(in,NULL,0);
3059 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3061 yaffs_INVALIDATECHUNKCACHE(in);
3062 yaffs_RemoveObjectFromDirectory(in);
3063 yaffs_DeleteChunk(in->myDev,in->chunkId);
3067 in->myInode->u.generic_ip = NULL;
3071 yaffs_FreeObject(in);
3076 // yaffs_DeleteFile deletes the whole file data
3077 // and the inode associated with the file.
3078 // It does not delete the links associated with the file.
3079 static int yaffs_UnlinkFile(yaffs_Object *in)
3082 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3083 // Delete the file data & tnodes
3085 yaffs_ResizeFile(in,0);
3087 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3091 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3093 return yaffs_DoGenericObjectDeletion(in);
3096 int immediateDeletion=0;
3097 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL);
3098 if(retVal == YAFFS_OK)
3101 //in->myDev->nUnlinkedFiles++;
3102 //in->renameAllowed = 0;
3106 immediateDeletion = 1;
3113 immediateDeletion = 1;
3118 if(immediateDeletion)
3120 T((TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3122 in->myDev->nDeletedFiles++;
3132 int yaffs_DeleteFile(yaffs_Object *in)
3134 int retVal = YAFFS_OK;
3137 retVal = yaffs_UnlinkFile(in);
3139 if(retVal == YAFFS_OK &&
3144 in->myDev->nDeletedFiles++;
3146 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3149 static int yaffs_DeleteDirectory(yaffs_Object *in)
3151 //First check that the directory is empty.
3152 if(list_empty(&in->variant.directoryVariant.children))
3154 return yaffs_DoGenericObjectDeletion(in);
3161 static int yaffs_DeleteSymLink(yaffs_Object *in)
3163 YFREE(in->variant.symLinkVariant.alias);
3165 return yaffs_DoGenericObjectDeletion(in);
3168 static int yaffs_DeleteHardLink(yaffs_Object *in)
3170 // remove this hardlink from the list assocaited with the equivalent
3172 list_del(&in->hardLinks);
3173 return yaffs_DoGenericObjectDeletion(in);
3177 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3181 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3183 return yaffs_DeleteHardLink(obj);
3185 else if(!list_empty(&obj->hardLinks))
3188 // Curve ball: We're unlinking an object that has a hardlink.
3189 // Therefore we can't really delete the object.
3190 // Instead, we do the following:
3191 // - Select a hardlink.
3192 // - Re-type a hardlink as the equivalent object and populate the fields, including the
3193 // objectId. Updating the object id is important so that all the hardlinks do not need
3195 // - Update the equivalet object pointers.
3196 // - Delete all object.
3199 struct list_head *i;
3202 yaffs_RemoveObjectFromDirectory(obj);
3206 hl = list_entry(obj->hardLinks.next, yaffs_Object,hardLinks);
3209 hl->st_mode = obj->st_mode;
3210 hl->st_uid = obj->st_uid;
3211 hl->st_gid = obj->st_gid;
3212 hl->st_atime = obj->st_atime;
3213 hl->st_mtime = obj->st_mtime;
3214 hl->st_ctime = obj->st_ctime;
3215 hl->st_rdev = obj->st_rdev;
3217 hl->variantType = obj->variantType;
3219 switch(hl->variantType)
3221 case YAFFS_OBJECT_TYPE_FILE:
3222 case YAFFS_OBJECT_TYPE_SYMLINK:
3223 case YAFFS_OBJECT_TYPE_SPECIAL:
3224 // These types are OK to just copy across.
3225 hl->variant = obj->variant;
3227 case YAFFS_OBJECT_TYPE_DIRECTORY:
3229 list_add(&hl->variant.directoryVariant.children,
3230 &obj->variant.directoryVariant.children);
3231 list_del(&obj->variant.directoryVariant.children);
3233 // Now change all the directory children to point to the new parent.
3234 list_for_each(i,&hl->variant.directoryVariant.children)
3236 list_entry(i,yaffs_Object,siblings)->parent = hl;
3240 case YAFFS_OBJECT_TYPE_HARDLINK:
3241 case YAFFS_OBJECT_TYPE_UNKNOWN:
3242 // Should not be either of these types.
3245 // Now fix up the hardlink chain
3246 list_del(&obj->hardLinks);
3248 list_for_each(i,&hl->hardLinks)
3250 list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObject = hl;
3251 list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObjectId = hl->objectId;
3254 // Now fix up the hash links.
3255 yaffs_UnhashObject(hl);
3256 hl->objectId = obj->objectId;
3257 yaffs_HashObject(hl);
3259 // Update the hardlink which has become an object
3260 yaffs_UpdateObjectHeader(hl,NULL,0);
3262 // Finally throw away the deleted object
3263 yaffs_DeleteChunk(obj->myDev,obj->chunkId);
3264 yaffs_FreeObject(obj);
3268 // Curve ball: We're unlinking an object that has a hardlink.
3270 // This problem arises because we are not strictly following
3271 // The Linux link/inode model.
3273 // We can't really delete the object.
3274 // Instead, we do the following:
3275 // - Select a hardlink.
3276 // - Unhook it from the hard links
3277 // - Unhook it from its parent directory (so that the rename can work)
3278 // - Rename the object to the hardlink's name.
3279 // - Delete the hardlink
3284 char name[YAFFS_MAX_NAME_LENGTH+1];
3286 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3288 list_del_init(&hl->hardLinks);
3289 list_del_init(&hl->siblings);
3291 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3293 retVal = yaffs_ChangeObjectName(obj, hl->parent, name);
3295 if(retVal == YAFFS_OK)
3297 retVal = yaffs_DoGenericObjectDeletion(hl);
3307 switch(obj->variantType)
3309 case YAFFS_OBJECT_TYPE_FILE:
3310 return yaffs_UnlinkFile(obj);
3312 case YAFFS_OBJECT_TYPE_DIRECTORY:
3313 return yaffs_DeleteDirectory(obj);
3315 case YAFFS_OBJECT_TYPE_SYMLINK:
3316 return yaffs_DeleteSymLink(obj);
3318 case YAFFS_OBJECT_TYPE_HARDLINK:
3319 case YAFFS_OBJECT_TYPE_UNKNOWN:
3326 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3330 obj = yaffs_FindObjectByName(dir,name);
3332 if(obj && obj->unlinkAllowed)
3334 return yaffs_UnlinkWorker(obj);
3341 //////////////// Initialisation Scanning /////////////////
3345 // For now we use the SmartMedia check.
3346 // We look at the blockStatus byte in the first two chunks
3347 // These must be 0xFF to pass as OK.
3348 // todo: this function needs to be modifyable foir different NAND types
3349 // and different chunk sizes. Suggest make this into a per-device configurable
3351 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3355 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK,NULL,&spare,1);
3357 if(yaffs_CountBits(spare.blockStatus) < 7)
3362 if(spare.blockStatus != 0xFF)
3367 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK + 1,NULL,&spare,1);
3370 if(yaffs_CountBits(spare.blockStatus) < 7)
3375 if(spare.blockStatus != 0xFF)
3385 static int yaffs_Scan(yaffs_Device *dev)
3393 yaffs_BlockState state;
3394 yaffs_Object *hardList = NULL;
3396 yaffs_BlockInfo *bi;
3399 yaffs_ObjectHeader *oh;
3401 yaffs_Object *parent;
3403 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
3406 // Scan all the blocks...
3408 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
3411 bi = yaffs_GetBlockInfo(dev,blk);
3414 state = YAFFS_BLOCK_STATE_SCANNING;
3417 if(yaffs_IsBlockBad(dev,blk))
3419 state = YAFFS_BLOCK_STATE_DEAD;
3420 T((TSTR("block %d is bad" TENDSTR),blk));
3423 // Read each chunk in the block.
3425 for(c = 0; c < YAFFS_CHUNKS_PER_BLOCK &&
3426 state == YAFFS_BLOCK_STATE_SCANNING; c++)
3428 // Read the spare area and decide what to do
3429 chunk = blk * YAFFS_CHUNKS_PER_BLOCK + c;
3431 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
3434 // This block looks ok, now what's in this chunk?
3435 yaffs_GetTagsFromSpare(&spare,&tags);
3437 if(yaffs_CountBits(spare.pageStatus) < 6)
3441 dev->nFreeChunks ++;
3442 //T((" %d %d deleted\n",blk,c));
3444 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
3446 // An unassigned chunk in the block
3447 // This means that either the block is empty or
3448 // this is the one being allocated from
3452 // the block is unused
3453 state = YAFFS_BLOCK_STATE_EMPTY;
3454 dev->nErasedBlocks++;
3458 // this is the block being allocated from
3459 T((TSTR(" Allocating from %d %d" TENDSTR),blk,c));
3460 state = YAFFS_BLOCK_STATE_ALLOCATING;
3461 dev->allocationBlock = blk;
3462 dev->allocationPage = c;
3465 dev->nFreeChunks += (YAFFS_CHUNKS_PER_BLOCK - c);
3467 else if(tags.chunkId > 0)
3471 bi->pageBits |= (1 << c);
3474 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
3475 // PutChunkIntoFIle checks for a clash (two data chunks with
3476 // the same chunkId).
3477 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
3478 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
3479 if(in->variant.fileVariant.scannedFileSize <endpos)
3481 in->variant.fileVariant.scannedFileSize = endpos;
3482 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3483 in->variant.fileVariant.fileSize =
3484 in->variant.fileVariant.scannedFileSize;
3488 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
3492 // chunkId == 0, so it is an ObjectHeader.
3493 // Thus, we read in the object header and make the object
3494 bi->pageBits |= (1 << c);
3497 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
3499 oh = (yaffs_ObjectHeader *)chunkData;
3501 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
3505 // We have already filled this one. We have a duplicate and need to resolve it.
3507 unsigned existingSerial = in->serial;
3508 unsigned newSerial = tags.serialNumber;
3510 if(((existingSerial+1) & 3) == newSerial)
3512 // Use new one - destroy the exisiting one
3513 yaffs_DeleteChunk(dev,in->chunkId);
3518 // Use existing - destroy this one.
3519 yaffs_DeleteChunk(dev,chunk);
3524 (tags.objectId == YAFFS_OBJECTID_ROOT ||
3525 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
3527 // We only load some info, don't fiddle with directory structure
3529 in->variantType = oh->type;
3531 in->st_mode = oh->st_mode;
3532 in->st_uid = oh->st_uid;
3533 in->st_gid = oh->st_gid;
3534 in->st_atime = oh->st_atime;
3535 in->st_mtime = oh->st_mtime;
3536 in->st_ctime = oh->st_ctime;
3537 in->st_rdev = oh->st_rdev;
3538 in->chunkId = chunk;
3543 // we need to load this info
3546 in->variantType = oh->type;
3548 in->st_mode = oh->st_mode;
3549 in->st_uid = oh->st_uid;
3550 in->st_gid = oh->st_gid;
3551 in->st_atime = oh->st_atime;
3552 in->st_mtime = oh->st_mtime;
3553 in->st_ctime = oh->st_ctime;
3554 in->st_rdev = oh->st_rdev;
3555 in->chunkId = chunk;
3560 // directory stuff...
3561 // hook up to parent
3563 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
3564 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
3566 // Set up as a directory
3567 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
3568 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
3570 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
3572 // Hoosterman, another problem....
3573 // We're trying to use a non-directory as a directory
3577 yaffs_AddObjectToDirectory(parent,in);
3578 if(parent == dev->unlinkedDir)
3580 in->deleted = 1; // If it is unlinked at start up then it wants deleting
3581 dev->nDeletedFiles++;
3584 // Note re hardlinks.
3585 // Since we might scan a hardlink before its equivalent object is scanned
3586 // we put them all in a list.
3587 // After scanning is complete, we should have all the objects, so we run through this
3588 // list and fix up all the chains.
3590 switch(in->variantType)
3592 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
3594 case YAFFS_OBJECT_TYPE_FILE:
3595 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3596 in->variant.fileVariant.fileSize = oh->fileSize;
3599 case YAFFS_OBJECT_TYPE_HARDLINK:
3600 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
3601 (yaffs_Object *)(in->hardLinks.next) = hardList;
3604 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
3606 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
3608 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
3609 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
3612 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
3617 if(state == YAFFS_BLOCK_STATE_SCANNING)
3619 // If we got this far while scanning, then the block is fully allocated.
3620 state = YAFFS_BLOCK_STATE_FULL;
3623 bi->blockState = state;
3625 // Now let's see if it was dirty
3626 if( bi->pagesInUse == 0 &&
3627 bi->blockState == YAFFS_BLOCK_STATE_FULL)
3629 yaffs_BlockBecameDirty(dev,blk);
3634 // Fix up the hard link chains.
3635 // We should now have scanned all the objects, now it's time to add these
3640 hardList = (yaffs_Object *)(hardList->hardLinks.next);
3642 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
3646 // Add the hardlink pointers
3647 hl->variant.hardLinkVariant.equivalentObject=in;
3648 list_add(&hl->hardLinks,&in->hardLinks);
3652 //Todo Need to report/handle this better.
3653 // Got a problem... hardlink to a non-existant object
3654 hl->variant.hardLinkVariant.equivalentObject=NULL;
3655 INIT_LIST_HEAD(&hl->hardLinks);
3667 ////////////////////////// Directory Functions /////////////////////////
3670 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
3673 if(obj->siblings.prev == NULL)
3676 INIT_LIST_HEAD(&obj->siblings);
3679 else if(!list_empty(&obj->siblings))
3681 // If it is holed up somewhere else, un hook it
3682 list_del_init(&obj->siblings);
3685 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
3686 obj->parent = directory;
3688 if(directory == obj->myDev->unlinkedDir)
3691 obj->myDev->nUnlinkedFiles++;
3692 obj->renameAllowed = 0;
3696 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
3698 list_del_init(&obj->siblings);
3702 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
3706 struct list_head *i;
3707 char buffer[YAFFS_MAX_NAME_LENGTH+1];
3711 sum = yaffs_CalcNameSum(name);
3713 list_for_each(i,&directory->variant.directoryVariant.children)
3715 l = list_entry(i, yaffs_Object,siblings);
3717 // Special case for lost-n-found
3718 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
3720 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
3725 else if(yaffs_SumCompare(l->sum, sum))
3728 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
3729 if(yaffs_strcmp(name,buffer) == 0)
3742 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
3744 struct list_head *i;
3748 list_for_each(i,&theDir->variant.directoryVariant.children)
3750 l = list_entry(i, yaffs_Object,siblings);
3762 // GetEquivalentObject dereferences any hard links to get to the
3765 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
3767 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3769 // We want the object id of the equivalent object, not this one
3770 obj = obj->variant.hardLinkVariant.equivalentObject;
3776 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
3778 memset(name,0,buffSize);
3780 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
3782 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
3784 else if(obj->chunkId <= 0)
3788 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
3789 strncpy(name,locName,buffSize - 1);
3794 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
3795 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
3797 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
3799 if(obj->chunkId >= 0)
3801 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
3803 strncpy(name,oh->name,buffSize - 1);
3806 return strlen(name);
3809 int yaffs_GetObjectFileLength(yaffs_Object *obj)
3812 // Dereference any hard linking
3813 obj = yaffs_GetEquivalentObject(obj);
3815 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3817 return obj->variant.fileVariant.fileSize;
3819 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
3821 return strlen(obj->variant.symLinkVariant.alias);
3825 // Only a directory should drop through to here
3826 return YAFFS_BYTES_PER_CHUNK;
3830 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
3833 struct list_head *i;
3837 count++; // the object itself
3839 list_for_each(i,&obj->hardLinks)
3841 count++; // add the hard links;
3848 int yaffs_GetObjectInode(yaffs_Object *obj)
3850 obj = yaffs_GetEquivalentObject(obj);
3852 return obj->objectId;
3855 unsigned yaffs_GetObjectType(yaffs_Object *obj)
3857 obj = yaffs_GetEquivalentObject(obj);
3859 switch(obj->variantType)
3861 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
3862 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
3863 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
3864 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
3865 case YAFFS_OBJECT_TYPE_SPECIAL:
3866 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
3867 if(S_ISCHR(obj->st_mode)) return DT_CHR;
3868 if(S_ISBLK(obj->st_mode)) return DT_BLK;
3869 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
3870 default: return DT_REG; break;
3874 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
3876 obj = yaffs_GetEquivalentObject(obj);
3877 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
3879 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
3883 return yaffs_CloneString("");
3888 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
3890 unsigned int valid = attr->ia_valid;
3892 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
3893 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
3894 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
3896 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
3897 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
3898 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
3900 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
3902 yaffs_UpdateObjectHeader(obj,NULL,1);
3907 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
3909 unsigned int valid = 0;
3911 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
3912 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
3913 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
3915 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
3916 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
3917 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
3919 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
3921 attr->ia_valid = valid;
3929 int yaffs_DumpObject(yaffs_Object *obj)
3931 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
3933 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
3935 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
3937 // if(obj->chunkId >= 0)
3939 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
3942 yaffs_GetObjectName(obj,name,256);
3944 YPRINTF(("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d type %d size %d\n",
3945 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
3946 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
3949 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
3950 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
3951 obj->sum, obj->chunkId));
3952 switch(obj->variantType)
3954 case YAFFS_OBJECT_TYPE_FILE:
3955 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
3957 case YAFFS_OBJECT_TYPE_DIRECTORY:
3958 YPRINTF((" DIRECTORY\n"));
3960 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
3961 case YAFFS_OBJECT_TYPE_SYMLINK:
3962 case YAFFS_OBJECT_TYPE_UNKNOWN:
3971 ///////////////////////// Initialisation code ///////////////////////////
3975 int yaffs_GutsInitialise(yaffs_Device *dev)
3984 if(!yaffs_CheckStructures())
3986 YPRINTF(("yaffs_CheckStructures failed\n"));
3990 if(dev->startBlock <= 0 ||
3991 (dev->endBlock - dev->startBlock) < 10)
3993 YPRINTF(("startBlock %d or endBlock %d invalid\n",
3994 dev->startBlock, dev->endBlock));
3998 nBlocks = dev->endBlock - dev->startBlock + 1;
4002 // OK now calculate a few things for the device
4003 // Calculate chunkGroupBits.
4004 // We need to find the next power of 2 > than endBlock
4006 x = YAFFS_CHUNKS_PER_BLOCK * (dev->endBlock+1);
4008 for(bits = extraBits = 0; x > 1; bits++)
4010 if(x & 1) extraBits++;
4014 if(extraBits > 0) bits++;
4017 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4018 // chunk range we're using is greater than 16 we need
4019 // to figure out chunk shift and chunkGroupSize
4022 dev->chunkGroupBits = 0;
4026 dev->chunkGroupBits = bits - 16;
4028 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4031 // More device initialisation
4032 dev->garbageCollectionRequired = 0;
4033 dev->garbageCollections = 0;
4034 dev->currentDirtyChecker = 0;
4035 dev->bufferedBlock = -1;
4036 dev->doingBufferedBlockRewrite = 0;
4037 dev->blockSelectedForGC = -1;
4038 dev->nDeletedFiles = 0;
4039 dev->nBackgroundDeletions=0;
4040 dev->nUnlinkedFiles = 0;
4042 yaffs_InitialiseBlocks(dev,nBlocks);
4044 yaffs_InitialiseTnodes(dev);
4046 yaffs_InitialiseObjects(dev);
4048 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
4051 for(i=0; i < YAFFS_N_CACHE_CHUNKS; i++)
4053 dev->srCache[i].objectId = 0;
4054 dev->srCache[i].lastUse = 0;
4063 // Initialise the unlinked, root and lost and found directories
4064 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4066 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4068 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4069 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4070 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4073 // Now scan the flash.
4077 dev->nPageReads = 0;
4078 dev->nPageWrites = 0;
4079 dev->nBlockErasures = 0;
4081 dev->nRetriedWrites = 0;
4082 dev->nRetiredBlocks = 0;
4089 void yaffs_Deinitialise(yaffs_Device *dev)
4091 yaffs_DeinitialiseBlocks(dev);
4092 yaffs_DeinitialiseTnodes(dev);
4093 yaffs_DeinitialiseObjects(dev);
4097 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4099 int nFree = dev->nFreeChunks - (YAFFS_CHUNKS_PER_BLOCK * YAFFS_RESERVED_BLOCKS);
4101 struct list_head *i;
4105 // To the free chunks add the chunks that are in the deleted unlinked files.
4106 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4108 l = list_entry(i, yaffs_Object,siblings);
4112 nFree += l->nDataChunks;
4117 return (nFree < 0) ? 0 : nFree;
4122 /////////////////// YAFFS test code //////////////////////////////////
4124 #define yaffs_CheckStruct(structure,syze, name) \
4125 if(sizeof(structure) != syze) \
4126 { YPRINTF(("%s should be %d but is %d\n",name,syze,sizeof(structure))); \
4127 return YAFFS_FAIL; \
4131 static int yaffs_CheckStructures(void)
4133 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4134 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4135 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4136 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4137 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4143 void yaffs_GutsTest(yaffs_Device *dev)
4146 if(yaffs_CheckStructures() != YAFFS_OK)
4148 YPRINTF(("One or more structures malformed-- aborting\n"));
4153 YPRINTF(("Structures OK\n"));
4156 yaffs_TnodeTest(dev);
4157 yaffs_ObjectTest(dev);