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.25 2003-05-20 22:30:35 charles Exp $";
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
24 #define YAFFS_PASSIVE_GC_CHUNKS 2
27 // Use Steven Hill's ECC struff instead
28 // External functions for ECC on data
29 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
30 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
31 #define yaffs_ECCCalculate(data,ecc) nand_calculate_ecc(data,ecc)
32 #define yaffs_ECCCorrect(data,read_ecc,calc_ecc) nand_correct_ecc(data,read_ecc,calc_ecc)
34 #include "yaffs_ecc.h"
37 // countBits is a quick way of counting the number of bits in a byte.
38 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
40 static const char yaffs_countBitsTable[256] =
42 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
43 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
44 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
45 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
46 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
47 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
48 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
49 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
50 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
51 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
52 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
53 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
54 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
55 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
56 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
57 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
60 static int yaffs_CountBits(__u8 x)
63 retVal = yaffs_countBitsTable[x];
70 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
71 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
72 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
73 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
75 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
76 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
77 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force);
78 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND);
79 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
80 static int yaffs_CheckStructures(void);
81 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
82 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
84 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
87 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
88 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
89 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
90 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare);
91 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare);
93 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
95 static int yaffs_UnlinkWorker(yaffs_Object *obj);
96 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj);
98 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1);
102 loff_t yaffs_GetFileSize(yaffs_Object *obj);
104 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
105 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
108 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
110 #ifdef YAFFS_PARANOID
111 static int yaffs_CheckFileSanity(yaffs_Object *in);
113 #define yaffs_CheckFileSanity(in)
116 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
117 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
119 // Chunk bitmap manipulations
121 static __inline __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
123 if(blk < dev->startBlock || blk > dev->endBlock)
125 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
128 return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->startBlock));
131 static __inline__ void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
133 __u8 *blkBits = yaffs_BlockBits(dev,blk);
135 memset(blkBits,0,dev->chunkBitmapStride);
138 static __inline__ void yaffs_ClearChunkBit(yaffs_Device *dev,int blk,int chunk)
140 __u8 *blkBits = yaffs_BlockBits(dev,blk);
142 blkBits[chunk/8] &= ~ (1<<(chunk & 7));
145 static __inline__ void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
147 __u8 *blkBits = yaffs_BlockBits(dev,blk);
149 blkBits[chunk/8] |= (1<<(chunk & 7));
152 static __inline__ int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
154 __u8 *blkBits = yaffs_BlockBits(dev,blk);
155 return (blkBits[chunk/8] & (1<<(chunk & 7))) ? 1 :0;
158 static __inline__ int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
160 __u8 *blkBits = yaffs_BlockBits(dev,blk);
162 for(i = 0; i < dev->chunkBitmapStride; i++)
164 if(*blkBits) return 1;
170 // Function to manipulate block info
171 static __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
173 if(blk < dev->startBlock || blk > dev->endBlock)
175 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),blk));
178 return &dev->blockInfo[blk - dev->startBlock];
182 static __inline__ int yaffs_HashFunction(int n)
184 return (n % YAFFS_NOBJECT_BUCKETS);
188 yaffs_Object *yaffs_Root(yaffs_Device *dev)
193 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
195 return dev->lostNFoundDir;
199 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
201 if(chunkInNAND < dev->startBlock * dev->nChunksPerBlock)
203 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
208 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
213 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
217 int doErrorCorrection)
220 yaffs_Spare localSpare;
229 // If we don't have a real spare, then we use a local one.
230 // Need this for the calculation of the ecc
237 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
238 if(data && doErrorCorrection)
241 //Todo handle any errors
242 int eccResult1,eccResult2;
245 yaffs_ECCCalculate(data,calcEcc);
246 eccResult1 = yaffs_ECCCorrect (data,spare->ecc1, calcEcc);
247 yaffs_ECCCalculate(&data[256],calcEcc);
248 eccResult2 = yaffs_ECCCorrect(&data[256],spare->ecc2, calcEcc);
252 T(YAFFS_TRACE_ERROR, (TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
255 else if(eccResult1<0)
257 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
263 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
266 else if(eccResult2<0)
268 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
272 if(eccResult1 || eccResult2)
274 // Hoosterman, we had a data problem on this page
275 yaffs_HandleReadDataError(dev,chunkInNAND);
281 // Must allocate enough memory for spare+2*sizeof(int) for ecc results from device.
282 struct yaffs_NANDSpare nspare;
283 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
284 memcpy (spare, &nspare, sizeof(yaffs_Spare));
285 if(data && doErrorCorrection)
289 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
291 else if(nspare.eccres1<0)
293 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
298 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
300 else if(nspare.eccres2<0)
302 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
305 if(nspare.eccres1 || nspare.eccres2)
307 // Hoosterman, we had a data problem on this page
308 yaffs_HandleReadDataError(dev,chunkInNAND);
317 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
321 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
322 static __u8 data[YAFFS_BYTES_PER_CHUNK];
323 // Might as well always allocate the larger size for dev->useNANDECC == true;
324 static __u8 spare[sizeof(struct yaffs_NANDSpare)];
326 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
330 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
334 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL;
335 if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
344 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
346 dev->nBlockErasures++;
347 return dev->eraseBlockInNAND(dev,blockInNAND);
350 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
352 return dev->initialiseNAND(dev);
355 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
362 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
366 chunk = yaffs_AllocateChunk(dev,useReserve);
371 // First check this chunk is erased...
372 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
373 writeOk = yaffs_CheckChunkErased(dev,chunk);
377 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
381 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
387 // If verify fails, then delete this chunk and try again
388 // To verify we compare everything except the block and
389 // page status bytes.
390 // NB We check a raw read without ECC correction applied
391 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
393 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
394 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
397 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
406 // Copy the data into the write buffer.
407 // NB We do this at the end to prevent duplicates in the case of a write error.
409 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
413 yaffs_HandleWriteChunkError(dev,chunk);
417 } while(chunk >= 0 && ! writeOk);
421 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
422 dev->nRetriedWrites+= (attempts - 1);
429 // Functions for robustisizing
433 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
435 // Ding the blockStatus in the first two pages of the block.
439 memset(&spare, 0xff,sizeof(yaffs_Spare));
441 spare.blockStatus = 0;
443 // TODO change this retirement marking for other NAND types
444 yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock, NULL , &spare);
445 yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock + 1, NULL , &spare);
447 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
448 dev->nRetiredBlocks++;
453 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
455 dev->doingBufferedBlockRewrite = 1;
457 // Remove erased chunks
458 // Rewrite existing chunks to a new block
459 // Set current write block to the new block
461 dev->doingBufferedBlockRewrite = 0;
467 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
469 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
471 // Mark the block for retirement
472 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
473 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
477 // Just do a garbage collection on the affected block then retire the block
482 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
486 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare)
490 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare)
494 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
496 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
498 // Mark the block for retirement
499 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
501 yaffs_DeleteChunk(dev,chunkInNAND,1);
507 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1)
511 if( memcmp(d0,d1,YAFFS_BYTES_PER_CHUNK) != 0 ||
512 s0->tagByte0 != s1->tagByte0 ||
513 s0->tagByte1 != s1->tagByte1 ||
514 s0->tagByte2 != s1->tagByte2 ||
515 s0->tagByte3 != s1->tagByte3 ||
516 s0->tagByte4 != s1->tagByte4 ||
517 s0->tagByte5 != s1->tagByte5 ||
518 s0->tagByte6 != s1->tagByte6 ||
519 s0->tagByte7 != s1->tagByte7 ||
520 s0->ecc1[0] != s1->ecc1[0] ||
521 s0->ecc1[1] != s1->ecc1[1] ||
522 s0->ecc1[2] != s1->ecc1[2] ||
523 s0->ecc2[0] != s1->ecc2[0] ||
524 s0->ecc2[1] != s1->ecc2[1] ||
525 s0->ecc2[2] != s1->ecc2[2] )
534 ///////////////////////// Object management //////////////////
535 // List of spare objects
536 // The list is hooked together using the first pointer
539 // static yaffs_Object *yaffs_freeObjects = NULL;
541 // static int yaffs_nFreeObjects;
543 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
545 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
548 static __u16 yaffs_CalcNameSum(const char *name)
553 __u8 *bname = (__u8 *)name;
556 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
559 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
560 sum += toupper(*bname) * i;
571 void yaffs_SetObjectName(yaffs_Object *obj, const char *name)
573 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
574 if(name && strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
576 strcpy(obj->shortName,name);
580 obj->shortName[0]='\0';
583 obj->sum = yaffs_CalcNameSum(name);
586 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
588 yaffs_ECCCalculate(data , spare->ecc1);
589 yaffs_ECCCalculate(&data[256] , spare->ecc2);
592 void yaffs_CalcTagsECC(yaffs_Tags *tags)
596 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
603 for(i = 0; i < 8; i++)
605 for(j = 1; j &0xff; j<<=1)
620 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
622 unsigned ecc = tags->ecc;
624 yaffs_CalcTagsECC(tags);
630 // TODO: Handle the failure better. Retire?
631 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
635 b[ecc / 8] ^= (1 << (ecc & 7));
637 // Now recvalc the ecc
638 yaffs_CalcTagsECC(tags);
640 return 1; // recovered error
644 // Wierd ecc failure value
645 // TODO Need to do somethiong here
646 return -1; //unrecovered error
653 ///////////////////////// TNODES ///////////////////////
655 // List of spare tnodes
656 // The list is hooked together using the first pointer
659 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
661 // static int yaffs_nFreeTnodes;
663 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
667 // yaffs_CreateTnodes creates a bunch more tnodes and
668 // adds them to the tnode free list.
669 // Don't use this function directly
671 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
674 yaffs_Tnode *newTnodes;
675 yaffs_TnodeList *tnl;
677 if(nTnodes < 1) return YAFFS_OK;
681 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
685 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
689 // Hook them into the free list
690 for(i = 0; i < nTnodes - 1; i++)
692 newTnodes[i].internal[0] = &newTnodes[i+1];
693 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
694 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = 1;
698 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
699 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
700 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = 1;
702 dev->freeTnodes = newTnodes;
703 dev->nFreeTnodes+= nTnodes;
704 dev->nTnodesCreated += nTnodes;
706 // Now add this bunch of tnodes to a list for freeing up.
707 // NB If we can't add this to the management list it isn't fatal
708 // but it just means we can't free this bunch of tnodes later.
709 tnl = YMALLOC(sizeof(yaffs_TnodeList));
712 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
717 tnl->tnodes = newTnodes;
718 tnl->next = dev->allocatedTnodeList;
719 dev->allocatedTnodeList = tnl;
723 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
730 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
731 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
733 yaffs_Tnode *tn = NULL;
735 // If there are none left make more
738 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
743 tn = dev->freeTnodes;
744 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
745 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 1)
747 // Hoosterman, this thing looks like it isn't in the list
748 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 1" TENDSTR)));
751 dev->freeTnodes = dev->freeTnodes->internal[0];
754 memset(tn,0,sizeof(yaffs_Tnode));
762 // FreeTnode frees up a tnode and puts it back on the free list
763 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
767 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
768 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 0)
770 // Hoosterman, this thing looks like it is already in the list
771 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 2" TENDSTR)));
773 tn->internal[YAFFS_NTNODES_INTERNAL] = 1;
775 tn->internal[0] = dev->freeTnodes;
776 dev->freeTnodes = tn;
782 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
784 // Free the list of allocated tnodes
786 while(dev->allocatedTnodeList)
788 YFREE(dev->allocatedTnodeList->tnodes);
789 dev->allocatedTnodeList = dev->allocatedTnodeList->next;
792 dev->freeTnodes = NULL;
793 dev->nFreeTnodes = 0;
796 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
798 dev->allocatedTnodeList = NULL;
799 dev->freeTnodes = NULL;
800 dev->nFreeTnodes = 0;
801 dev->nTnodesCreated = 0;
806 void yaffs_TnodeTest(yaffs_Device *dev)
811 yaffs_Tnode *tn[1000];
813 YINFO("Testing TNodes");
815 for(j = 0; j < 50; j++)
817 for(i = 0; i < 1000; i++)
819 tn[i] = yaffs_GetTnode(dev);
822 YALERT("Getting tnode failed");
825 for(i = 0; i < 1000; i+=3)
827 yaffs_FreeTnode(dev,tn[i]);
836 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
838 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
839 // The look up tree is represented by the top tnode and the number of topLevel
840 // in the tree. 0 means only the level 0 tnode is in the tree.
843 // FindLevel0Tnode finds the level 0 tnode, if one exists.
844 // Used when reading.....
845 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
848 yaffs_Tnode *tn = fStruct->top;
850 int requiredTallness;
851 int level = fStruct->topLevel;
853 // Check sane level and chunk Id
854 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
857 // sprintf(str,"Bad level %d",level);
862 if(chunkId > YAFFS_MAX_CHUNK_ID)
865 // sprintf(str,"Bad chunkId %d",chunkId);
870 // First check we're tall enough (ie enough topLevel)
872 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
873 requiredTallness = 0;
876 i >>= YAFFS_TNODES_INTERNAL_BITS;
881 if(requiredTallness > fStruct->topLevel)
883 // Not tall enough, so we can't find it, return NULL.
888 // Traverse down to level 0
889 while (level > 0 && tn)
891 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
892 YAFFS_TNODES_INTERNAL_MASK];
900 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
901 // This happens in two steps:
902 // 1. If the tree isn't tall enough, then make it taller.
903 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
905 // Used when modifying the tree.
907 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
912 int requiredTallness;
919 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
921 // Check sane level and page Id
922 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
925 // sprintf(str,"Bad level %d",fStruct->topLevel);
930 if(chunkId > YAFFS_MAX_CHUNK_ID)
933 // sprintf(str,"Bad chunkId %d",chunkId);
938 // First check we're tall enough (ie enough topLevel)
940 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
941 requiredTallness = 0;
944 x >>= YAFFS_TNODES_INTERNAL_BITS;
948 //T((TSTR(" required=%d"),requiredTallness));
951 if(requiredTallness > fStruct->topLevel)
953 // Not tall enough,gotta make the tree taller
954 for(i = fStruct->topLevel; i < requiredTallness; i++)
956 //T((TSTR(" add new top")));
958 tn = yaffs_GetTnode(dev);
962 tn->internal[0] = fStruct->top;
967 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
971 fStruct->topLevel = requiredTallness;
975 // Traverse down to level 0, adding anything we need
977 l = fStruct->topLevel;
981 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
982 YAFFS_TNODES_INTERNAL_MASK;
984 //T((TSTR(" [%d:%d]"),l,i));
988 //T((TSTR(" added")));
990 tn->internal[x] = yaffs_GetTnode(dev);
993 tn = tn->internal[x];
1003 // DeleteWorker scans backwards through the tnode tree and deletes all the
1004 // chunks and tnodes in the file
1005 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1007 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1023 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1027 if(limit && (*limit) < 0)
1033 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1034 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1038 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1039 tn->internal[i] = NULL;
1044 return (allDone) ? 1 : 0;
1050 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1056 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1058 theChunk = tn->level0[i] << in->myDev->chunkGroupBits;
1060 // Now we need to search for it
1061 for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
1063 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
1064 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
1078 yaffs_DeleteChunk(in->myDev,theChunk,1);
1095 return (i < 0) ? 1 : 0;
1106 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1107 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1109 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1111 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1116 yaffs_BlockInfo *theBlock;
1128 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1132 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1133 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1136 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1137 tn->internal[i] = NULL;
1141 //Hoosterman... how could this happen.
1145 return (allDone) ? 1 : 0;
1150 for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1154 theChunk = (tn->level0[i] << in->myDev->chunkGroupBits);
1155 T(YAFFS_TRACE_SCAN,(TSTR("soft delete tch %d cgb %d chunk %d" TENDSTR),
1156 tn->level0[i],in->myDev->chunkGroupBits,theChunk));
1158 theBlock = yaffs_GetBlockInfo(in->myDev, theChunk/in->myDev->nChunksPerBlock);
1161 theBlock->softDeletions++;
1179 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1182 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1185 if(obj->nDataChunks <= 0)
1187 // Empty file, just delete it immediately
1188 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1189 obj->variant.fileVariant.top = NULL;
1190 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1191 yaffs_DoGenericObjectDeletion(obj);
1195 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1196 obj->softDeleted = 1;
1205 // Pruning removes any part of the file structure tree that is beyond the
1206 // bounds of the file (ie that does not point to chunks).
1208 // A file should only get pruned when its size is reduced.
1210 // Before pruning, the chunks must be pulled from the tree and the
1211 // level 0 tnode entries must be zeroed out.
1212 // Could also use this for file deletion, but that's probably better handled
1213 // by a special case.
1215 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1217 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1226 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1228 if(tn->internal[i] && level > 0)
1230 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1239 if(hasData == 0 && del0)
1241 // Free and return NULL
1243 yaffs_FreeTnode(dev,tn);
1253 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1260 if(fStruct->topLevel > 0)
1262 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1264 // Now we have a tree with all the non-zero branches NULL but the height
1265 // is the same as it was.
1266 // Let's see if we can trim internal tnodes to shorten the tree.
1267 // We can do this if only the 0th element in the tnode is in use
1268 // (ie all the non-zero are NULL)
1270 while(fStruct->topLevel && !done)
1275 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1285 fStruct->top = tn->internal[0];
1286 fStruct->topLevel--;
1287 yaffs_FreeTnode(dev,tn);
1303 /////////////////////// End of File Structure functions. /////////////////
1305 // yaffs_CreateFreeObjects creates a bunch more objects and
1306 // adds them to the object free list.
1307 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1310 yaffs_Object *newObjects;
1311 yaffs_ObjectList *list;
1313 if(nObjects < 1) return YAFFS_OK;
1315 // make these things
1317 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1321 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1325 // Hook them into the free list
1326 for(i = 0; i < nObjects - 1; i++)
1328 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1331 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1332 dev->freeObjects = newObjects;
1333 dev->nFreeObjects+= nObjects;
1334 dev->nObjectsCreated+= nObjects;
1336 // Now add this bunch of Objects to a list for freeing up.
1338 list = YMALLOC(sizeof(yaffs_ObjectList));
1341 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1345 list->objects = newObjects;
1346 list->next = dev->allocatedObjectList;
1347 dev->allocatedObjectList = list;
1356 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1357 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1359 yaffs_Object *tn = NULL;
1361 // If there are none left make more
1362 if(!dev->freeObjects)
1364 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1367 if(dev->freeObjects)
1369 tn = dev->freeObjects;
1370 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1371 dev->nFreeObjects--;
1373 // Now sweeten it up...
1375 memset(tn,0,sizeof(yaffs_Object));
1378 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1379 INIT_LIST_HEAD(&(tn->hardLinks));
1380 INIT_LIST_HEAD(&(tn->hashLink));
1381 INIT_LIST_HEAD(&tn->siblings);
1383 // Add it to the lost and found directory.
1384 // NB Can't put root or lostNFound in lostNFound so
1385 // check if lostNFound exists first
1386 if(dev->lostNFoundDir)
1388 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1396 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1399 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1402 obj->fake = 1; // it is fake so it has no NAND presence...
1403 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1404 obj->unlinkAllowed= 0; // ... or unlink it
1407 obj->st_mode = mode;
1409 obj->chunkId = 0; // Not a valid chunk.
1417 static void yaffs_UnhashObject(yaffs_Object *tn)
1420 yaffs_Device *dev = tn->myDev;
1423 // If it is still linked into the bucket list, free from the list
1424 if(!list_empty(&tn->hashLink))
1426 list_del_init(&tn->hashLink);
1427 bucket = yaffs_HashFunction(tn->objectId);
1428 dev->objectBucket[bucket].count--;
1434 // FreeObject frees up a Object and puts it back on the free list
1435 static void yaffs_FreeObject(yaffs_Object *tn)
1438 yaffs_Device *dev = tn->myDev;
1440 yaffs_UnhashObject(tn);
1442 // Link into the free list.
1443 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1444 dev->freeObjects = tn;
1445 dev->nFreeObjects++;
1451 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1453 // Free the list of allocated Objects
1455 while( dev->allocatedObjectList)
1457 YFREE(dev->allocatedObjectList->objects);
1458 dev->allocatedObjectList = dev->allocatedObjectList->next;
1461 dev->freeObjects = NULL;
1462 dev->nFreeObjects = 0;
1465 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1469 dev->allocatedObjectList = NULL;
1470 dev->freeObjects = NULL;
1471 dev->nFreeObjects = 0;
1473 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1475 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1476 dev->objectBucket[i].count = 0;
1486 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1491 int lowest = 999999;
1494 // First let's see if we can find one that's empty.
1496 for(i = 0; i < 10 && lowest > 0; i++)
1499 x %= YAFFS_NOBJECT_BUCKETS;
1500 if(dev->objectBucket[x].count < lowest)
1502 lowest = dev->objectBucket[x].count;
1508 // If we didn't find an empty list, then try
1509 // looking a bit further for a short one
1511 for(i = 0; i < 10 && lowest > 3; i++)
1514 x %= YAFFS_NOBJECT_BUCKETS;
1515 if(dev->objectBucket[x].count < lowest)
1517 lowest = dev->objectBucket[x].count;
1526 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1528 int bucket = yaffs_FindNiceObjectBucket(dev);
1530 // Now find an object value that has not already been taken
1531 // by scanning the list.
1534 struct list_head *i;
1536 __u32 n = (__u32)bucket;
1538 //yaffs_CheckObjectHashSanity();
1543 n += YAFFS_NOBJECT_BUCKETS;
1544 if(1 ||dev->objectBucket[bucket].count > 0)
1546 list_for_each(i,&dev->objectBucket[bucket].list)
1548 // If there is already one in the list
1549 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1557 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1562 void yaffs_HashObject(yaffs_Object *in)
1564 int bucket = yaffs_HashFunction(in->objectId);
1565 yaffs_Device *dev = in->myDev;
1567 if(!list_empty(&in->hashLink))
1573 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1574 dev->objectBucket[bucket].count++;
1578 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1580 int bucket = yaffs_HashFunction(number);
1581 struct list_head *i;
1584 list_for_each(i,&dev->objectBucket[bucket].list)
1586 // Look if it is in the list
1589 in = list_entry(i, yaffs_Object,hashLink);
1590 if(in->objectId == number)
1602 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1605 yaffs_Object *theObject;
1609 number = yaffs_CreateNewObjectNumber(dev);
1612 theObject = yaffs_AllocateEmptyObject(dev);
1616 theObject->fake = 0;
1617 theObject->renameAllowed = 1;
1618 theObject->unlinkAllowed = 1;
1619 theObject->objectId = number;
1620 yaffs_HashObject(theObject);
1621 theObject->variantType = type;
1622 #ifdef CONFIG_YAFFS_WINCE
1623 yfsd_WinFileTimeNow(theObject->win_atime);
1624 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1625 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1628 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1632 case YAFFS_OBJECT_TYPE_FILE:
1633 theObject->variant.fileVariant.fileSize = 0;
1634 theObject->variant.fileVariant.scannedFileSize = 0;
1635 theObject->variant.fileVariant.topLevel = 0;
1636 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1638 case YAFFS_OBJECT_TYPE_DIRECTORY:
1639 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1641 case YAFFS_OBJECT_TYPE_SYMLINK:
1642 // No action required
1644 case YAFFS_OBJECT_TYPE_HARDLINK:
1645 // No action required
1647 case YAFFS_OBJECT_TYPE_SPECIAL:
1648 // No action required
1650 case YAFFS_OBJECT_TYPE_UNKNOWN:
1651 // todo this should not happen
1659 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1661 yaffs_Object *theObject = NULL;
1665 theObject = yaffs_FindObjectByNumber(dev,number);
1670 theObject = yaffs_CreateNewObject(dev,number,type);
1677 char *yaffs_CloneString(const char *str)
1679 char *newStr = NULL;
1683 newStr = YMALLOC(strlen(str) + 1);
1692 // Mknod (create) a new object.
1693 // equivalentObject only has meaning for a hard link;
1694 // aliasString only has meaning for a sumlink.
1695 // rdev only has meaning for devices (a subset of special objects)
1696 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1697 yaffs_Object *parent,
1702 yaffs_Object *equivalentObject,
1703 const char *aliasString,
1708 yaffs_Device *dev = parent->myDev;
1710 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1711 if(yaffs_FindObjectByName(parent,name))
1716 in = yaffs_CreateNewObject(dev,-1,type);
1722 in->variantType = type;
1726 #ifdef CONFIG_YAFFS_WINCE
1727 yfsd_WinFileTimeNow(in->win_atime);
1728 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1729 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[0];
1732 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1737 in->nDataChunks = 0;
1739 yaffs_SetObjectName(in,name);
1742 yaffs_AddObjectToDirectory(parent,in);
1744 in->myDev = parent->myDev;
1749 case YAFFS_OBJECT_TYPE_SYMLINK:
1750 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1752 case YAFFS_OBJECT_TYPE_HARDLINK:
1753 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1754 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1755 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1757 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1758 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1759 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1760 case YAFFS_OBJECT_TYPE_UNKNOWN:
1764 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1765 yaffs_UpdateObjectHeader(in,name,0) < 0)
1767 // Could not create the object header, fail the creation
1768 yaffs_AbortHalfCreatedObject(in);
1777 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1779 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1782 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1784 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1787 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1789 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1792 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1794 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1797 // NB yaffs_Link returns the object id of the equivalent object.
1798 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1800 // Get the real object in case we were fed a hard link as an equivalent object
1801 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1803 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1805 return equivalentObject;
1815 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1821 newDir = obj->parent; // use the old directory
1824 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1826 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1827 // duplicate names are allowed.
1828 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1831 !yaffs_FindObjectByName(newDir,newName)) &&
1832 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1834 yaffs_SetObjectName(obj,newName);
1837 yaffs_AddObjectToDirectory(newDir,obj);
1839 if(unlinkOp) obj->unlinked = 1;
1842 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1853 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1858 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1859 // Special case for WinCE.
1860 // While look-up is case insensitive, the name isn't.
1861 // THerefore we might want to change x.txt to X.txt
1862 if(oldDir == newDir && _stricmp(oldName,newName) == 0)
1868 obj = yaffs_FindObjectByName(oldDir,oldName);
1869 if(obj && obj->renameAllowed)
1871 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1878 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1880 // Scan the buckets and check that the lists
1881 // have as many members as the count says there are
1884 struct list_head *j;
1887 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1891 list_for_each(j,&dev->objectBucket[bucket].list)
1896 if(countEm != dev->objectBucket[bucket].count)
1898 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1907 void yaffs_ObjectTest(yaffs_Device *dev)
1909 yaffs_Object *in[1000];
1911 yaffs_Object *inold[1000];
1915 memset(in,0,1000*sizeof(yaffs_Object *));
1916 memset(inold,0,1000*sizeof(yaffs_Object *));
1918 yaffs_CheckObjectHashSanity(dev);
1920 for(j = 0; j < 10; j++)
1924 for(i = 0; i < 1000; i++)
1926 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1929 YINFO("No more inodes");
1933 inNo[i] = in[i]->objectId;
1937 for(i = 0; i < 1000; i++)
1939 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1941 //T(("Differnce in look up test\n"));
1945 // T(("Look up ok\n"));
1949 yaffs_CheckObjectHashSanity(dev);
1951 for(i = 0; i < 1000; i+=3)
1953 yaffs_FreeObject(in[i]);
1958 yaffs_CheckObjectHashSanity(dev);
1965 /////////////////////////// Block Management and Page Allocation ///////////////////
1968 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1970 dev->allocationBlock = -1; // force it to get a new one
1971 //Todo we're assuming the malloc will pass.
1972 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1973 // Set up dynamic blockinfo stuff.
1974 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
1975 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1976 if(dev->blockInfo && dev->chunkBits)
1978 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1979 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
1987 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1989 YFREE(dev->blockInfo);
1990 dev->blockInfo = NULL;
1991 YFREE(dev->chunkBits);
1992 dev->chunkBits = NULL;
1995 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1996 // for garbage collection.
1998 static int yaffs_FindDirtiestBlock(yaffs_Device *dev,int aggressive)
2001 int b = dev->currentDirtyChecker;
2007 yaffs_BlockInfo *bi;
2009 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2012 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2015 iterations = dev->endBlock - dev->startBlock + 1;
2019 iterations = dev->endBlock - dev->startBlock + 1;
2020 iterations = iterations / 16;
2021 if(iterations > 200)
2027 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2030 if ( b < dev->startBlock || b > dev->endBlock)
2032 b = dev->startBlock;
2035 if(b < dev->startBlock || b > dev->endBlock)
2037 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2041 bi = yaffs_GetBlockInfo(dev,b);
2043 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2044 (bi->pagesInUse - bi->softDeletions )< pagesInUse)
2047 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2051 dev->currentDirtyChecker = b;
2057 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2059 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2063 // If the block is still healthy erase it and mark as clean.
2064 // If the block has had a data failure, then retire it.
2065 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2067 if(!bi->needsRetiring)
2069 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2072 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2079 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2080 dev->nErasedBlocks++;
2082 bi->softDeletions = 0;
2083 yaffs_ClearChunkBits(dev,blockNo);
2085 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2089 yaffs_RetireBlock(dev,blockNo);
2090 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2095 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2099 yaffs_BlockInfo *bi;
2101 if(dev->nErasedBlocks < 1)
2103 // Hoosterman we've got a problem.
2104 // Can't get space to gc
2105 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during gc" TENDSTR)));
2110 // Find an empty block.
2112 for(i = dev->startBlock; i <= dev->endBlock; i++)
2114 dev->allocationBlockFinder++;
2115 if(dev->allocationBlockFinder <dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2117 dev->allocationBlockFinder = dev->startBlock;
2120 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2122 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2124 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2125 dev->nErasedBlocks--;
2126 return dev->allocationBlockFinder;
2135 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2138 yaffs_BlockInfo *bi;
2140 if(dev->allocationBlock < 0)
2142 // Get next block to allocate off
2143 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2144 dev->allocationPage = 0;
2147 if(!useReserve && dev->nErasedBlocks <= dev->nReservedBlocks)
2149 // Not enough space to allocate unless we're allowed to use the reserve.
2153 // Next page please....
2154 if(dev->allocationBlock >= 0)
2156 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2158 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2159 dev->allocationPage;
2161 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2163 dev->allocationPage++;
2167 // If the block is full set the state to full
2168 if(dev->allocationPage >= dev->nChunksPerBlock)
2170 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2171 dev->allocationBlock = -1;
2178 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2183 // To determine if we have enough space we just look at the
2184 // number of erased blocks.
2185 // The cache is allowed to use reserved blocks.
2187 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2189 return (dev->nErasedBlocks >= dev->nReservedBlocks);
2193 static int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2203 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
2205 // yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2207 yaffs_Object *object;
2209 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2211 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2212 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2213 chunkInBlock++, oldChunk++ )
2215 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2218 // This page is in use and might need to be copied off
2222 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2224 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
2226 yaffs_GetTagsFromSpare(dev,&spare,&tags);
2228 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2230 if(object && object->deleted && tags.chunkId != 0)
2232 // Data chunk in a deleted file, throw it away
2233 // It's a deleted data chunk,
2234 // No need to copy this, just forget about it and fix up the
2237 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2238 object->nDataChunks--;
2240 if(object->nDataChunks <= 0)
2242 // Time to delete the file too
2243 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2244 object->variant.fileVariant.top = NULL;
2245 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2246 yaffs_DoGenericObjectDeletion(object);
2250 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2252 // Deleted object header with no data chunks.
2253 // Can be discarded and the file deleted.
2254 object->chunkId = 0;
2255 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2256 object->variant.fileVariant.top = NULL;
2257 yaffs_DoGenericObjectDeletion(object);
2262 // It's either a data chunk in a live file or
2263 // an ObjectHeader, so we're interested in it.
2264 // NB Need to keep the ObjectHeaders of deleted files
2265 // until the whole file has been deleted off
2266 tags.serialNumber++;
2267 yaffs_LoadTagsIntoSpare(&spare,&tags);
2271 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
2278 // Ok, now fix up the Tnodes etc.
2280 if(tags.chunkId == 0)
2283 object->chunkId = newChunk;
2287 // It's a data chunk
2288 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2292 yaffs_DeleteChunk(dev,oldChunk,markNAND);
2301 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2303 // find a file to delete
2304 struct list_head *i;
2308 //Scan the unlinked files looking for one to delete
2309 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2313 l = list_entry(i, yaffs_Object,siblings);
2324 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2326 // This does background deletion on unlinked files.. only deleted ones.
2327 // If we don't have a file we're working on then find one
2328 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2330 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2333 // OK, we're working on a file...
2334 if(dev->unlinkedDeletion)
2336 yaffs_Object *obj = dev->unlinkedDeletion;
2338 int limit; // Number of chunks to delete in a file.
2339 // NB this can be exceeded, but not by much.
2343 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2345 if(obj->nDataChunks == 0)
2347 // Done all the deleting of data chunks.
2348 // Now dump the header and clean up
2349 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2350 obj->variant.fileVariant.top = NULL;
2351 yaffs_DoGenericObjectDeletion(obj);
2352 dev->nDeletedFiles--;
2353 dev->nUnlinkedFiles--;
2354 dev->nBackgroundDeletions++;
2355 dev->unlinkedDeletion = NULL;
2362 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
2363 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2368 //yaffs_DoUnlinkedFileDeletion(dev);
2370 if(dev->nErasedBlocks <= (dev->nReservedBlocks + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2377 block = yaffs_FindDirtiestBlock(dev,aggressive);
2381 dev->garbageCollections++;
2382 return yaffs_GarbageCollectBlock(dev,block);
2394 // New garbage collector
2395 // If we're very low on erased blocks then we do aggressive garbage collection
2396 // otherwise we do "passive" garbage collection.
2397 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2398 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2400 // The idea is to help clear out space in a more spread-out manner.
2401 // Dunno if it really does anything useful.
2403 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2408 //yaffs_DoUnlinkedFileDeletion(dev);
2410 if(dev->nErasedBlocks <= (dev->nReservedBlocks + 1))
2415 block = yaffs_FindDirtiestBlock(dev,aggressive);
2419 dev->garbageCollections++;
2422 dev->passiveGarbageCollections++;
2425 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2427 return yaffs_GarbageCollectBlock(dev,block);
2430 return aggressive ? YAFFS_FAIL : YAFFS_OK;
2434 //////////////////////////// TAGS ///////////////////////////////////////
2436 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2438 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2440 yaffs_CalcTagsECC(tagsPtr);
2442 sparePtr->tagByte0 = tu->asBytes[0];
2443 sparePtr->tagByte1 = tu->asBytes[1];
2444 sparePtr->tagByte2 = tu->asBytes[2];
2445 sparePtr->tagByte3 = tu->asBytes[3];
2446 sparePtr->tagByte4 = tu->asBytes[4];
2447 sparePtr->tagByte5 = tu->asBytes[5];
2448 sparePtr->tagByte6 = tu->asBytes[6];
2449 sparePtr->tagByte7 = tu->asBytes[7];
2452 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2454 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2457 tu->asBytes[0]= sparePtr->tagByte0;
2458 tu->asBytes[1]= sparePtr->tagByte1;
2459 tu->asBytes[2]= sparePtr->tagByte2;
2460 tu->asBytes[3]= sparePtr->tagByte3;
2461 tu->asBytes[4]= sparePtr->tagByte4;
2462 tu->asBytes[5]= sparePtr->tagByte5;
2463 tu->asBytes[6]= sparePtr->tagByte6;
2464 tu->asBytes[7]= sparePtr->tagByte7;
2466 result = yaffs_CheckECCOnTags(tagsPtr);
2469 dev->tagsEccFixed++;
2473 dev->tagsEccUnfixed++;
2477 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2479 memset(spare,0xFF,sizeof(yaffs_Spare));
2482 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2487 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2489 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2490 yaffs_GetTagsFromSpare(dev,&spare,tags);
2503 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2505 // NB There must be tags, data is optional
2506 // If there is data, then an ECC is calculated on it.
2515 yaffs_SpareInitialise(&spare);
2517 if(!dev->useNANDECC && buffer)
2519 yaffs_CalcECC(buffer,&spare);
2522 yaffs_LoadTagsIntoSpare(&spare,tags);
2524 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2530 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2532 // NB There must be tags, data is optional
2533 // If there is data, then an ECC is calculated on it.
2542 yaffs_SpareInitialise(&spare);
2544 if(!dev->useNANDECC && buffer)
2546 yaffs_CalcECC(buffer,&spare);
2549 yaffs_LoadTagsIntoSpare(&spare,tags);
2551 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2555 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2557 return ( tags->chunkId == chunkInObject &&
2558 tags->objectId == objectId &&
2559 !chunkDeleted) ? 1 : 0;
2565 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2567 //Get the Tnode, then get the level 0 offset chunk offset
2570 yaffs_Tags localTags;
2575 yaffs_Device *dev = in->myDev;
2580 // Passed a NULL, so use our own tags space
2584 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2588 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2590 // Now we need to do the shifting etc and search for it
2591 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2593 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2594 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2605 return found ? theChunk : -1;
2608 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2610 //Get the Tnode, then get the level 0 offset chunk offset
2613 yaffs_Tags localTags;
2616 yaffs_Device *dev = in->myDev;
2621 // Passed a NULL, so use our own tags space
2625 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2630 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2632 // Now we need to do the shifting etc and search for it
2633 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2635 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2636 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2647 // Delete the entry in the filestructure
2650 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2655 //T(("No level 0 found for %d\n", chunkInInode));
2660 //T(("Could not find %d to delete\n",chunkInInode));
2662 return found ? theChunk : -1;
2666 #ifdef YAFFS_PARANOID
2668 static int yaffs_CheckFileSanity(yaffs_Object *in)
2676 yaffs_Tags localTags;
2677 yaffs_Tags *tags = &localTags;
2682 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2684 //T(("Object not a file\n"));
2688 objId = in->objectId;
2689 fSize = in->variant.fileVariant.fileSize;
2690 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
2692 for(chunk = 1; chunk <= nChunks; chunk++)
2694 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2699 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2702 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2703 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2710 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2711 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2720 //T(("No level 0 found for %d\n", chunk));
2724 return failed ? YAFFS_FAIL : YAFFS_OK;
2729 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2732 yaffs_Device *dev = in->myDev;
2734 yaffs_Tags existingTags;
2736 unsigned existingSerial, newSerial;
2738 int newChunkDeleted;
2741 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2747 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2751 // If we're scanning then we need to test for duplicates
2752 // NB This does not need to be efficient since it should only ever
2753 // happen when the power fails during a write, then only one
2754 // chunk should ever be affected.
2757 if(existingChunk != 0)
2759 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2760 // thus we have to do a FindChunkInFile to get the real chunk id.
2762 // We have a duplicate now we need to decide which one to use
2763 // To do this we get both sets of tags and compare serial numbers.
2764 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2768 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2770 if(existingChunk <=0)
2772 //Hoosterman - how did this happen?
2774 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
2779 // NB The deleted flags should be false, otherwise the chunks will
2780 // not be loaded during a scan
2782 newSerial = newTags.serialNumber;
2783 existingSerial = existingTags.serialNumber;
2785 if( existingChunk <= 0 ||
2786 ((existingSerial+1) & 3) == newSerial)
2789 // Delete the old one and drop through to update the tnode
2790 yaffs_DeleteChunk(dev,existingChunk,1);
2795 // Delete the new one and return early so that the tnode isn't changed
2796 yaffs_DeleteChunk(dev,chunkInNAND,1);
2803 if(existingChunk == 0)
2808 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2815 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2817 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2819 if(chunkInNAND >= 0)
2821 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2831 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND)
2836 yaffs_BlockInfo *bi;
2838 if(chunkId <= 0) return;
2841 block = chunkId / dev->nChunksPerBlock;
2842 page = chunkId % dev->nChunksPerBlock;
2846 yaffs_SpareInitialise(&spare);
2848 spare.pageStatus = 0; // To mark it as deleted.
2851 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2852 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2856 dev->nUnmarkedDeletions++;
2859 bi = yaffs_GetBlockInfo(dev,block);
2862 // Pull out of the management area.
2863 // If the whole block became dirty, this will kick off an erasure.
2864 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2865 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2869 yaffs_ClearChunkBit(dev,block,page);
2872 if(bi->pagesInUse == 0 &&
2873 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2875 yaffs_BlockBecameDirty(dev,block);
2881 // T(("Bad news deleting chunk %d\n",chunkId));
2889 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2891 // Find old chunk Need to do this to get serial number
2892 // Write new one and patch into tree.
2893 // Invalidate old tags.
2896 yaffs_Tags prevTags;
2901 yaffs_Device *dev = in->myDev;
2903 yaffs_CheckGarbageCollection(dev);
2905 // Get the previous chunk at this location in the file if it exists
2906 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2909 newTags.chunkId = chunkInInode;
2910 newTags.objectId = in->objectId;
2911 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2912 newTags.byteCount = nBytes;
2913 newTags.unusedStuff = 0xFFFFFFFF;
2915 yaffs_CalcTagsECC(&newTags);
2917 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2920 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2923 if(prevChunkId >= 0)
2925 yaffs_DeleteChunk(dev,prevChunkId,1);
2929 yaffs_CheckFileSanity(in);
2940 // UpdateObjectHeader updates the header on NAND for an object.
2941 // If name is not NULL, then that new name is used.
2943 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2946 yaffs_Device *dev = in->myDev;
2952 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2953 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2955 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2956 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2959 if(!in->fake || force)
2962 yaffs_CheckGarbageCollection(dev);
2964 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2966 prevChunkId = in->chunkId;
2968 if(prevChunkId >= 0)
2970 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2974 oh->type = in->variantType;
2976 oh->st_mode = in->st_mode;
2978 #ifdef CONFIG_YAFFS_WINCE
2979 oh->win_atime[0] = in->win_atime[0];
2980 oh->win_ctime[0] = in->win_ctime[0];
2981 oh->win_mtime[0] = in->win_mtime[0];
2982 oh->win_atime[1] = in->win_atime[1];
2983 oh->win_ctime[1] = in->win_ctime[1];
2984 oh->win_mtime[1] = in->win_mtime[1];
2986 oh->st_uid = in->st_uid;
2987 oh->st_gid = in->st_gid;
2988 oh->st_atime = in->st_atime;
2989 oh->st_mtime = in->st_mtime;
2990 oh->st_ctime = in->st_ctime;
2991 oh->st_rdev = in->st_rdev;
2995 oh->parentObjectId = in->parent->objectId;
2999 oh->parentObjectId = 0;
3002 //oh->sum = in->sum;
3005 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3006 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3008 else if(prevChunkId)
3010 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
3014 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3017 switch(in->variantType)
3019 case YAFFS_OBJECT_TYPE_UNKNOWN:
3020 // Should not happen
3022 case YAFFS_OBJECT_TYPE_FILE:
3023 oh->fileSize = in->variant.fileVariant.fileSize;
3025 case YAFFS_OBJECT_TYPE_HARDLINK:
3026 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3028 case YAFFS_OBJECT_TYPE_SPECIAL:
3031 case YAFFS_OBJECT_TYPE_DIRECTORY:
3034 case YAFFS_OBJECT_TYPE_SYMLINK:
3035 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3036 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3042 newTags.chunkId = 0;
3043 newTags.objectId = in->objectId;
3044 newTags.serialNumber = in->serial;
3045 newTags.byteCount = 0xFFFFFFFF;
3046 newTags.unusedStuff = 0xFFFFFFFF;
3048 yaffs_CalcTagsECC(&newTags);
3051 // Create new chunk in NAND
3052 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3057 in->chunkId = newChunkId;
3059 if(prevChunkId >= 0)
3061 yaffs_DeleteChunk(dev,prevChunkId,1);
3074 /////////////////////// Short Operations Cache ////////////////////////////////
3075 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3076 // reads might be short sequential reads, and a lot of writes may be short
3077 // sequential writes. eg. scanning/writing a jpeg file.
3078 // In these cases, a short read/write cache can provide a huge perfomance benefit
3079 // with dumb-as-a-rock code.
3080 // There are a limited number (~10) of cache chunks per device so that we don't
3081 // need a very intelligent search.
3087 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3089 yaffs_Device *dev = obj->myDev;
3092 yaffs_ChunkCache *cache;
3095 int nCaches = obj->myDev->nShortOpCaches;
3102 // Find the dirty cache for this object with the lowest chunk id.
3103 for(i = 0; i < nCaches; i++)
3105 if(dev->srCache[i].object == obj &&
3106 dev->srCache[i].dirty)
3108 if(!cache || dev->srCache[i].chunkId < lowest)
3110 cache = &dev->srCache[i];
3111 lowest = cache->chunkId;
3121 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3123 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3125 nBytes= YAFFS_BYTES_PER_CHUNK;
3128 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3134 cache->object = NULL;
3137 } while(cache && chunkWritten > 0);
3141 //Hoosterman, disk full while writing cache out.
3142 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3150 // Grab us a chunk for use.
3151 // First look for an empty one.
3152 // Then look for the least recently used non-dirty one.
3153 // Then look for the least recently used dirty one...., flush and look again.
3154 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3160 if(dev->nShortOpCaches > 0)
3162 for(i = 0; i < dev->nShortOpCaches; i++)
3164 if(!dev->srCache[i].object)
3166 //T(("Grabbing empty %d\n",i));
3168 //printf("Grabbing empty %d\n",i);
3170 return &dev->srCache[i];
3177 usage = 0; // just to stop the compiler grizzling
3179 for(i = 0; i < dev->nShortOpCaches; i++)
3181 if(!dev->srCache[i].dirty &&
3182 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3185 usage = dev->srCache[i].lastUse;
3190 //T(("Grabbing non-empty %d\n",theOne));
3192 //if(theOne >= 0) printf("Grabbed non-empty cache %d\n",theOne);
3194 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3204 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3206 yaffs_ChunkCache *cache;
3207 yaffs_Object *theObj;
3212 if(dev->nShortOpCaches > 0)
3214 // Try find a non-dirty one...
3216 cache = yaffs_GrabChunkCacheWorker(dev);
3220 // They were all dirty, find the last recently used object and flush
3221 // its cache, then find again.
3222 // NB what's here is not very accurate, we actually flush the object
3223 // the last recently used page.
3225 theObj = dev->srCache[0].object;
3226 usage = dev->srCache[0].lastUse;
3227 cache = &dev->srCache[0];
3230 for(i = 1; i < dev->nShortOpCaches; i++)
3232 if( dev->srCache[i].object &&
3233 dev->srCache[i].lastUse < usage)
3235 usage = dev->srCache[i].lastUse;
3236 theObj = dev->srCache[i].object;
3237 cache = &dev->srCache[i];
3242 if(!cache || cache->dirty)
3246 yaffs_FlushFilesChunkCache(theObj);
3249 cache = yaffs_GrabChunkCacheWorker(dev);
3253 //printf(" pushout %d\n",pushout);
3266 // Find a cached chunk
3267 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3269 yaffs_Device *dev = obj->myDev;
3271 if(dev->nShortOpCaches > 0)
3273 for(i = 0; i < dev->nShortOpCaches; i++)
3275 if(dev->srCache[i].object == obj &&
3276 dev->srCache[i].chunkId == chunkId)
3280 return &dev->srCache[i];
3287 // Mark the chunk for the least recently used algorithym
3288 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3291 if(dev->nShortOpCaches > 0)
3293 if( dev->srLastUse < 0 ||
3294 dev->srLastUse > 100000000)
3296 // Reset the cache usages
3298 for(i = 1; i < dev->nShortOpCaches; i++)
3300 dev->srCache[i].lastUse = 0;
3307 cache->lastUse = dev->srLastUse;
3316 // Invalidate a single cache page.
3317 // Do this when a whole page gets written,
3318 // ie the short cache for this page is no longer valid.
3319 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3321 if(object->myDev->nShortOpCaches > 0)
3323 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3327 cache->object = NULL;
3333 // Invalidate all the cache pages associated with this object
3334 // Do this whenever ther file is deleted or resized.
3335 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3338 yaffs_Device *dev = in->myDev;
3340 if(dev->nShortOpCaches > 0)
3342 // Now invalidate it.
3343 for(i = 0; i < dev->nShortOpCaches; i++)
3345 if(dev->srCache[i].object == in)
3347 dev->srCache[i].object = NULL;
3357 ///////////////////////// File read/write ///////////////////////////////
3358 // Read and write have very similar structures.
3359 // In general the read/write has three parts to it
3360 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3361 // * Some complete chunks
3362 // * An incomplete chunk to end off with
3364 // Curve-balls: the first chunk might also be the last chunk.
3366 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3375 yaffs_ChunkCache *cache;
3383 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
3384 start = offset % YAFFS_BYTES_PER_CHUNK;
3386 // OK now check for the curveball where the start and end are in
3388 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3394 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3397 cache = yaffs_FindChunkCache(in,chunk);
3399 // If the chunk is already in the cache or it is less than a whole chunk
3400 // then use the cache (if there is caching)
3401 // else bypass the cache.
3402 if( cache || nToCopy != YAFFS_BYTES_PER_CHUNK)
3404 if(dev->nShortOpCaches > 0)
3407 // If we can't find the data in the cache, then load it up.
3411 cache = yaffs_GrabChunkCache(in->myDev);
3413 cache->chunkId = chunk;
3415 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3419 yaffs_UseChunkCache(dev,cache,0);
3421 memcpy(buffer,&cache->data[start],nToCopy);
3425 // Read into the local buffer then copy...
3426 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3427 memcpy(buffer,&dev->localBuffer[start],nToCopy);
3433 #ifdef CONFIG_YAFFS_WINCE
3435 // Under WinCE can't do direct transfer. Need to use a local buffer.
3436 // This is because we otherwise screw up WinCE's memory mapper
3437 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3438 memcpy(buffer,dev->localBuffer,YAFFS_BYTES_PER_CHUNK);
3440 // A full chunk. Read directly into the supplied buffer.
3441 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3457 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3466 int startOfWrite = offset;
3467 int chunkWritten = 0;
3475 while(n > 0 && chunkWritten >= 0)
3477 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
3478 start = offset % YAFFS_BYTES_PER_CHUNK;
3481 // OK now check for the curveball where the start and end are in
3484 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3488 // Now folks, to calculate how many bytes to write back....
3489 // If we're overwriting and not writing to then end of file then
3490 // we need to write back as much as was there before.
3492 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
3494 if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
3496 nBytesRead = YAFFS_BYTES_PER_CHUNK;
3499 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3504 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3505 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3508 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3510 // An incomplete start or end chunk (or maybe both start and end chunk)
3511 if(dev->nShortOpCaches > 0)
3513 yaffs_ChunkCache *cache;
3514 // If we can't find the data in the cache, then load it up.
3515 cache = yaffs_FindChunkCache(in,chunk);
3516 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3518 cache = yaffs_GrabChunkCache(in->myDev);
3520 cache->chunkId = chunk;
3522 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3527 yaffs_UseChunkCache(dev,cache,1);
3528 memcpy(&cache->data[start],buffer,nToCopy);
3529 cache->nBytes = nToWriteBack;
3533 chunkWritten = -1; // fail the write
3538 // An incomplete start or end chunk (or maybe both start and end chunk)
3539 // Read into the local buffer then copy, then copy over and write back.
3541 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3543 memcpy(&dev->localBuffer[start],buffer,nToCopy);
3545 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,nToWriteBack,0);
3547 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3554 #ifdef CONFIG_YAFFS_WINCE
3555 // Under WinCE can't do direct transfer. Need to use a local buffer.
3556 // This is because we otherwise screw up WinCE's memory mapper
3557 memcpy(dev->localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3558 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3560 // A full chunk. Write directly from the supplied buffer.
3561 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3563 // Since we've overwritten the cached data, we better invalidate it.
3564 yaffs_InvalidateChunkCache(in,chunk);
3565 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3568 if(chunkWritten >= 0)
3578 // Update file object
3580 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3582 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3591 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3595 int oldFileSize = in->variant.fileVariant.fileSize;
3596 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3598 yaffs_Device *dev = in->myDev;
3601 yaffs_FlushFilesChunkCache(in);
3602 yaffs_InvalidateWholeChunkCache(in);
3604 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3606 return yaffs_GetFileSize(in);
3609 if(newSize < oldFileSize)
3612 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3614 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3615 YAFFS_BYTES_PER_CHUNK;
3617 // Delete backwards so that we don't end up with holes if
3618 // power is lost part-way through the operation.
3619 for(i = lastDel; i >= startDel; i--)
3621 // NB this could be optimised somewhat,
3622 // eg. could retrieve the tags and write them without
3623 // using yaffs_DeleteChunk
3625 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3626 if(chunkId < (dev->startBlock * 32) || chunkId >= ((dev->endBlock+1) * 32))
3628 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3633 yaffs_DeleteChunk(dev,chunkId,1);
3638 if(sizeOfPartialChunk != 0)
3640 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3642 // Got to read and rewrite the last chunk with its new size.
3643 yaffs_ReadChunkDataFromObject(in,lastChunk,dev->localBuffer);
3645 yaffs_WriteChunkDataToObject(in,lastChunk,dev->localBuffer,sizeOfPartialChunk,1);
3649 in->variant.fileVariant.fileSize = newSize;
3651 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3663 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3665 obj = yaffs_GetEquivalentObject(obj);
3667 switch(obj->variantType)
3669 case YAFFS_OBJECT_TYPE_FILE:
3670 return obj->variant.fileVariant.fileSize;
3671 case YAFFS_OBJECT_TYPE_SYMLINK:
3672 return strlen(obj->variant.symLinkVariant.alias);
3680 // yaffs_FlushFile() updates the file's
3683 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
3688 //T(("flushing object header\n"));
3690 yaffs_FlushFilesChunkCache(in);
3693 #ifdef CONFIG_YAFFS_WINCE
3694 yfsd_WinFileTimeNow(in->win_mtime);
3696 in->st_mtime = CURRENT_TIME;
3700 retVal = (yaffs_UpdateObjectHeader(in,NULL,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
3712 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3715 // First off, invalidate the file's data in the cache, without flushing.
3716 yaffs_InvalidateWholeChunkCache(in);
3718 yaffs_RemoveObjectFromDirectory(in);
3719 yaffs_DeleteChunk(in->myDev,in->chunkId,1);
3723 in->myInode->u.generic_ip = NULL;
3727 yaffs_FreeObject(in);
3732 // yaffs_DeleteFile deletes the whole file data
3733 // and the inode associated with the file.
3734 // It does not delete the links associated with the file.
3735 static int yaffs_UnlinkFile(yaffs_Object *in)
3738 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3740 // Delete the file data & tnodes
3742 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3745 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3747 return yaffs_DoGenericObjectDeletion(in);
3750 int immediateDeletion=0;
3751 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3752 if(1 || // Ignore the result of the change name. This will only fail
3753 // if the disk was completely full (an error condition)
3754 // We ignore the error so we can delete files to recover the disk
3758 //in->myDev->nUnlinkedFiles++;
3759 //in->renameAllowed = 0;
3763 immediateDeletion = 1;
3769 immediateDeletion = 1;
3774 if(immediateDeletion)
3776 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3778 in->myDev->nDeletedFiles++;
3779 yaffs_SoftDeleteFile(in);
3789 int yaffs_DeleteFile(yaffs_Object *in)
3791 int retVal = YAFFS_OK;
3793 if(in->nDataChunks > 0)
3795 // Use soft deletion
3798 retVal = yaffs_UnlinkFile(in);
3800 if(retVal == YAFFS_OK &&
3805 in->myDev->nDeletedFiles++;
3806 yaffs_SoftDeleteFile(in);
3808 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3812 // The file has no data chunks so we toss it immediately
3813 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3814 in->variant.fileVariant.top = NULL;
3815 yaffs_DoGenericObjectDeletion(in);
3821 static int yaffs_DeleteDirectory(yaffs_Object *in)
3823 //First check that the directory is empty.
3824 if(list_empty(&in->variant.directoryVariant.children))
3826 return yaffs_DoGenericObjectDeletion(in);
3833 static int yaffs_DeleteSymLink(yaffs_Object *in)
3835 YFREE(in->variant.symLinkVariant.alias);
3837 return yaffs_DoGenericObjectDeletion(in);
3840 static int yaffs_DeleteHardLink(yaffs_Object *in)
3842 // remove this hardlink from the list assocaited with the equivalent
3844 list_del(&in->hardLinks);
3845 return yaffs_DoGenericObjectDeletion(in);
3849 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj)
3851 switch(obj->variantType)
3853 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
3854 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
3855 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
3856 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
3857 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
3858 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
3863 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3867 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3869 return yaffs_DeleteHardLink(obj);
3871 else if(!list_empty(&obj->hardLinks))
3873 // Curve ball: We're unlinking an object that has a hardlink.
3875 // This problem arises because we are not strictly following
3876 // The Linux link/inode model.
3878 // We can't really delete the object.
3879 // Instead, we do the following:
3880 // - Select a hardlink.
3881 // - Unhook it from the hard links
3882 // - Unhook it from its parent directory (so that the rename can work)
3883 // - Rename the object to the hardlink's name.
3884 // - Delete the hardlink
3889 char name[YAFFS_MAX_NAME_LENGTH+1];
3891 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3893 list_del_init(&hl->hardLinks);
3894 list_del_init(&hl->siblings);
3896 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3898 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3900 if(retVal == YAFFS_OK)
3902 retVal = yaffs_DoGenericObjectDeletion(hl);
3909 switch(obj->variantType)
3911 case YAFFS_OBJECT_TYPE_FILE:
3912 return yaffs_UnlinkFile(obj);
3914 case YAFFS_OBJECT_TYPE_DIRECTORY:
3915 return yaffs_DeleteDirectory(obj);
3917 case YAFFS_OBJECT_TYPE_SYMLINK:
3918 return yaffs_DeleteSymLink(obj);
3920 case YAFFS_OBJECT_TYPE_HARDLINK:
3921 case YAFFS_OBJECT_TYPE_UNKNOWN:
3928 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3932 obj = yaffs_FindObjectByName(dir,name);
3934 if(obj && obj->unlinkAllowed)
3936 return yaffs_UnlinkWorker(obj);
3943 //////////////// Initialisation Scanning /////////////////
3947 // For now we use the SmartMedia check.
3948 // We look at the blockStatus byte in the first two chunks
3949 // These must be 0xFF to pass as OK.
3950 // todo: this function needs to be modifyable foir different NAND types
3951 // and different chunk sizes. Suggest make this into a per-device configurable
3953 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3957 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&spare,1);
3959 if(yaffs_CountBits(spare.blockStatus) < 7)
3964 if(spare.blockStatus != 0xFF)
3969 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
3972 if(yaffs_CountBits(spare.blockStatus) < 7)
3977 if(spare.blockStatus != 0xFF)
3987 static int yaffs_Scan(yaffs_Device *dev)
3995 yaffs_BlockState state;
3996 yaffs_Object *hardList = NULL;
3998 yaffs_BlockInfo *bi;
4001 yaffs_ObjectHeader *oh;
4003 yaffs_Object *parent;
4005 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
4008 // Scan all the blocks...
4010 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
4013 bi = yaffs_GetBlockInfo(dev,blk);
4014 yaffs_ClearChunkBits(dev,blk);
4016 bi->softDeletions = 0;
4017 state = YAFFS_BLOCK_STATE_SCANNING;
4020 if(yaffs_IsBlockBad(dev,blk))
4022 state = YAFFS_BLOCK_STATE_DEAD;
4023 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
4026 // Read each chunk in the block.
4028 for(c = 0; c < dev->nChunksPerBlock &&
4029 state == YAFFS_BLOCK_STATE_SCANNING; c++)
4031 // Read the spare area and decide what to do
4032 chunk = blk * dev->nChunksPerBlock + c;
4034 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
4037 // This block looks ok, now what's in this chunk?
4038 yaffs_GetTagsFromSpare(dev,&spare,&tags);
4040 if(yaffs_CountBits(spare.pageStatus) < 6)
4044 dev->nFreeChunks ++;
4045 //T((" %d %d deleted\n",blk,c));
4047 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
4049 // An unassigned chunk in the block
4050 // This means that either the block is empty or
4051 // this is the one being allocated from
4055 // the block is unused
4056 state = YAFFS_BLOCK_STATE_EMPTY;
4057 dev->nErasedBlocks++;
4061 // this is the block being allocated from
4062 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4063 state = YAFFS_BLOCK_STATE_ALLOCATING;
4064 dev->allocationBlock = blk;
4065 dev->allocationPage = c;
4068 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4070 else if(tags.chunkId > 0)
4074 yaffs_SetChunkBit(dev,blk,c);
4077 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4078 // PutChunkIntoFIle checks for a clash (two data chunks with
4079 // the same chunkId).
4080 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4081 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
4082 if(in->variant.fileVariant.scannedFileSize <endpos)
4084 in->variant.fileVariant.scannedFileSize = endpos;
4085 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4086 in->variant.fileVariant.fileSize =
4087 in->variant.fileVariant.scannedFileSize;
4091 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4095 // chunkId == 0, so it is an ObjectHeader.
4096 // Thus, we read in the object header and make the object
4097 yaffs_SetChunkBit(dev,blk,c);
4100 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
4102 oh = (yaffs_ObjectHeader *)chunkData;
4104 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4108 // We have already filled this one. We have a duplicate and need to resolve it.
4110 unsigned existingSerial = in->serial;
4111 unsigned newSerial = tags.serialNumber;
4113 if(((existingSerial+1) & 3) == newSerial)
4115 // Use new one - destroy the exisiting one
4116 yaffs_DeleteChunk(dev,in->chunkId,1);
4121 // Use existing - destroy this one.
4122 yaffs_DeleteChunk(dev,chunk,1);
4127 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4128 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4130 // We only load some info, don't fiddle with directory structure
4132 in->variantType = oh->type;
4134 in->st_mode = oh->st_mode;
4135 #ifdef CONFIG_YAFFS_WINCE
4136 in->win_atime[0] = oh->win_atime[0];
4137 in->win_ctime[0] = oh->win_ctime[0];
4138 in->win_mtime[0] = oh->win_mtime[0];
4139 in->win_atime[1] = oh->win_atime[1];
4140 in->win_ctime[1] = oh->win_ctime[1];
4141 in->win_mtime[1] = oh->win_mtime[1];
4143 in->st_uid = oh->st_uid;
4144 in->st_gid = oh->st_gid;
4145 in->st_atime = oh->st_atime;
4146 in->st_mtime = oh->st_mtime;
4147 in->st_ctime = oh->st_ctime;
4148 in->st_rdev = oh->st_rdev;
4150 in->chunkId = chunk;
4155 // we need to load this info
4158 in->variantType = oh->type;
4160 in->st_mode = oh->st_mode;
4161 #ifdef CONFIG_YAFFS_WINCE
4162 in->win_atime[0] = oh->win_atime[0];
4163 in->win_ctime[0] = oh->win_ctime[0];
4164 in->win_mtime[0] = oh->win_mtime[0];
4165 in->win_atime[1] = oh->win_atime[1];
4166 in->win_ctime[1] = oh->win_ctime[1];
4167 in->win_mtime[1] = oh->win_mtime[1];
4169 in->st_uid = oh->st_uid;
4170 in->st_gid = oh->st_gid;
4171 in->st_atime = oh->st_atime;
4172 in->st_mtime = oh->st_mtime;
4173 in->st_ctime = oh->st_ctime;
4174 in->st_rdev = oh->st_rdev;
4176 in->chunkId = chunk;
4178 yaffs_SetObjectName(in,oh->name);
4181 // directory stuff...
4182 // hook up to parent
4184 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4185 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4187 // Set up as a directory
4188 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4189 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4191 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4193 // Hoosterman, another problem....
4194 // We're trying to use a non-directory as a directory
4196 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan" TENDSTR)));
4200 yaffs_AddObjectToDirectory(parent,in);
4201 if(parent == dev->unlinkedDir)
4203 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4204 dev->nDeletedFiles++;
4207 // Note re hardlinks.
4208 // Since we might scan a hardlink before its equivalent object is scanned
4209 // we put them all in a list.
4210 // After scanning is complete, we should have all the objects, so we run through this
4211 // list and fix up all the chains.
4213 switch(in->variantType)
4215 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4217 case YAFFS_OBJECT_TYPE_FILE:
4218 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4219 in->variant.fileVariant.fileSize = oh->fileSize;
4222 case YAFFS_OBJECT_TYPE_HARDLINK:
4223 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4224 in->hardLinks.next = (struct list_head *)hardList;
4227 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4229 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4231 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4232 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4235 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4240 if(state == YAFFS_BLOCK_STATE_SCANNING)
4242 // If we got this far while scanning, then the block is fully allocated.
4243 state = YAFFS_BLOCK_STATE_FULL;
4246 bi->blockState = state;
4248 // Now let's see if it was dirty
4249 if( bi->pagesInUse == 0 &&
4250 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4252 yaffs_BlockBecameDirty(dev,blk);
4257 // Fix up the hard link chains.
4258 // We should now have scanned all the objects, now it's time to add these
4263 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4265 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4269 // Add the hardlink pointers
4270 hl->variant.hardLinkVariant.equivalentObject=in;
4271 list_add(&hl->hardLinks,&in->hardLinks);
4275 //Todo Need to report/handle this better.
4276 // Got a problem... hardlink to a non-existant object
4277 hl->variant.hardLinkVariant.equivalentObject=NULL;
4278 INIT_LIST_HEAD(&hl->hardLinks);
4285 struct list_head *i;
4286 struct list_head *n;
4289 // Soft delete all the unlinked files
4290 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
4294 l = list_entry(i, yaffs_Object,siblings);
4297 yaffs_SoftDeleteFile(l);
4308 ////////////////////////// Directory Functions /////////////////////////
4311 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
4314 if(obj->siblings.prev == NULL)
4317 INIT_LIST_HEAD(&obj->siblings);
4320 else if(!list_empty(&obj->siblings))
4322 // If it is holed up somewhere else, un hook it
4323 list_del_init(&obj->siblings);
4326 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
4327 obj->parent = directory;
4329 if(directory == obj->myDev->unlinkedDir)
4332 obj->myDev->nUnlinkedFiles++;
4333 obj->renameAllowed = 0;
4337 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4339 list_del_init(&obj->siblings);
4343 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
4347 struct list_head *i;
4348 char buffer[YAFFS_MAX_NAME_LENGTH+1];
4352 sum = yaffs_CalcNameSum(name);
4354 list_for_each(i,&directory->variant.directoryVariant.children)
4358 l = list_entry(i, yaffs_Object,siblings);
4360 // Special case for lost-n-found
4361 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4363 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
4368 else if(yaffs_SumCompare(l->sum, sum))
4371 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
4372 if(yaffs_strcmp(name,buffer) == 0)
4385 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
4387 struct list_head *i;
4391 list_for_each(i,&theDir->variant.directoryVariant.children)
4395 l = list_entry(i, yaffs_Object,siblings);
4408 // GetEquivalentObject dereferences any hard links to get to the
4411 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4413 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4415 // We want the object id of the equivalent object, not this one
4416 obj = obj->variant.hardLinkVariant.equivalentObject;
4422 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
4424 memset(name,0,buffSize);
4426 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4428 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
4430 else if(obj->chunkId <= 0)
4434 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
4435 strncpy(name,locName,buffSize - 1);
4438 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4439 else if(obj->shortName[0])
4441 strcpy(name,obj->shortName);
4446 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4447 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4449 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4451 if(obj->chunkId >= 0)
4453 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
4455 strncpy(name,oh->name,buffSize - 1);
4458 return strlen(name);
4461 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4464 // Dereference any hard linking
4465 obj = yaffs_GetEquivalentObject(obj);
4467 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4469 return obj->variant.fileVariant.fileSize;
4471 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4473 return strlen(obj->variant.symLinkVariant.alias);
4477 // Only a directory should drop through to here
4478 return YAFFS_BYTES_PER_CHUNK;
4482 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4485 struct list_head *i;
4489 count++; // the object itself
4491 list_for_each(i,&obj->hardLinks)
4493 count++; // add the hard links;
4500 int yaffs_GetObjectInode(yaffs_Object *obj)
4502 obj = yaffs_GetEquivalentObject(obj);
4504 return obj->objectId;
4507 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4509 obj = yaffs_GetEquivalentObject(obj);
4511 switch(obj->variantType)
4513 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
4514 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
4515 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
4516 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
4517 case YAFFS_OBJECT_TYPE_SPECIAL:
4518 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
4519 if(S_ISCHR(obj->st_mode)) return DT_CHR;
4520 if(S_ISBLK(obj->st_mode)) return DT_BLK;
4521 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
4522 default: return DT_REG; break;
4526 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4528 obj = yaffs_GetEquivalentObject(obj);
4529 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4531 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4535 return yaffs_CloneString("");
4539 #ifndef CONFIG_YAFFS_WINCE
4541 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4543 unsigned int valid = attr->ia_valid;
4545 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4546 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4547 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4549 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
4550 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
4551 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
4553 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4555 yaffs_UpdateObjectHeader(obj,NULL,1);
4560 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4562 unsigned int valid = 0;
4564 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
4565 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
4566 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
4568 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
4569 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
4570 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
4572 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4574 attr->ia_valid = valid;
4582 int yaffs_DumpObject(yaffs_Object *obj)
4584 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4586 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4588 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4590 // if(obj->chunkId >= 0)
4592 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4595 yaffs_GetObjectName(obj,name,256);
4597 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),
4598 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
4599 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4602 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4603 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
4604 obj->sum, obj->chunkId));
4605 switch(obj->variantType)
4607 case YAFFS_OBJECT_TYPE_FILE:
4608 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4610 case YAFFS_OBJECT_TYPE_DIRECTORY:
4611 YPRINTF((" DIRECTORY\n"));
4613 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4614 case YAFFS_OBJECT_TYPE_SYMLINK:
4615 case YAFFS_OBJECT_TYPE_UNKNOWN:
4624 ///////////////////////// Initialisation code ///////////////////////////
4628 int yaffs_GutsInitialise(yaffs_Device *dev)
4635 if( dev->nBytesPerChunk != YAFFS_BYTES_PER_CHUNK ||
4637 dev->nChunksPerBlock < 2 ||
4638 dev->nReservedBlocks < 2 ||
4639 dev->startBlock <= 0 ||
4640 dev->endBlock <= 0 ||
4641 dev->endBlock <= (dev->startBlock + dev->nReservedBlocks)
4644 //these parameters must be set before stating yaffs
4645 // Other parameters startBlock,
4651 if(!yaffs_CheckStructures())
4653 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
4659 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
4665 if(dev->startBlock <= 0 ||
4666 (dev->endBlock - dev->startBlock) < 10)
4668 T(YAFFS_TRACE_ALWAYS,(TSTR("startBlock %d or endBlock %d invalid\n" TENDSTR),
4669 dev->startBlock, dev->endBlock));
4673 nBlocks = dev->endBlock - dev->startBlock + 1;
4677 // OK now calculate a few things for the device
4678 // Calculate chunkGroupBits.
4679 // We need to find the next power of 2 > than endBlock
4681 x = dev->nChunksPerBlock * (dev->endBlock+1);
4683 for(bits = extraBits = 0; x > 1; bits++)
4685 if(x & 1) extraBits++;
4689 if(extraBits > 0) bits++;
4692 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4693 // chunk range we're using is greater than 16 we need
4694 // to figure out chunk shift and chunkGroupSize
4697 dev->chunkGroupBits = 0;
4701 dev->chunkGroupBits = bits - 16;
4703 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4707 // More device initialisation
4708 dev->garbageCollections = 0;
4709 dev->passiveGarbageCollections = 0;
4710 dev->currentDirtyChecker = 0;
4711 dev->bufferedBlock = -1;
4712 dev->doingBufferedBlockRewrite = 0;
4713 dev->nDeletedFiles = 0;
4714 dev->nBackgroundDeletions=0;
4715 dev->nUnlinkedFiles = 0;
4718 dev->tagsEccFixed=0;
4719 dev->tagsEccUnfixed=0;
4721 dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
4726 yaffs_InitialiseBlocks(dev,nBlocks);
4728 yaffs_InitialiseTnodes(dev);
4730 yaffs_InitialiseObjects(dev);
4732 if(dev->nShortOpCaches > 0)
4736 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
4738 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
4741 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
4743 for(i=0; i < dev->nShortOpCaches; i++)
4745 dev->srCache[i].object = NULL;
4746 dev->srCache[i].lastUse = 0;
4747 dev->srCache[i].dirty = 0;
4755 // Initialise the unlinked, root and lost and found directories
4756 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4758 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4760 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4761 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4762 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4765 // Now scan the flash.
4769 dev->nPageReads = 0;
4770 dev->nPageWrites = 0;
4771 dev->nBlockErasures = 0;
4773 dev->nRetriedWrites = 0;
4774 dev->nRetiredBlocks = 0;
4781 void yaffs_Deinitialise(yaffs_Device *dev)
4786 yaffs_DeinitialiseBlocks(dev);
4787 yaffs_DeinitialiseTnodes(dev);
4788 yaffs_DeinitialiseObjects(dev);
4789 YFREE(dev->localBuffer);
4796 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4798 int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
4800 struct list_head *i;
4804 // To the free chunks add the chunks that are in the deleted unlinked files.
4805 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4807 l = list_entry(i, yaffs_Object,siblings);
4811 nFree += l->nDataChunks;
4816 // printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
4818 if(nFree < 0) nFree = 0;
4826 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4831 int nDirtyCacheChunks=0;
4833 yaffs_BlockInfo *blk;
4835 struct list_head *i;
4838 for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
4840 blk = yaffs_GetBlockInfo(dev,b);
4842 switch(blk->blockState)
4844 case YAFFS_BLOCK_STATE_EMPTY:
4845 case YAFFS_BLOCK_STATE_ALLOCATING:
4846 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
4854 // To the free chunks add the chunks that are in the deleted unlinked files.
4855 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4859 l = list_entry(i, yaffs_Object,siblings);
4863 pending += l->nDataChunks;
4870 //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
4872 if(nFree != dev->nFreeChunks)
4874 // printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
4879 // Now count the number of dirty chunks in the cache and subtract those
4883 for(i = 0; i < dev->nShortOpCaches; i++)
4885 if(dev->srCache[i].dirty) nDirtyCacheChunks++;
4889 nFree -= nDirtyCacheChunks;
4891 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
4893 if(nFree < 0) nFree = 0;
4901 /////////////////// YAFFS test code //////////////////////////////////
4903 #define yaffs_CheckStruct(structure,syze, name) \
4904 if(sizeof(structure) != syze) \
4906 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
4907 return YAFFS_FAIL; \
4911 static int yaffs_CheckStructures(void)
4913 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4914 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4915 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4916 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
4917 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4919 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4926 void yaffs_GutsTest(yaffs_Device *dev)
4929 if(yaffs_CheckStructures() != YAFFS_OK)
4931 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
4935 yaffs_TnodeTest(dev);
4936 yaffs_ObjectTest(dev);