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.17 2003-01-17 04:19:08 charles Exp $";
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
27 #define YAFFS_PASSIVE_GC_CHUNKS 2
29 // External functions for ECC on data
30 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
31 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
34 // countBits is a quick way of counting the number of bits in a byte.
35 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
37 static const char yaffs_countBitsTable[256] =
39 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
40 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
41 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
42 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
43 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
44 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
45 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
46 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
47 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
48 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
49 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
50 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
51 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
52 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
53 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
54 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
57 static int yaffs_CountBits(__u8 x)
60 retVal = yaffs_countBitsTable[x];
67 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
68 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
69 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
70 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
72 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
73 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
74 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force);
75 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND);
76 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
77 static int yaffs_CheckStructures(void);
78 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
84 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
85 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
86 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
87 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare);
88 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare);
90 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
92 static int yaffs_UnlinkWorker(yaffs_Object *obj);
93 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj);
95 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1);
99 loff_t yaffs_GetFileSize(yaffs_Object *obj);
101 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
102 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
105 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
107 #ifdef YAFFS_PARANOID
108 static int yaffs_CheckFileSanity(yaffs_Object *in);
110 #define yaffs_CheckFileSanity(in)
113 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
114 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
116 // Chunk bitmap manipulations
118 static __inline __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
120 if(blk < dev->startBlock || blk > dev->endBlock)
122 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
125 return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->startBlock));
128 static __inline__ void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
130 __u8 *blkBits = yaffs_BlockBits(dev,blk);
132 memset(blkBits,0,dev->chunkBitmapStride);
135 static __inline__ void yaffs_ClearChunkBit(yaffs_Device *dev,int blk,int chunk)
137 __u8 *blkBits = yaffs_BlockBits(dev,blk);
139 blkBits[chunk/8] &= ~ (1<<(chunk & 7));
142 static __inline__ void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
144 __u8 *blkBits = yaffs_BlockBits(dev,blk);
146 blkBits[chunk/8] |= (1<<(chunk & 7));
149 static __inline__ int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
151 __u8 *blkBits = yaffs_BlockBits(dev,blk);
152 return (blkBits[chunk/8] & (1<<(chunk & 7))) ? 1 :0;
155 static __inline__ int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
157 __u8 *blkBits = yaffs_BlockBits(dev,blk);
159 for(i = 0; i < dev->chunkBitmapStride; i++)
161 if(*blkBits) return 1;
167 // Function to manipulate block info
168 static __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
170 if(blk < dev->startBlock || blk > dev->endBlock)
172 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),blk));
175 return &dev->blockInfo[blk - dev->startBlock];
179 static __inline__ int yaffs_HashFunction(int n)
181 return (n % YAFFS_NOBJECT_BUCKETS);
185 yaffs_Object *yaffs_Root(yaffs_Device *dev)
190 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
192 return dev->lostNFoundDir;
196 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
198 if(chunkInNAND < dev->startBlock * dev->nChunksPerBlock)
200 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
205 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
210 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
214 int doErrorCorrection)
217 yaffs_Spare localSpare;
220 int eccResult1,eccResult2;
221 struct yaffs_NANDSpare nspare;
230 // If we don't have a real spare, then we use a local one.
231 // Need this for the calculation of the ecc
238 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
239 if(data && doErrorCorrection)
242 //Todo handle any errors
243 nand_calculate_ecc(data,calcEcc);
244 eccResult1 = nand_correct_data (data,spare->ecc1, calcEcc);
245 nand_calculate_ecc(&data[256],calcEcc);
246 eccResult2 = nand_correct_data (&data[256],spare->ecc2, calcEcc);
250 T(YAFFS_TRACE_ERROR, (TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
253 else if(eccResult1<0)
255 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
261 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
264 else if(eccResult2<0)
266 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
270 if(eccResult1 || eccResult2)
272 // Hoosterman, we had a data problem on this page
273 yaffs_HandleReadDataError(dev,chunkInNAND);
279 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
280 memcpy (spare, &nspare, sizeof(yaffs_Spare));
281 if(data && doErrorCorrection)
285 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
287 else if(nspare.eccres1<0)
289 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
294 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
296 else if(nspare.eccres2<0)
298 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
301 if(nspare.eccres2 || nspare.eccres2)
303 // Hoosterman, we had a data problem on this page
304 yaffs_HandleReadDataError(dev,chunkInNAND);
313 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
317 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
318 static __u8 data[YAFFS_BYTES_PER_CHUNK];
319 static __u8 spare[16];
322 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
328 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
332 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL;
333 if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
342 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
344 dev->nBlockErasures++;
345 return dev->eraseBlockInNAND(dev,blockInNAND);
348 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
350 return dev->initialiseNAND(dev);
353 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
360 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
364 chunk = yaffs_AllocateChunk(dev,useReserve);
369 // First check this chunk is erased...
370 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
371 writeOk = yaffs_CheckChunkErased(dev,chunk);
375 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
379 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
385 // If verify fails, then delete this chunk and try again
386 // To verify we compare everything except the block and
387 // page status bytes.
388 // NB We check a raw read without ECC correction applied
389 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
391 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
392 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
395 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
404 // Copy the data into the write buffer.
405 // NB We do this at the end to prevent duplicates in the case of a write error.
407 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
411 yaffs_HandleWriteChunkError(dev,chunk);
415 } while(chunk >= 0 && ! writeOk);
419 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
420 dev->nRetriedWrites+= (attempts - 1);
427 // Functions for robustisizing
431 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
433 // Ding the blockStatus in the first two pages of the block.
437 memset(&spare, 0xff,sizeof(yaffs_Spare));
439 spare.blockStatus = 0;
441 // TODO change this retirement marking for other NAND types
442 yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock, NULL , &spare);
443 yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock + 1, NULL , &spare);
445 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
446 dev->nRetiredBlocks++;
451 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
453 dev->doingBufferedBlockRewrite = 1;
455 // Remove erased chunks
456 // Rewrite existing chunks to a new block
457 // Set current write block to the new block
459 dev->doingBufferedBlockRewrite = 0;
465 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
467 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
469 // Mark the block for retirement
470 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
471 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
475 // Just do a garbage collection on the affected block then retire the block
480 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
484 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare)
488 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare)
492 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
494 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
496 // Mark the block for retirement
497 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
499 yaffs_DeleteChunk(dev,chunkInNAND,1);
505 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1)
509 if( memcmp(d0,d1,YAFFS_BYTES_PER_CHUNK) != 0 ||
510 s0->tagByte0 != s1->tagByte0 ||
511 s0->tagByte1 != s1->tagByte1 ||
512 s0->tagByte2 != s1->tagByte2 ||
513 s0->tagByte3 != s1->tagByte3 ||
514 s0->tagByte4 != s1->tagByte4 ||
515 s0->tagByte5 != s1->tagByte5 ||
516 s0->tagByte6 != s1->tagByte6 ||
517 s0->tagByte7 != s1->tagByte7 ||
518 s0->ecc1[0] != s1->ecc1[0] ||
519 s0->ecc1[1] != s1->ecc1[1] ||
520 s0->ecc1[2] != s1->ecc1[2] ||
521 s0->ecc2[0] != s1->ecc2[0] ||
522 s0->ecc2[1] != s1->ecc2[1] ||
523 s0->ecc2[2] != s1->ecc2[2] )
532 ///////////////////////// Object management //////////////////
533 // List of spare objects
534 // The list is hooked together using the first pointer
537 // static yaffs_Object *yaffs_freeObjects = NULL;
539 // static int yaffs_nFreeObjects;
541 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
543 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
546 static __u16 yaffs_CalcNameSum(const char *name)
551 __u8 *bname = (__u8 *)name;
554 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
557 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
558 sum += toupper(*bname) * i;
569 void yaffs_SetObjectName(yaffs_Object *obj, const char *name)
571 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
572 if(name && strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
574 strcpy(obj->shortName,name);
578 obj->shortName[0]='\0';
581 obj->sum = yaffs_CalcNameSum(name);
584 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
586 nand_calculate_ecc (data , spare->ecc1);
587 nand_calculate_ecc (&data[256] , spare->ecc2);
590 void yaffs_CalcTagsECC(yaffs_Tags *tags)
594 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
601 for(i = 0; i < 8; i++)
603 for(j = 1; j &0xff; j<<=1)
618 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
620 unsigned ecc = tags->ecc;
622 yaffs_CalcTagsECC(tags);
628 // TODO: Handle the failure better. Retire?
629 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
633 b[ecc / 8] ^= (1 << (ecc & 7));
635 // Now recvalc the ecc
636 yaffs_CalcTagsECC(tags);
638 return 1; // recovered error
642 // Wierd ecc failure value
643 // TODO Need to do somethiong here
644 return -1; //unrecovered error
651 ///////////////////////// TNODES ///////////////////////
653 // List of spare tnodes
654 // The list is hooked together using the first pointer
657 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
659 // static int yaffs_nFreeTnodes;
661 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
665 // yaffs_CreateTnodes creates a bunch more tnodes and
666 // adds them to the tnode free list.
667 // Don't use this function directly
669 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
672 yaffs_Tnode *newTnodes;
673 yaffs_TnodeList *tnl;
675 if(nTnodes < 1) return YAFFS_OK;
679 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
683 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
687 // Hook them into the free list
688 for(i = 0; i < nTnodes - 1; i++)
690 newTnodes[i].internal[0] = &newTnodes[i+1];
691 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
692 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = 1;
696 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
697 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
698 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = 1;
700 dev->freeTnodes = newTnodes;
701 dev->nFreeTnodes+= nTnodes;
702 dev->nTnodesCreated += nTnodes;
704 // Now add this bunch of tnodes to a list for freeing up.
705 // NB If we can't add this to the management list it isn't fatal
706 // but it just means we can't free this bunch of tnodes later.
707 tnl = YMALLOC(sizeof(yaffs_TnodeList));
710 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
715 tnl->tnodes = newTnodes;
716 tnl->next = dev->allocatedTnodeList;
717 dev->allocatedTnodeList = tnl;
721 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
728 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
729 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
731 yaffs_Tnode *tn = NULL;
733 // If there are none left make more
736 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
741 tn = dev->freeTnodes;
742 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
743 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 1)
745 // Hoosterman, this thing looks like it isn't in the list
746 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 1" TENDSTR)));
749 dev->freeTnodes = dev->freeTnodes->internal[0];
752 memset(tn,0,sizeof(yaffs_Tnode));
760 // FreeTnode frees up a tnode and puts it back on the free list
761 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
765 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
766 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 0)
768 // Hoosterman, this thing looks like it is already in the list
769 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 2" TENDSTR)));
771 tn->internal[YAFFS_NTNODES_INTERNAL] = 1;
773 tn->internal[0] = dev->freeTnodes;
774 dev->freeTnodes = tn;
780 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
782 // Free the list of allocated tnodes
784 while(dev->allocatedTnodeList)
786 YFREE(dev->allocatedTnodeList->tnodes);
787 dev->allocatedTnodeList = dev->allocatedTnodeList->next;
790 dev->freeTnodes = NULL;
791 dev->nFreeTnodes = 0;
794 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
796 dev->allocatedTnodeList = NULL;
797 dev->freeTnodes = NULL;
798 dev->nFreeTnodes = 0;
799 dev->nTnodesCreated = 0;
804 void yaffs_TnodeTest(yaffs_Device *dev)
809 yaffs_Tnode *tn[1000];
811 YINFO("Testing TNodes");
813 for(j = 0; j < 50; j++)
815 for(i = 0; i < 1000; i++)
817 tn[i] = yaffs_GetTnode(dev);
820 YALERT("Getting tnode failed");
823 for(i = 0; i < 1000; i+=3)
825 yaffs_FreeTnode(dev,tn[i]);
834 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
836 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
837 // The look up tree is represented by the top tnode and the number of topLevel
838 // in the tree. 0 means only the level 0 tnode is in the tree.
841 // FindLevel0Tnode finds the level 0 tnode, if one exists.
842 // Used when reading.....
843 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
846 yaffs_Tnode *tn = fStruct->top;
848 int requiredTallness;
849 int level = fStruct->topLevel;
851 // Check sane level and chunk Id
852 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
855 // sprintf(str,"Bad level %d",level);
860 if(chunkId > YAFFS_MAX_CHUNK_ID)
863 // sprintf(str,"Bad chunkId %d",chunkId);
868 // First check we're tall enough (ie enough topLevel)
870 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
871 requiredTallness = 0;
874 i >>= YAFFS_TNODES_INTERNAL_BITS;
879 if(requiredTallness > fStruct->topLevel)
881 // Not tall enough, so we can't find it, return NULL.
886 // Traverse down to level 0
887 while (level > 0 && tn)
889 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
890 YAFFS_TNODES_INTERNAL_MASK];
898 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
899 // This happens in two steps:
900 // 1. If the tree isn't tall enough, then make it taller.
901 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
903 // Used when modifying the tree.
905 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
910 int requiredTallness;
917 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
919 // Check sane level and page Id
920 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
923 // sprintf(str,"Bad level %d",fStruct->topLevel);
928 if(chunkId > YAFFS_MAX_CHUNK_ID)
931 // sprintf(str,"Bad chunkId %d",chunkId);
936 // First check we're tall enough (ie enough topLevel)
938 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
939 requiredTallness = 0;
942 x >>= YAFFS_TNODES_INTERNAL_BITS;
946 //T((TSTR(" required=%d"),requiredTallness));
949 if(requiredTallness > fStruct->topLevel)
951 // Not tall enough,gotta make the tree taller
952 for(i = fStruct->topLevel; i < requiredTallness; i++)
954 //T((TSTR(" add new top")));
956 tn = yaffs_GetTnode(dev);
960 tn->internal[0] = fStruct->top;
965 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
969 fStruct->topLevel = requiredTallness;
973 // Traverse down to level 0, adding anything we need
975 l = fStruct->topLevel;
979 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
980 YAFFS_TNODES_INTERNAL_MASK;
982 //T((TSTR(" [%d:%d]"),l,i));
986 //T((TSTR(" added")));
988 tn->internal[x] = yaffs_GetTnode(dev);
991 tn = tn->internal[x];
1001 // DeleteWorker scans backwards through the tnode tree and deletes all the
1002 // chunks and tnodes in the file
1003 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1005 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1021 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1025 if(limit && (*limit) < 0)
1031 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1032 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1036 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1037 tn->internal[i] = NULL;
1042 return (allDone) ? 1 : 0;
1048 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1054 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1056 theChunk = tn->level0[i] << in->myDev->chunkGroupBits;
1058 // Now we need to search for it
1059 for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
1061 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
1062 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
1076 yaffs_DeleteChunk(in->myDev,theChunk,1);
1093 return (i < 0) ? 1 : 0;
1104 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1105 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1107 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1109 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1114 yaffs_BlockInfo *theBlock;
1126 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1130 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1131 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1134 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1135 tn->internal[i] = NULL;
1139 //Hoosterman... how could this happen.
1143 return (allDone) ? 1 : 0;
1148 for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1153 theChunk = (tn->level0[i] << in->myDev->chunkGroupBits);
1154 theBlock = yaffs_GetBlockInfo(in->myDev, theChunk/in->myDev->nChunksPerBlock);
1157 theBlock->softDeletions++;
1175 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1178 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1181 if(obj->nDataChunks <= 0)
1183 // Empty file, just delete it immediately
1184 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1185 obj->variant.fileVariant.top = NULL;
1186 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1187 yaffs_DoGenericObjectDeletion(obj);
1191 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1192 obj->softDeleted = 1;
1201 // Pruning removes any part of the file structure tree that is beyond the
1202 // bounds of the file (ie that does not point to chunks).
1204 // A file should only get pruned when its size is reduced.
1206 // Before pruning, the chunks must be pulled from the tree and the
1207 // level 0 tnode entries must be zeroed out.
1208 // Could also use this for file deletion, but that's probably better handled
1209 // by a special case.
1211 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1213 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1222 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1224 if(tn->internal[i] && level > 0)
1226 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1235 if(hasData == 0 && del0)
1237 // Free and return NULL
1239 yaffs_FreeTnode(dev,tn);
1249 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1256 if(fStruct->topLevel > 0)
1258 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1260 // Now we have a tree with all the non-zero branches NULL but the height
1261 // is the same as it was.
1262 // Let's see if we can trim internal tnodes to shorten the tree.
1263 // We can do this if only the 0th element in the tnode is in use
1264 // (ie all the non-zero are NULL)
1266 while(fStruct->topLevel && !done)
1271 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1281 fStruct->top = tn->internal[0];
1282 fStruct->topLevel--;
1283 yaffs_FreeTnode(dev,tn);
1299 /////////////////////// End of File Structure functions. /////////////////
1301 // yaffs_CreateFreeObjects creates a bunch more objects and
1302 // adds them to the object free list.
1303 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1306 yaffs_Object *newObjects;
1307 yaffs_ObjectList *list;
1309 if(nObjects < 1) return YAFFS_OK;
1311 // make these things
1313 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1317 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1321 // Hook them into the free list
1322 for(i = 0; i < nObjects - 1; i++)
1324 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1327 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1328 dev->freeObjects = newObjects;
1329 dev->nFreeObjects+= nObjects;
1330 dev->nObjectsCreated+= nObjects;
1332 // Now add this bunch of Objects to a list for freeing up.
1334 list = YMALLOC(sizeof(yaffs_ObjectList));
1337 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1341 list->objects = newObjects;
1342 list->next = dev->allocatedObjectList;
1343 dev->allocatedObjectList = list;
1352 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1353 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1355 yaffs_Object *tn = NULL;
1357 // If there are none left make more
1358 if(!dev->freeObjects)
1360 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1363 if(dev->freeObjects)
1365 tn = dev->freeObjects;
1366 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1367 dev->nFreeObjects--;
1369 // Now sweeten it up...
1371 memset(tn,0,sizeof(yaffs_Object));
1374 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1375 INIT_LIST_HEAD(&(tn->hardLinks));
1376 INIT_LIST_HEAD(&(tn->hashLink));
1377 INIT_LIST_HEAD(&tn->siblings);
1379 // Add it to the lost and found directory.
1380 // NB Can't put root or lostNFound in lostNFound so
1381 // check if lostNFound exists first
1382 if(dev->lostNFoundDir)
1384 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1392 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1395 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1398 obj->fake = 1; // it is fake so it has no NAND presence...
1399 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1400 obj->unlinkAllowed= 0; // ... or unlink it
1403 obj->st_mode = mode;
1405 obj->chunkId = 0; // Not a valid chunk.
1413 static void yaffs_UnhashObject(yaffs_Object *tn)
1416 yaffs_Device *dev = tn->myDev;
1419 // If it is still linked into the bucket list, free from the list
1420 if(!list_empty(&tn->hashLink))
1422 list_del_init(&tn->hashLink);
1423 bucket = yaffs_HashFunction(tn->objectId);
1424 dev->objectBucket[bucket].count--;
1430 // FreeObject frees up a Object and puts it back on the free list
1431 static void yaffs_FreeObject(yaffs_Object *tn)
1434 yaffs_Device *dev = tn->myDev;
1436 yaffs_UnhashObject(tn);
1438 // Link into the free list.
1439 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1440 dev->freeObjects = tn;
1441 dev->nFreeObjects++;
1447 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1449 // Free the list of allocated Objects
1451 while( dev->allocatedObjectList)
1453 YFREE(dev->allocatedObjectList->objects);
1454 dev->allocatedObjectList = dev->allocatedObjectList->next;
1457 dev->freeObjects = NULL;
1458 dev->nFreeObjects = 0;
1461 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1465 dev->allocatedObjectList = NULL;
1466 dev->freeObjects = NULL;
1467 dev->nFreeObjects = 0;
1469 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1471 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1472 dev->objectBucket[i].count = 0;
1482 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1487 int lowest = 999999;
1490 // First let's see if we can find one that's empty.
1492 for(i = 0; i < 10 && lowest > 0; i++)
1495 x %= YAFFS_NOBJECT_BUCKETS;
1496 if(dev->objectBucket[x].count < lowest)
1498 lowest = dev->objectBucket[x].count;
1504 // If we didn't find an empty list, then try
1505 // looking a bit further for a short one
1507 for(i = 0; i < 10 && lowest > 3; i++)
1510 x %= YAFFS_NOBJECT_BUCKETS;
1511 if(dev->objectBucket[x].count < lowest)
1513 lowest = dev->objectBucket[x].count;
1522 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1524 int bucket = yaffs_FindNiceObjectBucket(dev);
1526 // Now find an object value that has not already been taken
1527 // by scanning the list.
1530 struct list_head *i;
1532 __u32 n = (__u32)bucket;
1534 //yaffs_CheckObjectHashSanity();
1539 n += YAFFS_NOBJECT_BUCKETS;
1540 if(1 ||dev->objectBucket[bucket].count > 0)
1542 list_for_each(i,&dev->objectBucket[bucket].list)
1544 // If there is already one in the list
1545 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1553 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1558 void yaffs_HashObject(yaffs_Object *in)
1560 int bucket = yaffs_HashFunction(in->objectId);
1561 yaffs_Device *dev = in->myDev;
1563 if(!list_empty(&in->hashLink))
1569 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1570 dev->objectBucket[bucket].count++;
1574 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1576 int bucket = yaffs_HashFunction(number);
1577 struct list_head *i;
1580 list_for_each(i,&dev->objectBucket[bucket].list)
1582 // Look if it is in the list
1585 in = list_entry(i, yaffs_Object,hashLink);
1586 if(in->objectId == number)
1598 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1601 yaffs_Object *theObject;
1605 number = yaffs_CreateNewObjectNumber(dev);
1608 theObject = yaffs_AllocateEmptyObject(dev);
1612 theObject->fake = 0;
1613 theObject->renameAllowed = 1;
1614 theObject->unlinkAllowed = 1;
1615 theObject->objectId = number;
1616 yaffs_HashObject(theObject);
1617 theObject->variantType = type;
1618 #ifdef CONFIG_YAFFS_WINCE
1619 yfsd_WinFileTimeNow(theObject->win_atime);
1620 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1621 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1624 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1628 case YAFFS_OBJECT_TYPE_FILE:
1629 theObject->variant.fileVariant.fileSize = 0;
1630 theObject->variant.fileVariant.scannedFileSize = 0;
1631 theObject->variant.fileVariant.topLevel = 0;
1632 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1634 case YAFFS_OBJECT_TYPE_DIRECTORY:
1635 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1637 case YAFFS_OBJECT_TYPE_SYMLINK:
1638 // No action required
1640 case YAFFS_OBJECT_TYPE_HARDLINK:
1641 // No action required
1643 case YAFFS_OBJECT_TYPE_SPECIAL:
1644 // No action required
1646 case YAFFS_OBJECT_TYPE_UNKNOWN:
1647 // todo this should not happen
1655 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1657 yaffs_Object *theObject = NULL;
1661 theObject = yaffs_FindObjectByNumber(dev,number);
1666 theObject = yaffs_CreateNewObject(dev,number,type);
1673 char *yaffs_CloneString(const char *str)
1675 char *newStr = NULL;
1679 newStr = YMALLOC(strlen(str) + 1);
1688 // Mknod (create) a new object.
1689 // equivalentObject only has meaning for a hard link;
1690 // aliasString only has meaning for a sumlink.
1691 // rdev only has meaning for devices (a subset of special objects)
1692 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1693 yaffs_Object *parent,
1698 yaffs_Object *equivalentObject,
1699 const char *aliasString,
1704 yaffs_Device *dev = parent->myDev;
1706 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1707 if(yaffs_FindObjectByName(parent,name))
1712 in = yaffs_CreateNewObject(dev,-1,type);
1718 in->variantType = type;
1722 #ifdef CONFIG_YAFFS_WINCE
1723 yfsd_WinFileTimeNow(in->win_atime);
1724 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1725 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[0];
1728 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1733 in->nDataChunks = 0;
1735 yaffs_SetObjectName(in,name);
1738 yaffs_AddObjectToDirectory(parent,in);
1740 in->myDev = parent->myDev;
1745 case YAFFS_OBJECT_TYPE_SYMLINK:
1746 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1748 case YAFFS_OBJECT_TYPE_HARDLINK:
1749 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1750 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1751 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1753 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1754 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1755 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1756 case YAFFS_OBJECT_TYPE_UNKNOWN:
1760 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1761 yaffs_UpdateObjectHeader(in,name,0) < 0)
1763 // Could not create the object header, fail the creation
1764 yaffs_AbortHalfCreatedObject(in);
1773 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1775 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1778 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1780 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1783 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1785 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1788 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1790 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1793 // NB yaffs_Link returns the object id of the equivalent object.
1794 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1796 // Get the real object in case we were fed a hard link as an equivalent object
1797 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1799 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1801 return equivalentObject;
1811 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1817 newDir = obj->parent; // use the old directory
1820 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1822 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1823 // duplicate names are allowed.
1824 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1827 !yaffs_FindObjectByName(newDir,newName)) &&
1828 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1830 yaffs_SetObjectName(obj,newName);
1833 yaffs_AddObjectToDirectory(newDir,obj);
1835 if(unlinkOp) obj->unlinked = 1;
1838 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1849 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1854 #ifdef YAFFS_CASE_INSENSITIVE
1855 // Special case for WinCE.
1856 // While look-up is case insensitive, the name isn't.
1857 // THerefore we might want to change x.txt to X.txt
1858 if(oldDir == newDir && _stricmp(oldName,newName) == 0)
1864 obj = yaffs_FindObjectByName(oldDir,oldName);
1865 if(obj && obj->renameAllowed)
1867 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1874 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1876 // Scan the buckets and check that the lists
1877 // have as many members as the count says there are
1880 struct list_head *j;
1883 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1887 list_for_each(j,&dev->objectBucket[bucket].list)
1892 if(countEm != dev->objectBucket[bucket].count)
1894 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1903 void yaffs_ObjectTest(yaffs_Device *dev)
1905 yaffs_Object *in[1000];
1907 yaffs_Object *inold[1000];
1911 memset(in,0,1000*sizeof(yaffs_Object *));
1912 memset(inold,0,1000*sizeof(yaffs_Object *));
1914 yaffs_CheckObjectHashSanity(dev);
1916 for(j = 0; j < 10; j++)
1920 for(i = 0; i < 1000; i++)
1922 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1925 YINFO("No more inodes");
1929 inNo[i] = in[i]->objectId;
1933 for(i = 0; i < 1000; i++)
1935 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1937 //T(("Differnce in look up test\n"));
1941 // T(("Look up ok\n"));
1945 yaffs_CheckObjectHashSanity(dev);
1947 for(i = 0; i < 1000; i+=3)
1949 yaffs_FreeObject(in[i]);
1954 yaffs_CheckObjectHashSanity(dev);
1961 /////////////////////////// Block Management and Page Allocation ///////////////////
1964 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1966 dev->allocationBlock = -1; // force it to get a new one
1967 //Todo we're assuming the malloc will pass.
1968 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1969 // Set up dynamic blockinfo stuff.
1970 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
1971 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1972 if(dev->blockInfo && dev->chunkBits)
1974 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1975 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
1983 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1985 YFREE(dev->blockInfo);
1986 dev->blockInfo = NULL;
1987 YFREE(dev->chunkBits);
1988 dev->chunkBits = NULL;
1991 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1992 // for garbage collection.
1994 static int yaffs_FindDirtiestBlock(yaffs_Device *dev,int aggressive)
1997 int b = dev->currentDirtyChecker;
2003 yaffs_BlockInfo *bi;
2005 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2008 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2011 iterations = dev->endBlock - dev->startBlock + 1;
2015 iterations = iterations / 16;
2016 if(iterations > 200)
2022 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2025 if ( b < dev->startBlock || b > dev->endBlock)
2027 b = dev->startBlock;
2030 if(b < dev->startBlock || b > dev->endBlock)
2032 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2036 bi = yaffs_GetBlockInfo(dev,b);
2038 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2039 (bi->pagesInUse - bi->softDeletions )< pagesInUse)
2042 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2046 dev->currentDirtyChecker = b;
2052 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2054 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2058 // If the block is still healthy erase it and mark as clean.
2059 // If the block has had a data failure, then retire it.
2060 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2062 if(!bi->needsRetiring)
2064 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2067 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2074 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2075 dev->nErasedBlocks++;
2077 bi->softDeletions = 0;
2078 yaffs_ClearChunkBits(dev,blockNo);
2080 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2084 yaffs_RetireBlock(dev,blockNo);
2085 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2090 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2094 yaffs_BlockInfo *bi;
2096 if(dev->nErasedBlocks < 1)
2098 // Hoosterman we've got a problem.
2099 // Can't get space to gc
2100 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during gc" TENDSTR)));
2105 // Find an empty block.
2107 for(i = dev->startBlock; i <= dev->endBlock; i++)
2109 dev->allocationBlockFinder++;
2110 if(dev->allocationBlockFinder <dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2112 dev->allocationBlockFinder = dev->startBlock;
2115 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2117 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2119 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2120 dev->nErasedBlocks--;
2121 return dev->allocationBlockFinder;
2130 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2133 yaffs_BlockInfo *bi;
2135 if(dev->allocationBlock < 0)
2137 // Get next block to allocate off
2138 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2139 dev->allocationPage = 0;
2142 if(!useReserve && dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
2144 // Not enough space to allocate unless we're allowed to use the reserve.
2148 // Next page please....
2149 if(dev->allocationBlock >= 0)
2151 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2153 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2154 dev->allocationPage;
2156 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2158 dev->allocationPage++;
2162 // If the block is full set the state to full
2163 if(dev->allocationPage >= dev->nChunksPerBlock)
2165 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2166 dev->allocationBlock = -1;
2173 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2178 // To determine if we have enough space we just look at the
2179 // number of erased blocks.
2180 // The cache is allowed to use reserved blocks.
2182 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2184 return (dev->nErasedBlocks >= YAFFS_RESERVED_BLOCKS);
2188 static int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2198 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
2200 // yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2202 yaffs_Object *object;
2204 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2206 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2207 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2208 chunkInBlock++, oldChunk++ )
2210 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2213 // This page is in use and might need to be copied off
2217 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2219 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
2221 yaffs_GetTagsFromSpare(dev,&spare,&tags);
2223 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2225 if(object && object->deleted && tags.chunkId != 0)
2227 // Data chunk in a deleted file, throw it away
2228 // It's a deleted data chunk,
2229 // No need to copy this, just forget about it and fix up the
2232 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2233 object->nDataChunks--;
2235 if(object->nDataChunks <= 0)
2237 // Time to delete the file too
2238 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2239 object->variant.fileVariant.top = NULL;
2240 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2241 yaffs_DoGenericObjectDeletion(object);
2245 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2247 // Deleted object header with no data chunks.
2248 // Can be discarded and the file deleted.
2249 object->chunkId = 0;
2250 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2251 object->variant.fileVariant.top = NULL;
2252 yaffs_DoGenericObjectDeletion(object);
2257 // It's either a data chunk in a live file or
2258 // an ObjectHeader, so we're interested in it.
2259 // NB Need to keep the ObjectHeaders of deleted files
2260 // until the whole file has been deleted off
2261 tags.serialNumber++;
2262 yaffs_LoadTagsIntoSpare(&spare,&tags);
2266 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
2273 // Ok, now fix up the Tnodes etc.
2275 if(tags.chunkId == 0)
2278 object->chunkId = newChunk;
2282 // It's a data chunk
2283 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2287 yaffs_DeleteChunk(dev,oldChunk,markNAND);
2296 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2298 // find a file to delete
2299 struct list_head *i;
2303 //Scan the unlinked files looking for one to delete
2304 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2308 l = list_entry(i, yaffs_Object,siblings);
2319 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2321 // This does background deletion on unlinked files.. only deleted ones.
2322 // If we don't have a file we're working on then find one
2323 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2325 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2328 // OK, we're working on a file...
2329 if(dev->unlinkedDeletion)
2331 yaffs_Object *obj = dev->unlinkedDeletion;
2333 int limit; // Number of chunks to delete in a file.
2334 // NB this can be exceeded, but not by much.
2338 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2340 if(obj->nDataChunks == 0)
2342 // Done all the deleting of data chunks.
2343 // Now dump the header and clean up
2344 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2345 obj->variant.fileVariant.top = NULL;
2346 yaffs_DoGenericObjectDeletion(obj);
2347 dev->nDeletedFiles--;
2348 dev->nUnlinkedFiles--;
2349 dev->nBackgroundDeletions++;
2350 dev->unlinkedDeletion = NULL;
2357 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
2358 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2363 //yaffs_DoUnlinkedFileDeletion(dev);
2365 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2372 block = yaffs_FindDirtiestBlock(dev,aggressive);
2376 dev->garbageCollections++;
2377 return yaffs_GarbageCollectBlock(dev,block);
2389 // New garbage collector
2390 // If we're very low on erased blocks then we do aggressive garbage collection
2391 // otherwise we do "passive" garbage collection.
2392 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2393 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2395 // The idea is to help clear out space in a more spread-out manner.
2396 // Dunno if it really does anything useful.
2398 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2403 //yaffs_DoUnlinkedFileDeletion(dev);
2405 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + 1))
2410 block = yaffs_FindDirtiestBlock(dev,aggressive);
2414 dev->garbageCollections++;
2417 dev->passiveGarbageCollections++;
2420 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2422 return yaffs_GarbageCollectBlock(dev,block);
2425 return aggressive ? YAFFS_FAIL : YAFFS_OK;
2429 //////////////////////////// TAGS ///////////////////////////////////////
2431 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2433 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2435 yaffs_CalcTagsECC(tagsPtr);
2437 sparePtr->tagByte0 = tu->asBytes[0];
2438 sparePtr->tagByte1 = tu->asBytes[1];
2439 sparePtr->tagByte2 = tu->asBytes[2];
2440 sparePtr->tagByte3 = tu->asBytes[3];
2441 sparePtr->tagByte4 = tu->asBytes[4];
2442 sparePtr->tagByte5 = tu->asBytes[5];
2443 sparePtr->tagByte6 = tu->asBytes[6];
2444 sparePtr->tagByte7 = tu->asBytes[7];
2447 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2449 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2452 tu->asBytes[0]= sparePtr->tagByte0;
2453 tu->asBytes[1]= sparePtr->tagByte1;
2454 tu->asBytes[2]= sparePtr->tagByte2;
2455 tu->asBytes[3]= sparePtr->tagByte3;
2456 tu->asBytes[4]= sparePtr->tagByte4;
2457 tu->asBytes[5]= sparePtr->tagByte5;
2458 tu->asBytes[6]= sparePtr->tagByte6;
2459 tu->asBytes[7]= sparePtr->tagByte7;
2461 result = yaffs_CheckECCOnTags(tagsPtr);
2464 dev->tagsEccFixed++;
2468 dev->tagsEccUnfixed++;
2472 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2474 memset(spare,0xFF,sizeof(yaffs_Spare));
2477 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2482 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2484 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2485 yaffs_GetTagsFromSpare(dev,&spare,tags);
2498 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2500 // NB There must be tags, data is optional
2501 // If there is data, then an ECC is calculated on it.
2510 yaffs_SpareInitialise(&spare);
2512 if(!dev->useNANDECC && buffer)
2514 yaffs_CalcECC(buffer,&spare);
2517 yaffs_LoadTagsIntoSpare(&spare,tags);
2519 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2525 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2527 // NB There must be tags, data is optional
2528 // If there is data, then an ECC is calculated on it.
2537 yaffs_SpareInitialise(&spare);
2539 if(!dev->useNANDECC && buffer)
2541 yaffs_CalcECC(buffer,&spare);
2544 yaffs_LoadTagsIntoSpare(&spare,tags);
2546 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2550 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2552 return ( tags->chunkId == chunkInObject &&
2553 tags->objectId == objectId &&
2554 !chunkDeleted) ? 1 : 0;
2560 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2562 //Get the Tnode, then get the level 0 offset chunk offset
2565 yaffs_Tags localTags;
2570 yaffs_Device *dev = in->myDev;
2575 // Passed a NULL, so use our own tags space
2579 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2583 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2585 // Now we need to do the shifting etc and search for it
2586 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2588 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2589 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2600 return found ? theChunk : -1;
2603 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2605 //Get the Tnode, then get the level 0 offset chunk offset
2608 yaffs_Tags localTags;
2611 yaffs_Device *dev = in->myDev;
2616 // Passed a NULL, so use our own tags space
2620 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2625 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2627 // Now we need to do the shifting etc and search for it
2628 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2630 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2631 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2642 // Delete the entry in the filestructure
2645 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2650 //T(("No level 0 found for %d\n", chunkInInode));
2655 //T(("Could not find %d to delete\n",chunkInInode));
2657 return found ? theChunk : -1;
2661 #ifdef YAFFS_PARANOID
2663 static int yaffs_CheckFileSanity(yaffs_Object *in)
2671 yaffs_Tags localTags;
2672 yaffs_Tags *tags = &localTags;
2677 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2679 //T(("Object not a file\n"));
2683 objId = in->objectId;
2684 fSize = in->variant.fileVariant.fileSize;
2685 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
2687 for(chunk = 1; chunk <= nChunks; chunk++)
2689 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2694 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2697 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2698 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2705 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2706 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2715 //T(("No level 0 found for %d\n", chunk));
2719 return failed ? YAFFS_FAIL : YAFFS_OK;
2724 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2727 yaffs_Device *dev = in->myDev;
2729 yaffs_Tags existingTags;
2731 unsigned existingSerial, newSerial;
2733 int newChunkDeleted;
2736 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2742 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2746 // If we're scanning then we need to test for duplicates
2747 // NB This does not need to be efficient since it should only ever
2748 // happen when the power fails during a write, then only one
2749 // chunk should ever be affected.
2752 if(existingChunk != 0)
2754 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2755 // thus we have to do a FindChunkInFile to get the real chunk id.
2757 // We have a duplicate now we need to decide which one to use
2758 // To do this we get both sets of tags and compare serial numbers.
2759 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2763 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2765 if(existingChunk <=0)
2767 //Hoosterman - how did this happen?
2769 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
2774 // NB The deleted flags should be false, otherwise the chunks will
2775 // not be loaded during a scan
2777 newSerial = newTags.serialNumber;
2778 existingSerial = existingTags.serialNumber;
2780 if( existingChunk <= 0 ||
2781 ((existingSerial+1) & 3) == newSerial)
2784 // Delete the old one and drop through to update the tnode
2785 yaffs_DeleteChunk(dev,existingChunk,1);
2790 // Delete the new one and return early so that the tnode isn't changed
2791 yaffs_DeleteChunk(dev,chunkInNAND,1);
2798 if(existingChunk == 0)
2803 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2810 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2812 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2814 if(chunkInNAND >= 0)
2816 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2826 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND)
2831 yaffs_BlockInfo *bi;
2833 if(chunkId <= 0) return;
2836 block = chunkId / dev->nChunksPerBlock;
2837 page = chunkId % dev->nChunksPerBlock;
2841 yaffs_SpareInitialise(&spare);
2843 spare.pageStatus = 0; // To mark it as deleted.
2846 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2847 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2851 dev->nUnmarkedDeletions++;
2854 bi = yaffs_GetBlockInfo(dev,block);
2857 // Pull out of the management area.
2858 // If the whole block became dirty, this will kick off an erasure.
2859 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2860 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2864 yaffs_ClearChunkBit(dev,block,page);
2867 if(bi->pagesInUse == 0 &&
2868 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2870 yaffs_BlockBecameDirty(dev,block);
2876 // T(("Bad news deleting chunk %d\n",chunkId));
2884 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2886 // Find old chunk Need to do this to get serial number
2887 // Write new one and patch into tree.
2888 // Invalidate old tags.
2891 yaffs_Tags prevTags;
2896 yaffs_Device *dev = in->myDev;
2898 yaffs_CheckGarbageCollection(dev);
2900 // Get the previous chunk at this location in the file if it exists
2901 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2904 newTags.chunkId = chunkInInode;
2905 newTags.objectId = in->objectId;
2906 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2907 newTags.byteCount = nBytes;
2908 newTags.unusedStuff = 0xFFFFFFFF;
2910 yaffs_CalcTagsECC(&newTags);
2912 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2915 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2918 if(prevChunkId >= 0)
2920 yaffs_DeleteChunk(dev,prevChunkId,1);
2924 yaffs_CheckFileSanity(in);
2935 // UpdateObjectHeader updates the header on NAND for an object.
2936 // If name is not NULL, then that new name is used.
2938 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2941 yaffs_Device *dev = in->myDev;
2947 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2948 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2950 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2951 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2954 if(!in->fake || force)
2957 yaffs_CheckGarbageCollection(dev);
2959 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2961 prevChunkId = in->chunkId;
2963 if(prevChunkId >= 0)
2965 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2969 oh->type = in->variantType;
2971 oh->st_mode = in->st_mode;
2973 #ifdef CONFIG_YAFFS_WINCE
2974 oh->win_atime[0] = in->win_atime[0];
2975 oh->win_ctime[0] = in->win_ctime[0];
2976 oh->win_mtime[0] = in->win_mtime[0];
2977 oh->win_atime[1] = in->win_atime[1];
2978 oh->win_ctime[1] = in->win_ctime[1];
2979 oh->win_mtime[1] = in->win_mtime[1];
2981 oh->st_uid = in->st_uid;
2982 oh->st_gid = in->st_gid;
2983 oh->st_atime = in->st_atime;
2984 oh->st_mtime = in->st_mtime;
2985 oh->st_ctime = in->st_ctime;
2986 oh->st_rdev = in->st_rdev;
2990 oh->parentObjectId = in->parent->objectId;
2994 oh->parentObjectId = 0;
2997 //oh->sum = in->sum;
3000 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3001 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3003 else if(prevChunkId)
3005 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
3009 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3012 switch(in->variantType)
3014 case YAFFS_OBJECT_TYPE_UNKNOWN:
3015 // Should not happen
3017 case YAFFS_OBJECT_TYPE_FILE:
3018 oh->fileSize = in->variant.fileVariant.fileSize;
3020 case YAFFS_OBJECT_TYPE_HARDLINK:
3021 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3023 case YAFFS_OBJECT_TYPE_SPECIAL:
3026 case YAFFS_OBJECT_TYPE_DIRECTORY:
3029 case YAFFS_OBJECT_TYPE_SYMLINK:
3030 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3031 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3037 newTags.chunkId = 0;
3038 newTags.objectId = in->objectId;
3039 newTags.serialNumber = in->serial;
3040 newTags.byteCount = 0xFFFFFFFF;
3041 newTags.unusedStuff = 0xFFFFFFFF;
3043 yaffs_CalcTagsECC(&newTags);
3046 // Create new chunk in NAND
3047 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3052 in->chunkId = newChunkId;
3054 if(prevChunkId >= 0)
3056 yaffs_DeleteChunk(dev,prevChunkId,1);
3069 /////////////////////// Short Operations Cache ////////////////////////////////
3070 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3071 // reads might be short sequential reads, and a lot of writes may be short
3072 // sequential writes. eg. scanning/writing a jpeg file.
3073 // In these cases, a short read/write cache can provide a huge perfomance benefit
3074 // with dumb-as-a-rock code.
3075 // There are a limited number (~10) of cache chunks per device so that we don't
3076 // need a very intelligent search.
3082 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3084 yaffs_Device *dev = obj->myDev;
3087 yaffs_ChunkCache *cache;
3090 int nCaches = obj->myDev->nShortOpCaches;
3097 // Find the dirty cache for this object with the lowest chunk id.
3098 for(i = 0; i < nCaches; i++)
3100 if(dev->srCache[i].object == obj &&
3101 dev->srCache[i].dirty)
3103 if(!cache || dev->srCache[i].chunkId < lowest)
3105 cache = &dev->srCache[i];
3106 lowest = cache->chunkId;
3116 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3118 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3120 nBytes= YAFFS_BYTES_PER_CHUNK;
3123 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3131 } while(cache && chunkWritten > 0);
3135 //Hoosterman, disk full while writing cache out.
3136 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3144 // Grab us a chunk for use.
3145 // First look for an empty one.
3146 // Then look for the least recently used non-dirty one.
3147 // Then look for the least recently used dirty one...., flush and look again.
3148 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3154 if(dev->nShortOpCaches > 0)
3156 for(i = 0; i < dev->nShortOpCaches; i++)
3158 if(!dev->srCache[i].object)
3160 //T(("Grabbing empty %d\n",i));
3162 return &dev->srCache[i];
3167 usage = 0; // just to stop the compiler grizzling
3169 for(i = 0; i < dev->nShortOpCaches; i++)
3171 if(!dev->srCache[i].dirty &&
3172 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3175 usage = dev->srCache[i].lastUse;
3180 //T(("Grabbing non-empty %d\n",theOne));
3181 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3191 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3193 yaffs_ChunkCache *cache;
3194 yaffs_Object *theObj;
3198 if(dev->nShortOpCaches > 0)
3200 // Try find a non-dirty one...
3202 cache = yaffs_GrabChunkCacheWorker(dev);
3206 // They were all dirty, find the last recently used object and flush
3207 // its cache, then find again.
3208 // NB what's here is not very accurate, we actually flush the object
3209 // the last recently used page.
3211 theObj = dev->srCache[0].object;
3212 usage = dev->srCache[0].lastUse;
3214 for(i = 1; i < dev->nShortOpCaches; i++)
3216 if( dev->srCache[i].object &&
3217 dev->srCache[i].lastUse < usage)
3219 usage = dev->srCache[i].lastUse;
3220 theObj = dev->srCache[i].object;
3224 yaffs_FlushFilesChunkCache(theObj);
3227 cache = yaffs_GrabChunkCacheWorker(dev);
3238 // Find a cached chunk
3239 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3241 yaffs_Device *dev = obj->myDev;
3243 if(dev->nShortOpCaches > 0)
3245 for(i = 0; i < dev->nShortOpCaches; i++)
3247 if(dev->srCache[i].object == obj &&
3248 dev->srCache[i].chunkId == chunkId)
3252 return &dev->srCache[i];
3259 // Mark the chunk for the least recently used algorithym
3260 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3263 if(dev->nShortOpCaches > 0)
3265 if( dev->srLastUse < 0 ||
3266 dev->srLastUse > 100000000)
3268 // Reset the cache usages
3270 for(i = 1; i < dev->nShortOpCaches; i++)
3272 dev->srCache[i].lastUse = 0;
3279 cache->lastUse = dev->srLastUse;
3288 // Invalidate a single cache page.
3289 // Do this when a whole page gets written,
3290 // ie the short cache for this page is no longer valid.
3291 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3293 if(object->myDev->nShortOpCaches > 0)
3295 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3299 cache->object = NULL;
3305 // Invalidate all the cache pages associated with this object
3306 // Do this whenever ther file is deleted or resized.
3307 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3310 yaffs_Device *dev = in->myDev;
3312 if(dev->nShortOpCaches > 0)
3314 // Now invalidate it.
3315 for(i = 0; i < dev->nShortOpCaches; i++)
3317 if(dev->srCache[i].object == in)
3319 dev->srCache[i].object = NULL;
3329 ///////////////////////// File read/write ///////////////////////////////
3330 // Read and write have very similar structures.
3331 // In general the read/write has three parts to it
3332 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3333 // * Some complete chunks
3334 // * An incomplete chunk to end off with
3336 // Curve-balls: the first chunk might also be the last chunk.
3338 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3354 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
3355 start = offset % YAFFS_BYTES_PER_CHUNK;
3357 // OK now check for the curveball where the start and end are in
3359 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3365 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3368 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3370 // An incomplete start or end chunk (or maybe both start and end chunk)
3371 if(dev->nShortOpCaches > 0)
3373 yaffs_ChunkCache *cache;
3374 // If we can't find the data in the cache, then load it up.
3375 cache = yaffs_FindChunkCache(in,chunk);
3378 cache = yaffs_GrabChunkCache(in->myDev);
3380 cache->chunkId = chunk;
3382 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3386 yaffs_UseChunkCache(dev,cache,0);
3388 memcpy(buffer,&cache->data[start],nToCopy);
3392 // Read into the local buffer then copy...
3393 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3394 memcpy(buffer,&dev->localBuffer[start],nToCopy);
3400 #ifdef CONFIG_YAFFS_WINCE
3402 // Under WinCE can't do direct transfer. Need to use a local buffer.
3403 // This is because we otherwise screw up WinCE's memory mapper
3404 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3405 memcpy(buffer,dev->localBuffer,YAFFS_BYTES_PER_CHUNK);
3407 // A full chunk. Read directly into the supplied buffer.
3408 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3424 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3433 int startOfWrite = offset;
3434 int chunkWritten = 0;
3442 while(n > 0 && chunkWritten >= 0)
3444 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
3445 start = offset % YAFFS_BYTES_PER_CHUNK;
3448 // OK now check for the curveball where the start and end are in
3451 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3455 // Now folks, to calculate how many bytes to write back....
3456 // If we're overwriting and not writing to then end of file then
3457 // we need to write back as much as was there before.
3459 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
3461 if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
3463 nBytesRead = YAFFS_BYTES_PER_CHUNK;
3466 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3471 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3472 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3475 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3477 // An incomplete start or end chunk (or maybe both start and end chunk)
3478 if(dev->nShortOpCaches > 0)
3480 yaffs_ChunkCache *cache;
3481 // If we can't find the data in the cache, then load it up.
3482 cache = yaffs_FindChunkCache(in,chunk);
3483 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3485 cache = yaffs_GrabChunkCache(in->myDev);
3487 cache->chunkId = chunk;
3489 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3494 yaffs_UseChunkCache(dev,cache,1);
3495 memcpy(&cache->data[start],buffer,nToCopy);
3496 cache->nBytes = nToWriteBack;
3500 chunkWritten = -1; // fail the write
3505 // An incomplete start or end chunk (or maybe both start and end chunk)
3506 // Read into the local buffer then copy, then copy over and write back.
3508 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3510 memcpy(&dev->localBuffer[start],buffer,nToCopy);
3512 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,nToWriteBack,0);
3514 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3521 #ifdef CONFIG_YAFFS_WINCE
3522 // Under WinCE can't do direct transfer. Need to use a local buffer.
3523 // This is because we otherwise screw up WinCE's memory mapper
3524 memcpy(dev->localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3525 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3527 // A full chunk. Write directly from the supplied buffer.
3528 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3530 // Since we've overwritten the cached data, we better invalidate it.
3531 yaffs_InvalidateChunkCache(in,chunk);
3532 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3535 if(chunkWritten >= 0)
3545 // Update file object
3547 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3549 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3558 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3562 int oldFileSize = in->variant.fileVariant.fileSize;
3563 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3565 yaffs_Device *dev = in->myDev;
3568 yaffs_FlushFilesChunkCache(in);
3569 yaffs_InvalidateWholeChunkCache(in);
3571 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3573 return yaffs_GetFileSize(in);
3576 if(newSize < oldFileSize)
3579 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3581 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3582 YAFFS_BYTES_PER_CHUNK;
3584 // Delete backwards so that we don't end up with holes if
3585 // power is lost part-way through the operation.
3586 for(i = lastDel; i >= startDel; i--)
3588 // NB this could be optimised somewhat,
3589 // eg. could retrieve the tags and write them without
3590 // using yaffs_DeleteChunk
3592 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3593 if(chunkId <= 0 || chunkId >= (dev->endBlock * 32))
3595 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3600 yaffs_DeleteChunk(dev,chunkId,1);
3605 if(sizeOfPartialChunk != 0)
3607 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3609 // Got to read and rewrite the last chunk with its new size.
3610 yaffs_ReadChunkDataFromObject(in,lastChunk,dev->localBuffer);
3612 yaffs_WriteChunkDataToObject(in,lastChunk,dev->localBuffer,sizeOfPartialChunk,1);
3616 in->variant.fileVariant.fileSize = newSize;
3618 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3630 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3632 obj = yaffs_GetEquivalentObject(obj);
3634 switch(obj->variantType)
3636 case YAFFS_OBJECT_TYPE_FILE:
3637 return obj->variant.fileVariant.fileSize;
3638 case YAFFS_OBJECT_TYPE_SYMLINK:
3639 return strlen(obj->variant.symLinkVariant.alias);
3647 // yaffs_FlushFile() updates the file's
3650 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
3655 //T(("flushing object header\n"));
3657 yaffs_FlushFilesChunkCache(in);
3660 #ifdef CONFIG_YAFFS_WINCE
3661 yfsd_WinFileTimeNow(in->win_mtime);
3663 in->st_mtime = CURRENT_TIME;
3667 retVal = (yaffs_UpdateObjectHeader(in,NULL,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
3679 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3682 // First off, invalidate the file's data in the cache, without flushing.
3683 yaffs_InvalidateWholeChunkCache(in);
3685 yaffs_RemoveObjectFromDirectory(in);
3686 yaffs_DeleteChunk(in->myDev,in->chunkId,1);
3690 in->myInode->u.generic_ip = NULL;
3694 yaffs_FreeObject(in);
3699 // yaffs_DeleteFile deletes the whole file data
3700 // and the inode associated with the file.
3701 // It does not delete the links associated with the file.
3702 static int yaffs_UnlinkFile(yaffs_Object *in)
3705 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3707 // Delete the file data & tnodes
3709 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3712 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3714 return yaffs_DoGenericObjectDeletion(in);
3717 int immediateDeletion=0;
3718 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3719 if(1 || // Ignore the result of the change name. This will only fail
3720 // if the disk was completely full (an error condition)
3721 // We ignore the error so we can delete files to recover the disk
3725 //in->myDev->nUnlinkedFiles++;
3726 //in->renameAllowed = 0;
3730 immediateDeletion = 1;
3736 immediateDeletion = 1;
3741 if(immediateDeletion)
3743 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3745 in->myDev->nDeletedFiles++;
3746 yaffs_SoftDeleteFile(in);
3756 int yaffs_DeleteFile(yaffs_Object *in)
3758 int retVal = YAFFS_OK;
3760 if(in->nDataChunks > 0)
3762 // Use soft deletion
3765 retVal = yaffs_UnlinkFile(in);
3767 if(retVal == YAFFS_OK &&
3772 in->myDev->nDeletedFiles++;
3773 yaffs_SoftDeleteFile(in);
3775 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3779 // The file has no data chunks so we toss it immediately
3780 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3781 in->variant.fileVariant.top = NULL;
3782 yaffs_DoGenericObjectDeletion(in);
3788 static int yaffs_DeleteDirectory(yaffs_Object *in)
3790 //First check that the directory is empty.
3791 if(list_empty(&in->variant.directoryVariant.children))
3793 return yaffs_DoGenericObjectDeletion(in);
3800 static int yaffs_DeleteSymLink(yaffs_Object *in)
3802 YFREE(in->variant.symLinkVariant.alias);
3804 return yaffs_DoGenericObjectDeletion(in);
3807 static int yaffs_DeleteHardLink(yaffs_Object *in)
3809 // remove this hardlink from the list assocaited with the equivalent
3811 list_del(&in->hardLinks);
3812 return yaffs_DoGenericObjectDeletion(in);
3816 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj)
3818 switch(obj->variantType)
3820 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
3821 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
3822 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
3823 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
3824 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
3825 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
3830 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3834 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3836 return yaffs_DeleteHardLink(obj);
3838 else if(!list_empty(&obj->hardLinks))
3840 // Curve ball: We're unlinking an object that has a hardlink.
3842 // This problem arises because we are not strictly following
3843 // The Linux link/inode model.
3845 // We can't really delete the object.
3846 // Instead, we do the following:
3847 // - Select a hardlink.
3848 // - Unhook it from the hard links
3849 // - Unhook it from its parent directory (so that the rename can work)
3850 // - Rename the object to the hardlink's name.
3851 // - Delete the hardlink
3856 char name[YAFFS_MAX_NAME_LENGTH+1];
3858 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3860 list_del_init(&hl->hardLinks);
3861 list_del_init(&hl->siblings);
3863 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3865 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3867 if(retVal == YAFFS_OK)
3869 retVal = yaffs_DoGenericObjectDeletion(hl);
3876 switch(obj->variantType)
3878 case YAFFS_OBJECT_TYPE_FILE:
3879 return yaffs_UnlinkFile(obj);
3881 case YAFFS_OBJECT_TYPE_DIRECTORY:
3882 return yaffs_DeleteDirectory(obj);
3884 case YAFFS_OBJECT_TYPE_SYMLINK:
3885 return yaffs_DeleteSymLink(obj);
3887 case YAFFS_OBJECT_TYPE_HARDLINK:
3888 case YAFFS_OBJECT_TYPE_UNKNOWN:
3895 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3899 obj = yaffs_FindObjectByName(dir,name);
3901 if(obj && obj->unlinkAllowed)
3903 return yaffs_UnlinkWorker(obj);
3910 //////////////// Initialisation Scanning /////////////////
3914 // For now we use the SmartMedia check.
3915 // We look at the blockStatus byte in the first two chunks
3916 // These must be 0xFF to pass as OK.
3917 // todo: this function needs to be modifyable foir different NAND types
3918 // and different chunk sizes. Suggest make this into a per-device configurable
3920 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3924 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&spare,1);
3926 if(yaffs_CountBits(spare.blockStatus) < 7)
3931 if(spare.blockStatus != 0xFF)
3936 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
3939 if(yaffs_CountBits(spare.blockStatus) < 7)
3944 if(spare.blockStatus != 0xFF)
3954 static int yaffs_Scan(yaffs_Device *dev)
3962 yaffs_BlockState state;
3963 yaffs_Object *hardList = NULL;
3965 yaffs_BlockInfo *bi;
3968 yaffs_ObjectHeader *oh;
3970 yaffs_Object *parent;
3972 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
3975 // Scan all the blocks...
3977 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
3980 bi = yaffs_GetBlockInfo(dev,blk);
3981 yaffs_ClearChunkBits(dev,blk);
3983 bi->softDeletions = 0;
3984 state = YAFFS_BLOCK_STATE_SCANNING;
3987 if(yaffs_IsBlockBad(dev,blk))
3989 state = YAFFS_BLOCK_STATE_DEAD;
3990 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
3993 // Read each chunk in the block.
3995 for(c = 0; c < dev->nChunksPerBlock &&
3996 state == YAFFS_BLOCK_STATE_SCANNING; c++)
3998 // Read the spare area and decide what to do
3999 chunk = blk * dev->nChunksPerBlock + c;
4001 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
4004 // This block looks ok, now what's in this chunk?
4005 yaffs_GetTagsFromSpare(dev,&spare,&tags);
4007 if(yaffs_CountBits(spare.pageStatus) < 6)
4011 dev->nFreeChunks ++;
4012 //T((" %d %d deleted\n",blk,c));
4014 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
4016 // An unassigned chunk in the block
4017 // This means that either the block is empty or
4018 // this is the one being allocated from
4022 // the block is unused
4023 state = YAFFS_BLOCK_STATE_EMPTY;
4024 dev->nErasedBlocks++;
4028 // this is the block being allocated from
4029 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4030 state = YAFFS_BLOCK_STATE_ALLOCATING;
4031 dev->allocationBlock = blk;
4032 dev->allocationPage = c;
4035 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4037 else if(tags.chunkId > 0)
4041 yaffs_SetChunkBit(dev,blk,c);
4044 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4045 // PutChunkIntoFIle checks for a clash (two data chunks with
4046 // the same chunkId).
4047 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4048 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
4049 if(in->variant.fileVariant.scannedFileSize <endpos)
4051 in->variant.fileVariant.scannedFileSize = endpos;
4052 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4053 in->variant.fileVariant.fileSize =
4054 in->variant.fileVariant.scannedFileSize;
4058 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4062 // chunkId == 0, so it is an ObjectHeader.
4063 // Thus, we read in the object header and make the object
4064 yaffs_SetChunkBit(dev,blk,c);
4067 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
4069 oh = (yaffs_ObjectHeader *)chunkData;
4071 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4075 // We have already filled this one. We have a duplicate and need to resolve it.
4077 unsigned existingSerial = in->serial;
4078 unsigned newSerial = tags.serialNumber;
4080 if(((existingSerial+1) & 3) == newSerial)
4082 // Use new one - destroy the exisiting one
4083 yaffs_DeleteChunk(dev,in->chunkId,1);
4088 // Use existing - destroy this one.
4089 yaffs_DeleteChunk(dev,chunk,1);
4094 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4095 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4097 // We only load some info, don't fiddle with directory structure
4099 in->variantType = oh->type;
4101 in->st_mode = oh->st_mode;
4102 #ifdef CONFIG_YAFFS_WINCE
4103 in->win_atime[0] = oh->win_atime[0];
4104 in->win_ctime[0] = oh->win_ctime[0];
4105 in->win_mtime[0] = oh->win_mtime[0];
4106 in->win_atime[1] = oh->win_atime[1];
4107 in->win_ctime[1] = oh->win_ctime[1];
4108 in->win_mtime[1] = oh->win_mtime[1];
4110 in->st_uid = oh->st_uid;
4111 in->st_gid = oh->st_gid;
4112 in->st_atime = oh->st_atime;
4113 in->st_mtime = oh->st_mtime;
4114 in->st_ctime = oh->st_ctime;
4115 in->st_rdev = oh->st_rdev;
4117 in->chunkId = chunk;
4122 // we need to load this info
4125 in->variantType = oh->type;
4127 in->st_mode = oh->st_mode;
4128 #ifdef CONFIG_YAFFS_WINCE
4129 in->win_atime[0] = oh->win_atime[0];
4130 in->win_ctime[0] = oh->win_ctime[0];
4131 in->win_mtime[0] = oh->win_mtime[0];
4132 in->win_atime[1] = oh->win_atime[1];
4133 in->win_ctime[1] = oh->win_ctime[1];
4134 in->win_mtime[1] = oh->win_mtime[1];
4136 in->st_uid = oh->st_uid;
4137 in->st_gid = oh->st_gid;
4138 in->st_atime = oh->st_atime;
4139 in->st_mtime = oh->st_mtime;
4140 in->st_ctime = oh->st_ctime;
4141 in->st_rdev = oh->st_rdev;
4143 in->chunkId = chunk;
4145 yaffs_SetObjectName(in,oh->name);
4148 // directory stuff...
4149 // hook up to parent
4151 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4152 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4154 // Set up as a directory
4155 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4156 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4158 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4160 // Hoosterman, another problem....
4161 // We're trying to use a non-directory as a directory
4163 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan" TENDSTR)));
4167 yaffs_AddObjectToDirectory(parent,in);
4168 if(parent == dev->unlinkedDir)
4170 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4171 dev->nDeletedFiles++;
4174 // Note re hardlinks.
4175 // Since we might scan a hardlink before its equivalent object is scanned
4176 // we put them all in a list.
4177 // After scanning is complete, we should have all the objects, so we run through this
4178 // list and fix up all the chains.
4180 switch(in->variantType)
4182 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4184 case YAFFS_OBJECT_TYPE_FILE:
4185 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4186 in->variant.fileVariant.fileSize = oh->fileSize;
4189 case YAFFS_OBJECT_TYPE_HARDLINK:
4190 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4191 in->hardLinks.next = (struct list_head *)hardList;
4194 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4196 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4198 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4199 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4202 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4207 if(state == YAFFS_BLOCK_STATE_SCANNING)
4209 // If we got this far while scanning, then the block is fully allocated.
4210 state = YAFFS_BLOCK_STATE_FULL;
4213 bi->blockState = state;
4215 // Now let's see if it was dirty
4216 if( bi->pagesInUse == 0 &&
4217 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4219 yaffs_BlockBecameDirty(dev,blk);
4224 // Fix up the hard link chains.
4225 // We should now have scanned all the objects, now it's time to add these
4230 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4232 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4236 // Add the hardlink pointers
4237 hl->variant.hardLinkVariant.equivalentObject=in;
4238 list_add(&hl->hardLinks,&in->hardLinks);
4242 //Todo Need to report/handle this better.
4243 // Got a problem... hardlink to a non-existant object
4244 hl->variant.hardLinkVariant.equivalentObject=NULL;
4245 INIT_LIST_HEAD(&hl->hardLinks);
4252 struct list_head *i;
4253 struct list_head *n;
4256 // Soft delete all the unlinked files
4257 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
4261 l = list_entry(i, yaffs_Object,siblings);
4264 yaffs_SoftDeleteFile(l);
4275 ////////////////////////// Directory Functions /////////////////////////
4278 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
4281 if(obj->siblings.prev == NULL)
4284 INIT_LIST_HEAD(&obj->siblings);
4287 else if(!list_empty(&obj->siblings))
4289 // If it is holed up somewhere else, un hook it
4290 list_del_init(&obj->siblings);
4293 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
4294 obj->parent = directory;
4296 if(directory == obj->myDev->unlinkedDir)
4299 obj->myDev->nUnlinkedFiles++;
4300 obj->renameAllowed = 0;
4304 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4306 list_del_init(&obj->siblings);
4310 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
4314 struct list_head *i;
4315 char buffer[YAFFS_MAX_NAME_LENGTH+1];
4319 sum = yaffs_CalcNameSum(name);
4321 list_for_each(i,&directory->variant.directoryVariant.children)
4325 l = list_entry(i, yaffs_Object,siblings);
4327 // Special case for lost-n-found
4328 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4330 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
4335 else if(yaffs_SumCompare(l->sum, sum))
4338 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
4339 if(yaffs_strcmp(name,buffer) == 0)
4352 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
4354 struct list_head *i;
4358 list_for_each(i,&theDir->variant.directoryVariant.children)
4362 l = list_entry(i, yaffs_Object,siblings);
4375 // GetEquivalentObject dereferences any hard links to get to the
4378 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4380 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4382 // We want the object id of the equivalent object, not this one
4383 obj = obj->variant.hardLinkVariant.equivalentObject;
4389 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
4391 memset(name,0,buffSize);
4393 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4395 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
4397 else if(obj->chunkId <= 0)
4401 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
4402 strncpy(name,locName,buffSize - 1);
4405 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4406 else if(obj->shortName[0])
4408 strcpy(name,obj->shortName);
4413 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4414 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4416 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4418 if(obj->chunkId >= 0)
4420 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
4422 strncpy(name,oh->name,buffSize - 1);
4425 return strlen(name);
4428 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4431 // Dereference any hard linking
4432 obj = yaffs_GetEquivalentObject(obj);
4434 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4436 return obj->variant.fileVariant.fileSize;
4438 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4440 return strlen(obj->variant.symLinkVariant.alias);
4444 // Only a directory should drop through to here
4445 return YAFFS_BYTES_PER_CHUNK;
4449 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4452 struct list_head *i;
4456 count++; // the object itself
4458 list_for_each(i,&obj->hardLinks)
4460 count++; // add the hard links;
4467 int yaffs_GetObjectInode(yaffs_Object *obj)
4469 obj = yaffs_GetEquivalentObject(obj);
4471 return obj->objectId;
4474 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4476 obj = yaffs_GetEquivalentObject(obj);
4478 switch(obj->variantType)
4480 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
4481 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
4482 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
4483 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
4484 case YAFFS_OBJECT_TYPE_SPECIAL:
4485 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
4486 if(S_ISCHR(obj->st_mode)) return DT_CHR;
4487 if(S_ISBLK(obj->st_mode)) return DT_BLK;
4488 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
4489 default: return DT_REG; break;
4493 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4495 obj = yaffs_GetEquivalentObject(obj);
4496 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4498 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4502 return yaffs_CloneString("");
4506 #ifndef CONFIG_YAFFS_WINCE
4508 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4510 unsigned int valid = attr->ia_valid;
4512 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4513 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4514 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4516 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
4517 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
4518 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
4520 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4522 yaffs_UpdateObjectHeader(obj,NULL,1);
4527 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4529 unsigned int valid = 0;
4531 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
4532 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
4533 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
4535 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
4536 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
4537 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
4539 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4541 attr->ia_valid = valid;
4549 int yaffs_DumpObject(yaffs_Object *obj)
4551 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4553 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4555 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4557 // if(obj->chunkId >= 0)
4559 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4562 yaffs_GetObjectName(obj,name,256);
4564 T(YAFFS_TRACE_ALWAYS,(TSTR("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d type %d size %d\n" TENDSTR),
4565 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
4566 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4569 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4570 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
4571 obj->sum, obj->chunkId));
4572 switch(obj->variantType)
4574 case YAFFS_OBJECT_TYPE_FILE:
4575 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4577 case YAFFS_OBJECT_TYPE_DIRECTORY:
4578 YPRINTF((" DIRECTORY\n"));
4580 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4581 case YAFFS_OBJECT_TYPE_SYMLINK:
4582 case YAFFS_OBJECT_TYPE_UNKNOWN:
4591 ///////////////////////// Initialisation code ///////////////////////////
4595 int yaffs_GutsInitialise(yaffs_Device *dev)
4604 if(!yaffs_CheckStructures())
4606 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
4612 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
4618 if(dev->startBlock <= 0 ||
4619 (dev->endBlock - dev->startBlock) < 10)
4621 T(YAFFS_TRACE_ALWAYS,(TSTR("startBlock %d or endBlock %d invalid\n" TENDSTR),
4622 dev->startBlock, dev->endBlock));
4626 nBlocks = dev->endBlock - dev->startBlock + 1;
4630 // OK now calculate a few things for the device
4631 // Calculate chunkGroupBits.
4632 // We need to find the next power of 2 > than endBlock
4634 x = dev->nChunksPerBlock * (dev->endBlock+1);
4636 for(bits = extraBits = 0; x > 1; bits++)
4638 if(x & 1) extraBits++;
4642 if(extraBits > 0) bits++;
4645 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4646 // chunk range we're using is greater than 16 we need
4647 // to figure out chunk shift and chunkGroupSize
4650 dev->chunkGroupBits = 0;
4654 dev->chunkGroupBits = bits - 16;
4656 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4658 // Stuff to be taken out later
4659 dev->nBytesPerChunk = YAFFS_BYTES_PER_CHUNK;
4660 dev->nChunksPerBlock = YAFFS_CHUNKS_PER_BLOCK;
4663 // More device initialisation
4664 dev->garbageCollections = 0;
4665 dev->passiveGarbageCollections = 0;
4666 dev->currentDirtyChecker = 0;
4667 dev->bufferedBlock = -1;
4668 dev->doingBufferedBlockRewrite = 0;
4669 dev->nDeletedFiles = 0;
4670 dev->nBackgroundDeletions=0;
4671 dev->nUnlinkedFiles = 0;
4674 dev->tagsEccFixed=0;
4675 dev->tagsEccUnfixed=0;
4677 dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
4682 yaffs_InitialiseBlocks(dev,nBlocks);
4684 yaffs_InitialiseTnodes(dev);
4686 yaffs_InitialiseObjects(dev);
4688 if(dev->nShortOpCaches > 0)
4692 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
4694 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
4697 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
4699 for(i=0; i < dev->nShortOpCaches; i++)
4701 dev->srCache[i].object = NULL;
4702 dev->srCache[i].lastUse = 0;
4703 dev->srCache[i].dirty = 0;
4711 // Initialise the unlinked, root and lost and found directories
4712 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4714 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4716 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4717 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4718 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4721 // Now scan the flash.
4725 dev->nPageReads = 0;
4726 dev->nPageWrites = 0;
4727 dev->nBlockErasures = 0;
4729 dev->nRetriedWrites = 0;
4730 dev->nRetiredBlocks = 0;
4737 void yaffs_Deinitialise(yaffs_Device *dev)
4742 yaffs_DeinitialiseBlocks(dev);
4743 yaffs_DeinitialiseTnodes(dev);
4744 yaffs_DeinitialiseObjects(dev);
4751 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4753 int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
4755 struct list_head *i;
4759 // To the free chunks add the chunks that are in the deleted unlinked files.
4760 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4762 l = list_entry(i, yaffs_Object,siblings);
4766 nFree += l->nDataChunks;
4771 printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
4773 if(nFree < 0) nFree = 0;
4781 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4787 yaffs_BlockInfo *blk;
4789 struct list_head *i;
4792 for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
4794 blk = yaffs_GetBlockInfo(dev,b);
4796 switch(blk->blockState)
4798 case YAFFS_BLOCK_STATE_EMPTY:
4799 case YAFFS_BLOCK_STATE_ALLOCATING:
4800 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
4808 // To the free chunks add the chunks that are in the deleted unlinked files.
4809 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4813 l = list_entry(i, yaffs_Object,siblings);
4817 pending += l->nDataChunks;
4824 //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
4826 if(nFree != dev->nFreeChunks)
4828 // printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
4833 if(nFree < 0) nFree = 0;
4841 /////////////////// YAFFS test code //////////////////////////////////
4843 #define yaffs_CheckStruct(structure,syze, name) \
4844 if(sizeof(structure) != syze) \
4846 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
4847 return YAFFS_FAIL; \
4851 static int yaffs_CheckStructures(void)
4853 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4854 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4855 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4856 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
4857 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4859 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4866 void yaffs_GutsTest(yaffs_Device *dev)
4869 if(yaffs_CheckStructures() != YAFFS_OK)
4871 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
4875 yaffs_TnodeTest(dev);
4876 yaffs_ObjectTest(dev);