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.36 2004-10-10 17:54:59 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
785 yaffs_TnodeList *tmp;
787 while(dev->allocatedTnodeList)
789 tmp = dev->allocatedTnodeList->next;
791 YFREE(dev->allocatedTnodeList->tnodes);
792 YFREE(dev->allocatedTnodeList);
793 dev->allocatedTnodeList = tmp;
797 dev->freeTnodes = NULL;
798 dev->nFreeTnodes = 0;
801 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
803 dev->allocatedTnodeList = NULL;
804 dev->freeTnodes = NULL;
805 dev->nFreeTnodes = 0;
806 dev->nTnodesCreated = 0;
811 void yaffs_TnodeTest(yaffs_Device *dev)
816 yaffs_Tnode *tn[1000];
818 YINFO("Testing TNodes");
820 for(j = 0; j < 50; j++)
822 for(i = 0; i < 1000; i++)
824 tn[i] = yaffs_GetTnode(dev);
827 YALERT("Getting tnode failed");
830 for(i = 0; i < 1000; i+=3)
832 yaffs_FreeTnode(dev,tn[i]);
841 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
843 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
844 // The look up tree is represented by the top tnode and the number of topLevel
845 // in the tree. 0 means only the level 0 tnode is in the tree.
848 // FindLevel0Tnode finds the level 0 tnode, if one exists.
849 // Used when reading.....
850 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
853 yaffs_Tnode *tn = fStruct->top;
855 int requiredTallness;
856 int level = fStruct->topLevel;
858 // Check sane level and chunk Id
859 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
862 // sprintf(str,"Bad level %d",level);
867 if(chunkId > YAFFS_MAX_CHUNK_ID)
870 // sprintf(str,"Bad chunkId %d",chunkId);
875 // First check we're tall enough (ie enough topLevel)
877 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
878 requiredTallness = 0;
881 i >>= YAFFS_TNODES_INTERNAL_BITS;
886 if(requiredTallness > fStruct->topLevel)
888 // Not tall enough, so we can't find it, return NULL.
893 // Traverse down to level 0
894 while (level > 0 && tn)
896 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
897 YAFFS_TNODES_INTERNAL_MASK];
905 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
906 // This happens in two steps:
907 // 1. If the tree isn't tall enough, then make it taller.
908 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
910 // Used when modifying the tree.
912 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
917 int requiredTallness;
924 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
926 // Check sane level and page Id
927 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
930 // sprintf(str,"Bad level %d",fStruct->topLevel);
935 if(chunkId > YAFFS_MAX_CHUNK_ID)
938 // sprintf(str,"Bad chunkId %d",chunkId);
943 // First check we're tall enough (ie enough topLevel)
945 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
946 requiredTallness = 0;
949 x >>= YAFFS_TNODES_INTERNAL_BITS;
953 //T((TSTR(" required=%d"),requiredTallness));
956 if(requiredTallness > fStruct->topLevel)
958 // Not tall enough,gotta make the tree taller
959 for(i = fStruct->topLevel; i < requiredTallness; i++)
961 //T((TSTR(" add new top")));
963 tn = yaffs_GetTnode(dev);
967 tn->internal[0] = fStruct->top;
972 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
976 fStruct->topLevel = requiredTallness;
980 // Traverse down to level 0, adding anything we need
982 l = fStruct->topLevel;
986 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
987 YAFFS_TNODES_INTERNAL_MASK;
989 //T((TSTR(" [%d:%d]"),l,i));
993 //T((TSTR(" added")));
995 tn->internal[x] = yaffs_GetTnode(dev);
998 tn = tn->internal[x];
1008 // DeleteWorker scans backwards through the tnode tree and deletes all the
1009 // chunks and tnodes in the file
1010 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1012 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1028 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1032 if(limit && (*limit) < 0)
1038 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1039 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1043 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1044 tn->internal[i] = NULL;
1049 return (allDone) ? 1 : 0;
1055 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1061 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1063 theChunk = tn->level0[i] << in->myDev->chunkGroupBits;
1065 // Now we need to search for it
1066 for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
1068 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
1069 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
1083 yaffs_DeleteChunk(in->myDev,theChunk,1);
1100 return (i < 0) ? 1 : 0;
1111 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1112 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1114 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1116 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1121 yaffs_BlockInfo *theBlock;
1133 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1137 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1138 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1141 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1142 tn->internal[i] = NULL;
1146 //Hoosterman... how could this happen.
1150 return (allDone) ? 1 : 0;
1155 for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1159 // Note this does not find the real chunk, only the chunk group.
1160 // We make an assumption that a chunk group is niot larger than a block.
1161 theChunk = (tn->level0[i] << in->myDev->chunkGroupBits);
1162 T(YAFFS_TRACE_SCAN,(TSTR("soft delete tch %d cgb %d chunk %d" TENDSTR),
1163 tn->level0[i],in->myDev->chunkGroupBits,theChunk));
1165 theBlock = yaffs_GetBlockInfo(in->myDev, theChunk/in->myDev->nChunksPerBlock);
1168 theBlock->softDeletions++;
1186 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1189 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1192 if(obj->nDataChunks <= 0)
1194 // Empty file, just delete it immediately
1195 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1196 obj->variant.fileVariant.top = NULL;
1197 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1198 yaffs_DoGenericObjectDeletion(obj);
1202 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1203 obj->softDeleted = 1;
1212 // Pruning removes any part of the file structure tree that is beyond the
1213 // bounds of the file (ie that does not point to chunks).
1215 // A file should only get pruned when its size is reduced.
1217 // Before pruning, the chunks must be pulled from the tree and the
1218 // level 0 tnode entries must be zeroed out.
1219 // Could also use this for file deletion, but that's probably better handled
1220 // by a special case.
1222 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1224 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1233 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1235 if(tn->internal[i] && level > 0)
1237 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1246 if(hasData == 0 && del0)
1248 // Free and return NULL
1250 yaffs_FreeTnode(dev,tn);
1260 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1267 if(fStruct->topLevel > 0)
1269 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1271 // Now we have a tree with all the non-zero branches NULL but the height
1272 // is the same as it was.
1273 // Let's see if we can trim internal tnodes to shorten the tree.
1274 // We can do this if only the 0th element in the tnode is in use
1275 // (ie all the non-zero are NULL)
1277 while(fStruct->topLevel && !done)
1282 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1292 fStruct->top = tn->internal[0];
1293 fStruct->topLevel--;
1294 yaffs_FreeTnode(dev,tn);
1310 /////////////////////// End of File Structure functions. /////////////////
1312 // yaffs_CreateFreeObjects creates a bunch more objects and
1313 // adds them to the object free list.
1314 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1317 yaffs_Object *newObjects;
1318 yaffs_ObjectList *list;
1320 if(nObjects < 1) return YAFFS_OK;
1322 // make these things
1324 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1328 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1332 // Hook them into the free list
1333 for(i = 0; i < nObjects - 1; i++)
1335 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1338 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1339 dev->freeObjects = newObjects;
1340 dev->nFreeObjects+= nObjects;
1341 dev->nObjectsCreated+= nObjects;
1343 // Now add this bunch of Objects to a list for freeing up.
1345 list = YMALLOC(sizeof(yaffs_ObjectList));
1348 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1352 list->objects = newObjects;
1353 list->next = dev->allocatedObjectList;
1354 dev->allocatedObjectList = list;
1363 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1364 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1366 yaffs_Object *tn = NULL;
1368 // If there are none left make more
1369 if(!dev->freeObjects)
1371 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1374 if(dev->freeObjects)
1376 tn = dev->freeObjects;
1377 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1378 dev->nFreeObjects--;
1380 // Now sweeten it up...
1382 memset(tn,0,sizeof(yaffs_Object));
1385 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1386 INIT_LIST_HEAD(&(tn->hardLinks));
1387 INIT_LIST_HEAD(&(tn->hashLink));
1388 INIT_LIST_HEAD(&tn->siblings);
1390 // Add it to the lost and found directory.
1391 // NB Can't put root or lostNFound in lostNFound so
1392 // check if lostNFound exists first
1393 if(dev->lostNFoundDir)
1395 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1403 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1406 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1409 obj->fake = 1; // it is fake so it has no NAND presence...
1410 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1411 obj->unlinkAllowed= 0; // ... or unlink it
1414 obj->st_mode = mode;
1416 obj->chunkId = 0; // Not a valid chunk.
1424 static void yaffs_UnhashObject(yaffs_Object *tn)
1427 yaffs_Device *dev = tn->myDev;
1430 // If it is still linked into the bucket list, free from the list
1431 if(!list_empty(&tn->hashLink))
1433 list_del_init(&tn->hashLink);
1434 bucket = yaffs_HashFunction(tn->objectId);
1435 dev->objectBucket[bucket].count--;
1441 // FreeObject frees up a Object and puts it back on the free list
1442 static void yaffs_FreeObject(yaffs_Object *tn)
1445 yaffs_Device *dev = tn->myDev;
1447 yaffs_UnhashObject(tn);
1449 // Link into the free list.
1450 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1451 dev->freeObjects = tn;
1452 dev->nFreeObjects++;
1458 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1460 // Free the list of allocated Objects
1462 yaffs_ObjectList *tmp;
1464 while( dev->allocatedObjectList)
1466 tmp = dev->allocatedObjectList->next;
1467 YFREE(dev->allocatedObjectList->objects);
1468 YFREE(dev->allocatedObjectList);
1470 dev->allocatedObjectList = tmp;
1473 dev->freeObjects = NULL;
1474 dev->nFreeObjects = 0;
1477 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1481 dev->allocatedObjectList = NULL;
1482 dev->freeObjects = NULL;
1483 dev->nFreeObjects = 0;
1485 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1487 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1488 dev->objectBucket[i].count = 0;
1498 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1503 int lowest = 999999;
1506 // First let's see if we can find one that's empty.
1508 for(i = 0; i < 10 && lowest > 0; i++)
1511 x %= YAFFS_NOBJECT_BUCKETS;
1512 if(dev->objectBucket[x].count < lowest)
1514 lowest = dev->objectBucket[x].count;
1520 // If we didn't find an empty list, then try
1521 // looking a bit further for a short one
1523 for(i = 0; i < 10 && lowest > 3; i++)
1526 x %= YAFFS_NOBJECT_BUCKETS;
1527 if(dev->objectBucket[x].count < lowest)
1529 lowest = dev->objectBucket[x].count;
1538 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1540 int bucket = yaffs_FindNiceObjectBucket(dev);
1542 // Now find an object value that has not already been taken
1543 // by scanning the list.
1546 struct list_head *i;
1548 __u32 n = (__u32)bucket;
1550 //yaffs_CheckObjectHashSanity();
1555 n += YAFFS_NOBJECT_BUCKETS;
1556 if(1 ||dev->objectBucket[bucket].count > 0)
1558 list_for_each(i,&dev->objectBucket[bucket].list)
1560 // If there is already one in the list
1561 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1569 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1574 void yaffs_HashObject(yaffs_Object *in)
1576 int bucket = yaffs_HashFunction(in->objectId);
1577 yaffs_Device *dev = in->myDev;
1579 if(!list_empty(&in->hashLink))
1585 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1586 dev->objectBucket[bucket].count++;
1590 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1592 int bucket = yaffs_HashFunction(number);
1593 struct list_head *i;
1596 list_for_each(i,&dev->objectBucket[bucket].list)
1598 // Look if it is in the list
1601 in = list_entry(i, yaffs_Object,hashLink);
1602 if(in->objectId == number)
1614 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1617 yaffs_Object *theObject;
1621 number = yaffs_CreateNewObjectNumber(dev);
1624 theObject = yaffs_AllocateEmptyObject(dev);
1628 theObject->fake = 0;
1629 theObject->renameAllowed = 1;
1630 theObject->unlinkAllowed = 1;
1631 theObject->objectId = number;
1632 yaffs_HashObject(theObject);
1633 theObject->variantType = type;
1634 #ifdef CONFIG_YAFFS_WINCE
1635 yfsd_WinFileTimeNow(theObject->win_atime);
1636 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1637 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1641 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = Y_CURRENT_TIME;
1646 case YAFFS_OBJECT_TYPE_FILE:
1647 theObject->variant.fileVariant.fileSize = 0;
1648 theObject->variant.fileVariant.scannedFileSize = 0;
1649 theObject->variant.fileVariant.topLevel = 0;
1650 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1652 case YAFFS_OBJECT_TYPE_DIRECTORY:
1653 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1655 case YAFFS_OBJECT_TYPE_SYMLINK:
1656 // No action required
1658 case YAFFS_OBJECT_TYPE_HARDLINK:
1659 // No action required
1661 case YAFFS_OBJECT_TYPE_SPECIAL:
1662 // No action required
1664 case YAFFS_OBJECT_TYPE_UNKNOWN:
1665 // todo this should not happen
1673 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1675 yaffs_Object *theObject = NULL;
1679 theObject = yaffs_FindObjectByNumber(dev,number);
1684 theObject = yaffs_CreateNewObject(dev,number,type);
1691 char *yaffs_CloneString(const char *str)
1693 char *newStr = NULL;
1697 newStr = YMALLOC(strlen(str) + 1);
1706 // Mknod (create) a new object.
1707 // equivalentObject only has meaning for a hard link;
1708 // aliasString only has meaning for a sumlink.
1709 // rdev only has meaning for devices (a subset of special objects)
1710 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1711 yaffs_Object *parent,
1716 yaffs_Object *equivalentObject,
1717 const char *aliasString,
1722 yaffs_Device *dev = parent->myDev;
1724 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1725 if(yaffs_FindObjectByName(parent,name))
1730 in = yaffs_CreateNewObject(dev,-1,type);
1736 in->variantType = type;
1740 #ifdef CONFIG_YAFFS_WINCE
1741 yfsd_WinFileTimeNow(in->win_atime);
1742 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1743 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1747 in->st_atime = in->st_mtime = in->st_ctime = Y_CURRENT_TIME;
1752 in->nDataChunks = 0;
1754 yaffs_SetObjectName(in,name);
1757 yaffs_AddObjectToDirectory(parent,in);
1759 in->myDev = parent->myDev;
1764 case YAFFS_OBJECT_TYPE_SYMLINK:
1765 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1767 case YAFFS_OBJECT_TYPE_HARDLINK:
1768 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1769 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1770 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1772 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1773 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1774 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1775 case YAFFS_OBJECT_TYPE_UNKNOWN:
1779 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1780 yaffs_UpdateObjectHeader(in,name,0) < 0)
1782 // Could not create the object header, fail the creation
1783 yaffs_AbortHalfCreatedObject(in);
1792 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1794 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1797 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1799 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1802 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1804 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1807 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1809 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1812 // NB yaffs_Link returns the object id of the equivalent object.
1813 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1815 // Get the real object in case we were fed a hard link as an equivalent object
1816 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1818 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1820 return equivalentObject;
1830 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1836 newDir = obj->parent; // use the old directory
1839 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1841 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1842 // duplicate names are allowed.
1843 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1846 !yaffs_FindObjectByName(newDir,newName)) &&
1847 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1849 yaffs_SetObjectName(obj,newName);
1852 yaffs_AddObjectToDirectory(newDir,obj);
1854 if(unlinkOp) obj->unlinked = 1;
1857 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1868 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1873 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1874 // Special case for WinCE.
1875 // While look-up is case insensitive, the name isn't.
1876 // THerefore we might want to change x.txt to X.txt
1877 if(oldDir == newDir && _stricmp(oldName,newName) == 0)
1883 obj = yaffs_FindObjectByName(oldDir,oldName);
1884 if(obj && obj->renameAllowed)
1886 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1893 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1895 // Scan the buckets and check that the lists
1896 // have as many members as the count says there are
1899 struct list_head *j;
1902 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1906 list_for_each(j,&dev->objectBucket[bucket].list)
1911 if(countEm != dev->objectBucket[bucket].count)
1913 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1922 void yaffs_ObjectTest(yaffs_Device *dev)
1924 yaffs_Object *in[1000];
1926 yaffs_Object *inold[1000];
1930 memset(in,0,1000*sizeof(yaffs_Object *));
1931 memset(inold,0,1000*sizeof(yaffs_Object *));
1933 yaffs_CheckObjectHashSanity(dev);
1935 for(j = 0; j < 10; j++)
1939 for(i = 0; i < 1000; i++)
1941 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1944 YINFO("No more inodes");
1948 inNo[i] = in[i]->objectId;
1952 for(i = 0; i < 1000; i++)
1954 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1956 //T(("Differnce in look up test\n"));
1960 // T(("Look up ok\n"));
1964 yaffs_CheckObjectHashSanity(dev);
1966 for(i = 0; i < 1000; i+=3)
1968 yaffs_FreeObject(in[i]);
1973 yaffs_CheckObjectHashSanity(dev);
1980 /////////////////////////// Block Management and Page Allocation ///////////////////
1983 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1985 dev->allocationBlock = -1; // force it to get a new one
1986 //Todo we're assuming the malloc will pass.
1987 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1988 // Set up dynamic blockinfo stuff.
1989 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
1990 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1991 if(dev->blockInfo && dev->chunkBits)
1993 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1994 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
2002 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2004 YFREE(dev->blockInfo);
2005 dev->blockInfo = NULL;
2006 YFREE(dev->chunkBits);
2007 dev->chunkBits = NULL;
2010 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
2011 // for garbage collection.
2013 static int yaffs_FindDirtiestBlock(yaffs_Device *dev,int aggressive)
2016 int b = dev->currentDirtyChecker;
2022 yaffs_BlockInfo *bi;
2024 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2027 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2030 iterations = dev->endBlock - dev->startBlock + 1;
2034 iterations = dev->endBlock - dev->startBlock + 1;
2035 iterations = iterations / 16;
2036 if(iterations > 200)
2042 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2045 if ( b < dev->startBlock || b > dev->endBlock)
2047 b = dev->startBlock;
2050 if(b < dev->startBlock || b > dev->endBlock)
2052 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2056 bi = yaffs_GetBlockInfo(dev,b);
2058 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2059 (bi->pagesInUse - bi->softDeletions )< pagesInUse)
2062 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2066 dev->currentDirtyChecker = b;
2072 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2074 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2078 // If the block is still healthy erase it and mark as clean.
2079 // If the block has had a data failure, then retire it.
2080 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2082 if(!bi->needsRetiring)
2084 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2087 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2094 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2095 dev->nErasedBlocks++;
2097 bi->softDeletions = 0;
2098 yaffs_ClearChunkBits(dev,blockNo);
2100 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2104 yaffs_RetireBlock(dev,blockNo);
2105 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2110 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2114 yaffs_BlockInfo *bi;
2116 if(dev->nErasedBlocks < 1)
2118 // Hoosterman we've got a problem.
2119 // Can't get space to gc
2120 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during gc" TENDSTR)));
2125 // Find an empty block.
2127 for(i = dev->startBlock; i <= dev->endBlock; i++)
2129 dev->allocationBlockFinder++;
2130 if(dev->allocationBlockFinder <dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2132 dev->allocationBlockFinder = dev->startBlock;
2135 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2137 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2139 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2140 dev->nErasedBlocks--;
2141 return dev->allocationBlockFinder;
2150 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2153 yaffs_BlockInfo *bi;
2155 if(dev->allocationBlock < 0)
2157 // Get next block to allocate off
2158 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2159 dev->allocationPage = 0;
2162 if(!useReserve && dev->nErasedBlocks <= dev->nReservedBlocks)
2164 // Not enough space to allocate unless we're allowed to use the reserve.
2168 // Next page please....
2169 if(dev->allocationBlock >= 0)
2171 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2173 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2174 dev->allocationPage;
2176 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2178 dev->allocationPage++;
2182 // If the block is full set the state to full
2183 if(dev->allocationPage >= dev->nChunksPerBlock)
2185 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2186 dev->allocationBlock = -1;
2193 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2198 // To determine if we have enough space we just look at the
2199 // number of erased blocks.
2200 // The cache is allowed to use reserved blocks.
2202 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2204 return (dev->nErasedBlocks >= dev->nReservedBlocks);
2208 static int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2218 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
2220 // yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2222 yaffs_Object *object;
2224 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2226 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2227 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2228 chunkInBlock++, oldChunk++ )
2230 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2233 // This page is in use and might need to be copied off
2237 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2239 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
2241 yaffs_GetTagsFromSpare(dev,&spare,&tags);
2243 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2245 if(object && object->deleted && tags.chunkId != 0)
2247 // Data chunk in a deleted file, throw it away
2248 // It's a deleted data chunk,
2249 // No need to copy this, just forget about it and fix up the
2252 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2253 object->nDataChunks--;
2255 if(object->nDataChunks <= 0)
2257 // Time to delete the file too
2258 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2259 object->variant.fileVariant.top = NULL;
2260 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2261 yaffs_DoGenericObjectDeletion(object);
2265 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2267 // Deleted object header with no data chunks.
2268 // Can be discarded and the file deleted.
2269 object->chunkId = 0;
2270 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2271 object->variant.fileVariant.top = NULL;
2272 yaffs_DoGenericObjectDeletion(object);
2277 // It's either a data chunk in a live file or
2278 // an ObjectHeader, so we're interested in it.
2279 // NB Need to keep the ObjectHeaders of deleted files
2280 // until the whole file has been deleted off
2281 tags.serialNumber++;
2282 yaffs_LoadTagsIntoSpare(&spare,&tags);
2286 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
2293 // Ok, now fix up the Tnodes etc.
2295 if(tags.chunkId == 0)
2298 object->chunkId = newChunk;
2299 object->serial = tags.serialNumber;
2303 // It's a data chunk
2304 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2308 yaffs_DeleteChunk(dev,oldChunk,markNAND);
2317 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2319 // find a file to delete
2320 struct list_head *i;
2324 //Scan the unlinked files looking for one to delete
2325 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2329 l = list_entry(i, yaffs_Object,siblings);
2340 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2342 // This does background deletion on unlinked files.. only deleted ones.
2343 // If we don't have a file we're working on then find one
2344 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2346 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2349 // OK, we're working on a file...
2350 if(dev->unlinkedDeletion)
2352 yaffs_Object *obj = dev->unlinkedDeletion;
2354 int limit; // Number of chunks to delete in a file.
2355 // NB this can be exceeded, but not by much.
2359 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2361 if(obj->nDataChunks == 0)
2363 // Done all the deleting of data chunks.
2364 // Now dump the header and clean up
2365 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2366 obj->variant.fileVariant.top = NULL;
2367 yaffs_DoGenericObjectDeletion(obj);
2368 dev->nDeletedFiles--;
2369 dev->nUnlinkedFiles--;
2370 dev->nBackgroundDeletions++;
2371 dev->unlinkedDeletion = NULL;
2378 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
2379 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2384 //yaffs_DoUnlinkedFileDeletion(dev);
2386 if(dev->nErasedBlocks <= (dev->nReservedBlocks + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2393 block = yaffs_FindDirtiestBlock(dev,aggressive);
2397 dev->garbageCollections++;
2398 return yaffs_GarbageCollectBlock(dev,block);
2410 // New garbage collector
2411 // If we're very low on erased blocks then we do aggressive garbage collection
2412 // otherwise we do "passive" garbage collection.
2413 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2414 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2416 // The idea is to help clear out space in a more spread-out manner.
2417 // Dunno if it really does anything useful.
2419 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2424 //yaffs_DoUnlinkedFileDeletion(dev);
2426 if(dev->nErasedBlocks <= (dev->nReservedBlocks + 1))
2431 block = yaffs_FindDirtiestBlock(dev,aggressive);
2435 dev->garbageCollections++;
2438 dev->passiveGarbageCollections++;
2441 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2443 return yaffs_GarbageCollectBlock(dev,block);
2446 return aggressive ? YAFFS_FAIL : YAFFS_OK;
2450 //////////////////////////// TAGS ///////////////////////////////////////
2452 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2454 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2456 yaffs_CalcTagsECC(tagsPtr);
2458 sparePtr->tagByte0 = tu->asBytes[0];
2459 sparePtr->tagByte1 = tu->asBytes[1];
2460 sparePtr->tagByte2 = tu->asBytes[2];
2461 sparePtr->tagByte3 = tu->asBytes[3];
2462 sparePtr->tagByte4 = tu->asBytes[4];
2463 sparePtr->tagByte5 = tu->asBytes[5];
2464 sparePtr->tagByte6 = tu->asBytes[6];
2465 sparePtr->tagByte7 = tu->asBytes[7];
2468 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2470 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2473 tu->asBytes[0]= sparePtr->tagByte0;
2474 tu->asBytes[1]= sparePtr->tagByte1;
2475 tu->asBytes[2]= sparePtr->tagByte2;
2476 tu->asBytes[3]= sparePtr->tagByte3;
2477 tu->asBytes[4]= sparePtr->tagByte4;
2478 tu->asBytes[5]= sparePtr->tagByte5;
2479 tu->asBytes[6]= sparePtr->tagByte6;
2480 tu->asBytes[7]= sparePtr->tagByte7;
2482 result = yaffs_CheckECCOnTags(tagsPtr);
2485 dev->tagsEccFixed++;
2489 dev->tagsEccUnfixed++;
2493 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2495 memset(spare,0xFF,sizeof(yaffs_Spare));
2498 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2503 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2505 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2506 yaffs_GetTagsFromSpare(dev,&spare,tags);
2519 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2521 // NB There must be tags, data is optional
2522 // If there is data, then an ECC is calculated on it.
2531 yaffs_SpareInitialise(&spare);
2533 if(!dev->useNANDECC && buffer)
2535 yaffs_CalcECC(buffer,&spare);
2538 yaffs_LoadTagsIntoSpare(&spare,tags);
2540 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2546 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2548 // NB There must be tags, data is optional
2549 // If there is data, then an ECC is calculated on it.
2558 yaffs_SpareInitialise(&spare);
2560 if(!dev->useNANDECC && buffer)
2562 yaffs_CalcECC(buffer,&spare);
2565 yaffs_LoadTagsIntoSpare(&spare,tags);
2567 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2571 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2573 return ( tags->chunkId == chunkInObject &&
2574 tags->objectId == objectId &&
2575 !chunkDeleted) ? 1 : 0;
2581 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2583 //Get the Tnode, then get the level 0 offset chunk offset
2586 yaffs_Tags localTags;
2591 yaffs_Device *dev = in->myDev;
2596 // Passed a NULL, so use our own tags space
2600 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2604 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2606 // Now we need to do the shifting etc and search for it
2607 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2609 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2610 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2621 return found ? theChunk : -1;
2624 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2626 //Get the Tnode, then get the level 0 offset chunk offset
2629 yaffs_Tags localTags;
2632 yaffs_Device *dev = in->myDev;
2637 // Passed a NULL, so use our own tags space
2641 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2646 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2648 // Now we need to do the shifting etc and search for it
2649 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2651 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2652 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2663 // Delete the entry in the filestructure
2666 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2671 //T(("No level 0 found for %d\n", chunkInInode));
2676 //T(("Could not find %d to delete\n",chunkInInode));
2678 return found ? theChunk : -1;
2682 #ifdef YAFFS_PARANOID
2684 static int yaffs_CheckFileSanity(yaffs_Object *in)
2692 yaffs_Tags localTags;
2693 yaffs_Tags *tags = &localTags;
2698 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2700 //T(("Object not a file\n"));
2704 objId = in->objectId;
2705 fSize = in->variant.fileVariant.fileSize;
2706 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
2708 for(chunk = 1; chunk <= nChunks; chunk++)
2710 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2715 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2718 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2719 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2726 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2727 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2736 //T(("No level 0 found for %d\n", chunk));
2740 return failed ? YAFFS_FAIL : YAFFS_OK;
2745 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2748 yaffs_Device *dev = in->myDev;
2750 yaffs_Tags existingTags;
2752 unsigned existingSerial, newSerial;
2754 int newChunkDeleted;
2757 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2763 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2767 // If we're scanning then we need to test for duplicates
2768 // NB This does not need to be efficient since it should only ever
2769 // happen when the power fails during a write, then only one
2770 // chunk should ever be affected.
2773 if(existingChunk != 0)
2775 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2776 // thus we have to do a FindChunkInFile to get the real chunk id.
2778 // We have a duplicate now we need to decide which one to use
2779 // To do this we get both sets of tags and compare serial numbers.
2780 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2784 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2786 if(existingChunk <=0)
2788 //Hoosterman - how did this happen?
2790 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
2795 // NB The deleted flags should be false, otherwise the chunks will
2796 // not be loaded during a scan
2798 newSerial = newTags.serialNumber;
2799 existingSerial = existingTags.serialNumber;
2801 if( existingChunk <= 0 ||
2802 ((existingSerial+1) & 3) == newSerial)
2805 // Delete the old one and drop through to update the tnode
2806 yaffs_DeleteChunk(dev,existingChunk,1);
2811 // Delete the new one and return early so that the tnode isn't changed
2812 yaffs_DeleteChunk(dev,chunkInNAND,1);
2819 if(existingChunk == 0)
2824 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2831 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2833 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2835 if(chunkInNAND >= 0)
2837 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2841 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
2848 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND)
2853 yaffs_BlockInfo *bi;
2855 if(chunkId <= 0) return;
2858 block = chunkId / dev->nChunksPerBlock;
2859 page = chunkId % dev->nChunksPerBlock;
2863 yaffs_SpareInitialise(&spare);
2865 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
2867 //read data before write, to ensure correct ecc
2868 //if we're using MTD verification under Linux
2869 yaffs_ReadChunkFromNAND(dev,chunkId,NULL,&spare,0);
2872 spare.pageStatus = 0; // To mark it as deleted.
2875 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2876 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2880 dev->nUnmarkedDeletions++;
2883 bi = yaffs_GetBlockInfo(dev,block);
2886 // Pull out of the management area.
2887 // If the whole block became dirty, this will kick off an erasure.
2888 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2889 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2893 yaffs_ClearChunkBit(dev,block,page);
2896 if(bi->pagesInUse == 0 &&
2897 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2899 yaffs_BlockBecameDirty(dev,block);
2905 // T(("Bad news deleting chunk %d\n",chunkId));
2913 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2915 // Find old chunk Need to do this to get serial number
2916 // Write new one and patch into tree.
2917 // Invalidate old tags.
2920 yaffs_Tags prevTags;
2925 yaffs_Device *dev = in->myDev;
2927 yaffs_CheckGarbageCollection(dev);
2929 // Get the previous chunk at this location in the file if it exists
2930 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2933 newTags.chunkId = chunkInInode;
2934 newTags.objectId = in->objectId;
2935 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2936 newTags.byteCount = nBytes;
2937 newTags.unusedStuff = 0xFFFFFFFF;
2939 yaffs_CalcTagsECC(&newTags);
2941 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2944 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2947 if(prevChunkId >= 0)
2949 yaffs_DeleteChunk(dev,prevChunkId,1);
2953 yaffs_CheckFileSanity(in);
2964 // UpdateObjectHeader updates the header on NAND for an object.
2965 // If name is not NULL, then that new name is used.
2967 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2970 yaffs_Device *dev = in->myDev;
2976 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2977 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2979 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2980 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2983 if(!in->fake || force)
2986 yaffs_CheckGarbageCollection(dev);
2988 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2990 prevChunkId = in->chunkId;
2992 if(prevChunkId >= 0)
2994 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2998 oh->type = in->variantType;
3000 oh->st_mode = in->st_mode;
3002 #ifdef CONFIG_YAFFS_WINCE
3003 oh->win_atime[0] = in->win_atime[0];
3004 oh->win_ctime[0] = in->win_ctime[0];
3005 oh->win_mtime[0] = in->win_mtime[0];
3006 oh->win_atime[1] = in->win_atime[1];
3007 oh->win_ctime[1] = in->win_ctime[1];
3008 oh->win_mtime[1] = in->win_mtime[1];
3010 oh->st_uid = in->st_uid;
3011 oh->st_gid = in->st_gid;
3012 oh->st_atime = in->st_atime;
3013 oh->st_mtime = in->st_mtime;
3014 oh->st_ctime = in->st_ctime;
3015 oh->st_rdev = in->st_rdev;
3019 oh->parentObjectId = in->parent->objectId;
3023 oh->parentObjectId = 0;
3026 //oh->sum = in->sum;
3029 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3030 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3032 else if(prevChunkId)
3034 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
3038 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3041 switch(in->variantType)
3043 case YAFFS_OBJECT_TYPE_UNKNOWN:
3044 // Should not happen
3046 case YAFFS_OBJECT_TYPE_FILE:
3047 oh->fileSize = in->variant.fileVariant.fileSize;
3049 case YAFFS_OBJECT_TYPE_HARDLINK:
3050 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3052 case YAFFS_OBJECT_TYPE_SPECIAL:
3055 case YAFFS_OBJECT_TYPE_DIRECTORY:
3058 case YAFFS_OBJECT_TYPE_SYMLINK:
3059 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3060 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3066 newTags.chunkId = 0;
3067 newTags.objectId = in->objectId;
3068 newTags.serialNumber = in->serial;
3069 newTags.byteCount = 0xFFFFFFFF;
3070 newTags.unusedStuff = 0xFFFFFFFF;
3072 yaffs_CalcTagsECC(&newTags);
3075 // Create new chunk in NAND
3076 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3081 in->chunkId = newChunkId;
3083 if(prevChunkId >= 0)
3085 yaffs_DeleteChunk(dev,prevChunkId,1);
3098 /////////////////////// Short Operations Cache ////////////////////////////////
3099 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3100 // reads might be short sequential reads, and a lot of writes may be short
3101 // sequential writes. eg. scanning/writing a jpeg file.
3102 // In these cases, a short read/write cache can provide a huge perfomance benefit
3103 // with dumb-as-a-rock code.
3104 // There are a limited number (~10) of cache chunks per device so that we don't
3105 // need a very intelligent search.
3111 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3113 yaffs_Device *dev = obj->myDev;
3116 yaffs_ChunkCache *cache;
3119 int nCaches = obj->myDev->nShortOpCaches;
3126 // Find the dirty cache for this object with the lowest chunk id.
3127 for(i = 0; i < nCaches; i++)
3129 if(dev->srCache[i].object == obj &&
3130 dev->srCache[i].dirty)
3132 if(!cache || dev->srCache[i].chunkId < lowest)
3134 cache = &dev->srCache[i];
3135 lowest = cache->chunkId;
3145 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3147 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3149 nBytes= YAFFS_BYTES_PER_CHUNK;
3152 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3158 cache->object = NULL;
3161 } while(cache && chunkWritten > 0);
3165 //Hoosterman, disk full while writing cache out.
3166 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3174 // Grab us a chunk for use.
3175 // First look for an empty one.
3176 // Then look for the least recently used non-dirty one.
3177 // Then look for the least recently used dirty one...., flush and look again.
3178 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3184 if(dev->nShortOpCaches > 0)
3186 for(i = 0; i < dev->nShortOpCaches; i++)
3188 if(!dev->srCache[i].object)
3190 //T(("Grabbing empty %d\n",i));
3192 //printf("Grabbing empty %d\n",i);
3194 return &dev->srCache[i];
3201 usage = 0; // just to stop the compiler grizzling
3203 for(i = 0; i < dev->nShortOpCaches; i++)
3205 if(!dev->srCache[i].dirty &&
3206 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3209 usage = dev->srCache[i].lastUse;
3214 //T(("Grabbing non-empty %d\n",theOne));
3216 //if(theOne >= 0) printf("Grabbed non-empty cache %d\n",theOne);
3218 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3228 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3230 yaffs_ChunkCache *cache;
3231 yaffs_Object *theObj;
3236 if(dev->nShortOpCaches > 0)
3238 // Try find a non-dirty one...
3240 cache = yaffs_GrabChunkCacheWorker(dev);
3244 // They were all dirty, find the last recently used object and flush
3245 // its cache, then find again.
3246 // NB what's here is not very accurate, we actually flush the object
3247 // the last recently used page.
3249 theObj = dev->srCache[0].object;
3250 usage = dev->srCache[0].lastUse;
3251 cache = &dev->srCache[0];
3254 for(i = 1; i < dev->nShortOpCaches; i++)
3256 if( dev->srCache[i].object &&
3257 dev->srCache[i].lastUse < usage)
3259 usage = dev->srCache[i].lastUse;
3260 theObj = dev->srCache[i].object;
3261 cache = &dev->srCache[i];
3266 if(!cache || cache->dirty)
3270 yaffs_FlushFilesChunkCache(theObj);
3273 cache = yaffs_GrabChunkCacheWorker(dev);
3277 //printf(" pushout %d\n",pushout);
3290 // Find a cached chunk
3291 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3293 yaffs_Device *dev = obj->myDev;
3295 if(dev->nShortOpCaches > 0)
3297 for(i = 0; i < dev->nShortOpCaches; i++)
3299 if(dev->srCache[i].object == obj &&
3300 dev->srCache[i].chunkId == chunkId)
3304 return &dev->srCache[i];
3311 // Mark the chunk for the least recently used algorithym
3312 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3315 if(dev->nShortOpCaches > 0)
3317 if( dev->srLastUse < 0 ||
3318 dev->srLastUse > 100000000)
3320 // Reset the cache usages
3322 for(i = 1; i < dev->nShortOpCaches; i++)
3324 dev->srCache[i].lastUse = 0;
3331 cache->lastUse = dev->srLastUse;
3340 // Invalidate a single cache page.
3341 // Do this when a whole page gets written,
3342 // ie the short cache for this page is no longer valid.
3343 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3345 if(object->myDev->nShortOpCaches > 0)
3347 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3351 cache->object = NULL;
3357 // Invalidate all the cache pages associated with this object
3358 // Do this whenever ther file is deleted or resized.
3359 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3362 yaffs_Device *dev = in->myDev;
3364 if(dev->nShortOpCaches > 0)
3366 // Now invalidate it.
3367 for(i = 0; i < dev->nShortOpCaches; i++)
3369 if(dev->srCache[i].object == in)
3371 dev->srCache[i].object = NULL;
3381 ///////////////////////// File read/write ///////////////////////////////
3382 // Read and write have very similar structures.
3383 // In general the read/write has three parts to it
3384 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3385 // * Some complete chunks
3386 // * An incomplete chunk to end off with
3388 // Curve-balls: the first chunk might also be the last chunk.
3390 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3399 yaffs_ChunkCache *cache;
3407 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
3408 start = offset % YAFFS_BYTES_PER_CHUNK;
3410 // OK now check for the curveball where the start and end are in
3412 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3418 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3421 cache = yaffs_FindChunkCache(in,chunk);
3423 // If the chunk is already in the cache or it is less than a whole chunk
3424 // then use the cache (if there is caching)
3425 // else bypass the cache.
3426 if( cache || nToCopy != YAFFS_BYTES_PER_CHUNK)
3428 if(dev->nShortOpCaches > 0)
3431 // If we can't find the data in the cache, then load it up.
3435 cache = yaffs_GrabChunkCache(in->myDev);
3437 cache->chunkId = chunk;
3439 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3443 yaffs_UseChunkCache(dev,cache,0);
3445 memcpy(buffer,&cache->data[start],nToCopy);
3449 // Read into the local buffer then copy...
3450 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3451 memcpy(buffer,&dev->localBuffer[start],nToCopy);
3457 #ifdef CONFIG_YAFFS_WINCE
3459 // Under WinCE can't do direct transfer. Need to use a local buffer.
3460 // This is because we otherwise screw up WinCE's memory mapper
3461 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3462 memcpy(buffer,dev->localBuffer,YAFFS_BYTES_PER_CHUNK);
3464 // A full chunk. Read directly into the supplied buffer.
3465 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3481 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3490 int startOfWrite = offset;
3491 int chunkWritten = 0;
3499 while(n > 0 && chunkWritten >= 0)
3501 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
3502 start = offset % YAFFS_BYTES_PER_CHUNK;
3505 // OK now check for the curveball where the start and end are in
3508 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3512 // Now folks, to calculate how many bytes to write back....
3513 // If we're overwriting and not writing to then end of file then
3514 // we need to write back as much as was there before.
3516 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
3518 if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
3520 nBytesRead = YAFFS_BYTES_PER_CHUNK;
3523 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3528 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3529 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3532 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3534 // An incomplete start or end chunk (or maybe both start and end chunk)
3535 if(dev->nShortOpCaches > 0)
3537 yaffs_ChunkCache *cache;
3538 // If we can't find the data in the cache, then load it up.
3539 cache = yaffs_FindChunkCache(in,chunk);
3540 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3542 cache = yaffs_GrabChunkCache(in->myDev);
3544 cache->chunkId = chunk;
3546 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3551 yaffs_UseChunkCache(dev,cache,1);
3552 memcpy(&cache->data[start],buffer,nToCopy);
3553 cache->nBytes = nToWriteBack;
3557 chunkWritten = -1; // fail the write
3562 // An incomplete start or end chunk (or maybe both start and end chunk)
3563 // Read into the local buffer then copy, then copy over and write back.
3565 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3567 memcpy(&dev->localBuffer[start],buffer,nToCopy);
3569 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,nToWriteBack,0);
3571 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3578 #ifdef CONFIG_YAFFS_WINCE
3579 // Under WinCE can't do direct transfer. Need to use a local buffer.
3580 // This is because we otherwise screw up WinCE's memory mapper
3581 memcpy(dev->localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3582 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3584 // A full chunk. Write directly from the supplied buffer.
3585 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3587 // Since we've overwritten the cached data, we better invalidate it.
3588 yaffs_InvalidateChunkCache(in,chunk);
3589 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3592 if(chunkWritten >= 0)
3602 // Update file object
3604 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3606 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3615 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3619 int oldFileSize = in->variant.fileVariant.fileSize;
3620 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3622 yaffs_Device *dev = in->myDev;
3625 yaffs_FlushFilesChunkCache(in);
3626 yaffs_InvalidateWholeChunkCache(in);
3628 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3630 return yaffs_GetFileSize(in);
3633 if(newSize < oldFileSize)
3636 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3638 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3639 YAFFS_BYTES_PER_CHUNK;
3641 // Delete backwards so that we don't end up with holes if
3642 // power is lost part-way through the operation.
3643 for(i = lastDel; i >= startDel; i--)
3645 // NB this could be optimised somewhat,
3646 // eg. could retrieve the tags and write them without
3647 // using yaffs_DeleteChunk
3649 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3650 if(chunkId < (dev->startBlock * 32) || chunkId >= ((dev->endBlock+1) * 32))
3652 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3657 yaffs_DeleteChunk(dev,chunkId,1);
3662 if(sizeOfPartialChunk != 0)
3664 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3666 // Got to read and rewrite the last chunk with its new size.
3667 // NB Got to zero pad to nuke old data
3668 yaffs_ReadChunkDataFromObject(in,lastChunk,dev->localBuffer);
3669 memset(dev->localBuffer + sizeOfPartialChunk,0, YAFFS_BYTES_PER_CHUNK - sizeOfPartialChunk);
3671 yaffs_WriteChunkDataToObject(in,lastChunk,dev->localBuffer,sizeOfPartialChunk,1);
3675 in->variant.fileVariant.fileSize = newSize;
3677 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3689 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3691 obj = yaffs_GetEquivalentObject(obj);
3693 switch(obj->variantType)
3695 case YAFFS_OBJECT_TYPE_FILE:
3696 return obj->variant.fileVariant.fileSize;
3697 case YAFFS_OBJECT_TYPE_SYMLINK:
3698 return strlen(obj->variant.symLinkVariant.alias);
3706 // yaffs_FlushFile() updates the file's
3709 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
3714 //T(("flushing object header\n"));
3716 yaffs_FlushFilesChunkCache(in);
3719 #ifdef CONFIG_YAFFS_WINCE
3720 yfsd_WinFileTimeNow(in->win_mtime);
3722 in->st_mtime = Y_CURRENT_TIME;
3726 retVal = (yaffs_UpdateObjectHeader(in,NULL,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
3738 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3741 // First off, invalidate the file's data in the cache, without flushing.
3742 yaffs_InvalidateWholeChunkCache(in);
3744 yaffs_RemoveObjectFromDirectory(in);
3745 yaffs_DeleteChunk(in->myDev,in->chunkId,1);
3749 in->myInode->u.generic_ip = NULL;
3753 yaffs_FreeObject(in);
3758 // yaffs_DeleteFile deletes the whole file data
3759 // and the inode associated with the file.
3760 // It does not delete the links associated with the file.
3761 static int yaffs_UnlinkFile(yaffs_Object *in)
3764 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3766 // Delete the file data & tnodes
3768 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3771 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3773 return yaffs_DoGenericObjectDeletion(in);
3776 int immediateDeletion=0;
3777 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3778 if(1 || // Ignore the result of the change name. This will only fail
3779 // if the disk was completely full (an error condition)
3780 // We ignore the error so we can delete files to recover the disk
3784 //in->myDev->nUnlinkedFiles++;
3785 //in->renameAllowed = 0;
3789 immediateDeletion = 1;
3795 immediateDeletion = 1;
3800 if(immediateDeletion)
3802 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3804 in->myDev->nDeletedFiles++;
3805 yaffs_SoftDeleteFile(in);
3815 int yaffs_DeleteFile(yaffs_Object *in)
3817 int retVal = YAFFS_OK;
3819 if(in->nDataChunks > 0)
3821 // Use soft deletion
3824 retVal = yaffs_UnlinkFile(in);
3826 if(retVal == YAFFS_OK &&
3831 in->myDev->nDeletedFiles++;
3832 yaffs_SoftDeleteFile(in);
3834 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3838 // The file has no data chunks so we toss it immediately
3839 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3840 in->variant.fileVariant.top = NULL;
3841 yaffs_DoGenericObjectDeletion(in);
3847 static int yaffs_DeleteDirectory(yaffs_Object *in)
3849 //First check that the directory is empty.
3850 if(list_empty(&in->variant.directoryVariant.children))
3852 return yaffs_DoGenericObjectDeletion(in);
3859 static int yaffs_DeleteSymLink(yaffs_Object *in)
3861 YFREE(in->variant.symLinkVariant.alias);
3863 return yaffs_DoGenericObjectDeletion(in);
3866 static int yaffs_DeleteHardLink(yaffs_Object *in)
3868 // remove this hardlink from the list assocaited with the equivalent
3870 list_del(&in->hardLinks);
3871 return yaffs_DoGenericObjectDeletion(in);
3875 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj)
3877 switch(obj->variantType)
3879 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
3880 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
3881 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
3882 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
3883 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
3884 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
3889 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3893 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3895 return yaffs_DeleteHardLink(obj);
3897 else if(!list_empty(&obj->hardLinks))
3899 // Curve ball: We're unlinking an object that has a hardlink.
3901 // This problem arises because we are not strictly following
3902 // The Linux link/inode model.
3904 // We can't really delete the object.
3905 // Instead, we do the following:
3906 // - Select a hardlink.
3907 // - Unhook it from the hard links
3908 // - Unhook it from its parent directory (so that the rename can work)
3909 // - Rename the object to the hardlink's name.
3910 // - Delete the hardlink
3915 char name[YAFFS_MAX_NAME_LENGTH+1];
3917 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3919 list_del_init(&hl->hardLinks);
3920 list_del_init(&hl->siblings);
3922 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3924 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3926 if(retVal == YAFFS_OK)
3928 retVal = yaffs_DoGenericObjectDeletion(hl);
3935 switch(obj->variantType)
3937 case YAFFS_OBJECT_TYPE_FILE:
3938 return yaffs_UnlinkFile(obj);
3940 case YAFFS_OBJECT_TYPE_DIRECTORY:
3941 return yaffs_DeleteDirectory(obj);
3943 case YAFFS_OBJECT_TYPE_SYMLINK:
3944 return yaffs_DeleteSymLink(obj);
3946 case YAFFS_OBJECT_TYPE_HARDLINK:
3947 case YAFFS_OBJECT_TYPE_UNKNOWN:
3954 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3958 obj = yaffs_FindObjectByName(dir,name);
3960 if(obj && obj->unlinkAllowed)
3962 return yaffs_UnlinkWorker(obj);
3969 //////////////// Initialisation Scanning /////////////////
3973 // For now we use the SmartMedia check.
3974 // We look at the blockStatus byte in the first two chunks
3975 // These must be 0xFF to pass as OK.
3976 // todo: this function needs to be modifyable foir different NAND types
3977 // and different chunk sizes. Suggest make this into a per-device configurable
3979 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3983 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&spare,1);
3985 if(yaffs_CountBits(spare.blockStatus) < 7)
3990 if(spare.blockStatus != 0xFF)
3995 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
3998 if(yaffs_CountBits(spare.blockStatus) < 7)
4003 if(spare.blockStatus != 0xFF)
4013 static int yaffs_Scan(yaffs_Device *dev)
4021 yaffs_BlockState state;
4022 yaffs_Object *hardList = NULL;
4024 yaffs_BlockInfo *bi;
4027 yaffs_ObjectHeader *oh;
4029 yaffs_Object *parent;
4031 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
4034 // Scan all the blocks...
4036 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
4039 bi = yaffs_GetBlockInfo(dev,blk);
4040 yaffs_ClearChunkBits(dev,blk);
4042 bi->softDeletions = 0;
4043 state = YAFFS_BLOCK_STATE_SCANNING;
4046 if(yaffs_IsBlockBad(dev,blk))
4048 state = YAFFS_BLOCK_STATE_DEAD;
4049 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
4052 // Read each chunk in the block.
4054 for(c = 0; c < dev->nChunksPerBlock &&
4055 state == YAFFS_BLOCK_STATE_SCANNING; c++)
4057 // Read the spare area and decide what to do
4058 chunk = blk * dev->nChunksPerBlock + c;
4060 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
4063 // This block looks ok, now what's in this chunk?
4064 yaffs_GetTagsFromSpare(dev,&spare,&tags);
4066 if(yaffs_CountBits(spare.pageStatus) < 6)
4070 dev->nFreeChunks ++;
4071 //T((" %d %d deleted\n",blk,c));
4073 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
4075 // An unassigned chunk in the block
4076 // This means that either the block is empty or
4077 // this is the one being allocated from
4081 // the block is unused
4082 state = YAFFS_BLOCK_STATE_EMPTY;
4083 dev->nErasedBlocks++;
4087 // this is the block being allocated from
4088 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4089 state = YAFFS_BLOCK_STATE_ALLOCATING;
4090 dev->allocationBlock = blk;
4091 dev->allocationPage = c;
4094 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4096 else if(tags.chunkId > 0)
4100 yaffs_SetChunkBit(dev,blk,c);
4103 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4104 // PutChunkIntoFIle checks for a clash (two data chunks with
4105 // the same chunkId).
4106 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4107 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
4108 if(in->variant.fileVariant.scannedFileSize <endpos)
4110 in->variant.fileVariant.scannedFileSize = endpos;
4111 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4112 in->variant.fileVariant.fileSize =
4113 in->variant.fileVariant.scannedFileSize;
4117 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4121 // chunkId == 0, so it is an ObjectHeader.
4122 // Thus, we read in the object header and make the object
4123 yaffs_SetChunkBit(dev,blk,c);
4126 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
4128 oh = (yaffs_ObjectHeader *)chunkData;
4130 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4134 // We have already filled this one. We have a duplicate and need to resolve it.
4136 unsigned existingSerial = in->serial;
4137 unsigned newSerial = tags.serialNumber;
4139 if(((existingSerial+1) & 3) == newSerial)
4141 // Use new one - destroy the exisiting one
4142 yaffs_DeleteChunk(dev,in->chunkId,1);
4147 // Use existing - destroy this one.
4148 yaffs_DeleteChunk(dev,chunk,1);
4153 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4154 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4156 // We only load some info, don't fiddle with directory structure
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;
4181 // we need to load this info
4184 in->variantType = oh->type;
4186 in->st_mode = oh->st_mode;
4187 #ifdef CONFIG_YAFFS_WINCE
4188 in->win_atime[0] = oh->win_atime[0];
4189 in->win_ctime[0] = oh->win_ctime[0];
4190 in->win_mtime[0] = oh->win_mtime[0];
4191 in->win_atime[1] = oh->win_atime[1];
4192 in->win_ctime[1] = oh->win_ctime[1];
4193 in->win_mtime[1] = oh->win_mtime[1];
4195 in->st_uid = oh->st_uid;
4196 in->st_gid = oh->st_gid;
4197 in->st_atime = oh->st_atime;
4198 in->st_mtime = oh->st_mtime;
4199 in->st_ctime = oh->st_ctime;
4200 in->st_rdev = oh->st_rdev;
4202 in->chunkId = chunk;
4204 yaffs_SetObjectName(in,oh->name);
4207 // directory stuff...
4208 // hook up to parent
4210 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4211 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4213 // Set up as a directory
4214 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4215 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4217 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4219 // Hoosterman, another problem....
4220 // We're trying to use a non-directory as a directory
4222 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found." TENDSTR)));
4223 parent = dev->lostNFoundDir;
4227 yaffs_AddObjectToDirectory(parent,in);
4228 if(parent == dev->unlinkedDir)
4230 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4231 dev->nDeletedFiles++;
4234 // Note re hardlinks.
4235 // Since we might scan a hardlink before its equivalent object is scanned
4236 // we put them all in a list.
4237 // After scanning is complete, we should have all the objects, so we run through this
4238 // list and fix up all the chains.
4240 switch(in->variantType)
4242 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4244 case YAFFS_OBJECT_TYPE_FILE:
4245 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4246 in->variant.fileVariant.fileSize = oh->fileSize;
4249 case YAFFS_OBJECT_TYPE_HARDLINK:
4250 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4251 in->hardLinks.next = (struct list_head *)hardList;
4254 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4256 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4258 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4259 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4262 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4267 if(state == YAFFS_BLOCK_STATE_SCANNING)
4269 // If we got this far while scanning, then the block is fully allocated.
4270 state = YAFFS_BLOCK_STATE_FULL;
4273 bi->blockState = state;
4275 // Now let's see if it was dirty
4276 if( bi->pagesInUse == 0 &&
4277 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4279 yaffs_BlockBecameDirty(dev,blk);
4284 // Fix up the hard link chains.
4285 // We should now have scanned all the objects, now it's time to add these
4290 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4292 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4296 // Add the hardlink pointers
4297 hl->variant.hardLinkVariant.equivalentObject=in;
4298 list_add(&hl->hardLinks,&in->hardLinks);
4302 //Todo Need to report/handle this better.
4303 // Got a problem... hardlink to a non-existant object
4304 hl->variant.hardLinkVariant.equivalentObject=NULL;
4305 INIT_LIST_HEAD(&hl->hardLinks);
4312 struct list_head *i;
4313 struct list_head *n;
4316 // Soft delete all the unlinked files
4317 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
4321 l = list_entry(i, yaffs_Object,siblings);
4324 yaffs_SoftDeleteFile(l);
4335 ////////////////////////// Directory Functions /////////////////////////
4338 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
4341 if(obj->siblings.prev == NULL)
4344 INIT_LIST_HEAD(&obj->siblings);
4347 else if(!list_empty(&obj->siblings))
4349 // If it is holed up somewhere else, un hook it
4350 list_del_init(&obj->siblings);
4353 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
4354 obj->parent = directory;
4356 if(directory == obj->myDev->unlinkedDir)
4359 obj->myDev->nUnlinkedFiles++;
4360 obj->renameAllowed = 0;
4364 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4366 list_del_init(&obj->siblings);
4370 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
4374 struct list_head *i;
4375 char buffer[YAFFS_MAX_NAME_LENGTH+1];
4379 sum = yaffs_CalcNameSum(name);
4381 list_for_each(i,&directory->variant.directoryVariant.children)
4385 l = list_entry(i, yaffs_Object,siblings);
4387 // Special case for lost-n-found
4388 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4390 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
4395 else if(yaffs_SumCompare(l->sum, sum))
4398 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
4399 if(yaffs_strcmp(name,buffer) == 0)
4412 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
4414 struct list_head *i;
4418 list_for_each(i,&theDir->variant.directoryVariant.children)
4422 l = list_entry(i, yaffs_Object,siblings);
4435 // GetEquivalentObject dereferences any hard links to get to the
4438 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4440 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4442 // We want the object id of the equivalent object, not this one
4443 obj = obj->variant.hardLinkVariant.equivalentObject;
4449 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
4451 memset(name,0,buffSize);
4453 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4455 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
4457 else if(obj->chunkId <= 0)
4461 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
4462 strncpy(name,locName,buffSize - 1);
4465 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4466 else if(obj->shortName[0])
4468 strcpy(name,obj->shortName);
4473 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4474 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4476 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4478 if(obj->chunkId >= 0)
4480 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
4482 strncpy(name,oh->name,buffSize - 1);
4485 return strlen(name);
4488 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4491 // Dereference any hard linking
4492 obj = yaffs_GetEquivalentObject(obj);
4494 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4496 return obj->variant.fileVariant.fileSize;
4498 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4500 return strlen(obj->variant.symLinkVariant.alias);
4504 // Only a directory should drop through to here
4505 return YAFFS_BYTES_PER_CHUNK;
4509 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4512 struct list_head *i;
4516 count++; // the object itself
4518 list_for_each(i,&obj->hardLinks)
4520 count++; // add the hard links;
4527 int yaffs_GetObjectInode(yaffs_Object *obj)
4529 obj = yaffs_GetEquivalentObject(obj);
4531 return obj->objectId;
4534 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4536 obj = yaffs_GetEquivalentObject(obj);
4538 switch(obj->variantType)
4540 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
4541 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
4542 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
4543 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
4544 case YAFFS_OBJECT_TYPE_SPECIAL:
4545 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
4546 if(S_ISCHR(obj->st_mode)) return DT_CHR;
4547 if(S_ISBLK(obj->st_mode)) return DT_BLK;
4548 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
4549 default: return DT_REG; break;
4553 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4555 obj = yaffs_GetEquivalentObject(obj);
4556 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4558 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4562 return yaffs_CloneString("");
4566 #ifndef CONFIG_YAFFS_WINCE
4568 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4570 unsigned int valid = attr->ia_valid;
4572 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4573 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4574 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4576 if(valid & ATTR_ATIME) obj->st_atime = Y_TIME_CONVERT(attr->ia_atime);
4577 if(valid & ATTR_CTIME) obj->st_ctime = Y_TIME_CONVERT(attr->ia_ctime);
4578 if(valid & ATTR_MTIME) obj->st_mtime = Y_TIME_CONVERT(attr->ia_mtime);
4581 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4583 yaffs_UpdateObjectHeader(obj,NULL,1);
4589 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4591 unsigned int valid = 0;
4593 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
4594 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
4595 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
4598 Y_TIME_CONVERT(attr->ia_atime) = obj->st_atime; valid |= ATTR_ATIME;
4599 Y_TIME_CONVERT(attr->ia_ctime) = obj->st_ctime; valid |= ATTR_CTIME;
4600 Y_TIME_CONVERT(attr->ia_mtime) = obj->st_mtime; valid |= ATTR_MTIME;
4602 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4604 attr->ia_valid = valid;
4612 int yaffs_DumpObject(yaffs_Object *obj)
4614 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4616 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4618 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4620 // if(obj->chunkId >= 0)
4622 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4625 yaffs_GetObjectName(obj,name,256);
4627 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),
4628 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
4629 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4632 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4633 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
4634 obj->sum, obj->chunkId));
4635 switch(obj->variantType)
4637 case YAFFS_OBJECT_TYPE_FILE:
4638 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4640 case YAFFS_OBJECT_TYPE_DIRECTORY:
4641 YPRINTF((" DIRECTORY\n"));
4643 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4644 case YAFFS_OBJECT_TYPE_SYMLINK:
4645 case YAFFS_OBJECT_TYPE_UNKNOWN:
4654 ///////////////////////// Initialisation code ///////////////////////////
4658 int yaffs_GutsInitialise(yaffs_Device *dev)
4665 if( dev->nBytesPerChunk != YAFFS_BYTES_PER_CHUNK ||
4666 dev->nChunksPerBlock < 2 ||
4667 dev->nReservedBlocks < 2 ||
4668 dev->startBlock <= 0 ||
4669 dev->endBlock <= 0 ||
4670 dev->endBlock <= (dev->startBlock + dev->nReservedBlocks)
4673 //these parameters must be set before stating yaffs
4674 // Other parameters startBlock,
4680 if(!yaffs_CheckStructures())
4682 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
4688 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
4694 if(dev->startBlock <= 0 ||
4695 (dev->endBlock - dev->startBlock) < 10)
4697 T(YAFFS_TRACE_ALWAYS,(TSTR("startBlock %d or endBlock %d invalid\n" TENDSTR),
4698 dev->startBlock, dev->endBlock));
4702 nBlocks = dev->endBlock - dev->startBlock + 1;
4706 // OK now calculate a few things for the device
4707 // Calculate chunkGroupBits.
4708 // We need to find the next power of 2 > than endBlock
4710 x = dev->nChunksPerBlock * (dev->endBlock+1);
4712 for(bits = extraBits = 0; x > 1; bits++)
4714 if(x & 1) extraBits++;
4718 if(extraBits > 0) bits++;
4721 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4722 // chunk range we're using is greater than 16 we need
4723 // to figure out chunk shift and chunkGroupSize
4726 dev->chunkGroupBits = 0;
4730 dev->chunkGroupBits = bits - 16;
4733 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4735 if(dev->nChunksPerBlock < dev->chunkGroupSize)
4737 // We have a problem because the soft delete won't work if
4738 // the chunk group size > chunks per block.
4739 // This can be remedied by using larger "virtual blocks".
4747 // More device initialisation
4748 dev->garbageCollections = 0;
4749 dev->passiveGarbageCollections = 0;
4750 dev->currentDirtyChecker = 0;
4751 dev->bufferedBlock = -1;
4752 dev->doingBufferedBlockRewrite = 0;
4753 dev->nDeletedFiles = 0;
4754 dev->nBackgroundDeletions=0;
4755 dev->nUnlinkedFiles = 0;
4758 dev->tagsEccFixed=0;
4759 dev->tagsEccUnfixed=0;
4761 dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
4766 yaffs_InitialiseBlocks(dev,nBlocks);
4768 yaffs_InitialiseTnodes(dev);
4770 yaffs_InitialiseObjects(dev);
4772 if(dev->nShortOpCaches > 0)
4776 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
4778 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
4781 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
4783 for(i=0; i < dev->nShortOpCaches; i++)
4785 dev->srCache[i].object = NULL;
4786 dev->srCache[i].lastUse = 0;
4787 dev->srCache[i].dirty = 0;
4795 // Initialise the unlinked, root and lost and found directories
4796 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4798 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4800 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4801 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4802 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4805 // Now scan the flash.
4809 dev->nPageReads = 0;
4810 dev->nPageWrites = 0;
4811 dev->nBlockErasures = 0;
4813 dev->nRetriedWrites = 0;
4814 dev->nRetiredBlocks = 0;
4821 void yaffs_Deinitialise(yaffs_Device *dev)
4826 yaffs_DeinitialiseBlocks(dev);
4827 yaffs_DeinitialiseTnodes(dev);
4828 yaffs_DeinitialiseObjects(dev);
4829 if(dev->nShortOpCaches > 0)
4830 YFREE(dev->srCache);
4831 YFREE(dev->localBuffer);
4838 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4840 int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
4842 struct list_head *i;
4846 // To the free chunks add the chunks that are in the deleted unlinked files.
4847 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4849 l = list_entry(i, yaffs_Object,siblings);
4853 nFree += l->nDataChunks;
4858 // printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
4860 if(nFree < 0) nFree = 0;
4868 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4873 int nDirtyCacheChunks=0;
4875 yaffs_BlockInfo *blk;
4877 struct list_head *i;
4880 for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
4882 blk = yaffs_GetBlockInfo(dev,b);
4884 switch(blk->blockState)
4886 case YAFFS_BLOCK_STATE_EMPTY:
4887 case YAFFS_BLOCK_STATE_ALLOCATING:
4888 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
4896 // To the free chunks add the chunks that are in the deleted unlinked files.
4897 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4901 l = list_entry(i, yaffs_Object,siblings);
4905 pending += l->nDataChunks;
4912 //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
4914 if(nFree != dev->nFreeChunks)
4916 // printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
4921 // Now count the number of dirty chunks in the cache and subtract those
4925 for(i = 0; i < dev->nShortOpCaches; i++)
4927 if(dev->srCache[i].dirty) nDirtyCacheChunks++;
4931 nFree -= nDirtyCacheChunks;
4933 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
4935 if(nFree < 0) nFree = 0;
4943 /////////////////// YAFFS test code //////////////////////////////////
4945 #define yaffs_CheckStruct(structure,syze, name) \
4946 if(sizeof(structure) != syze) \
4948 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
4949 return YAFFS_FAIL; \
4953 static int yaffs_CheckStructures(void)
4955 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4956 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4957 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4958 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
4959 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4961 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4968 void yaffs_GutsTest(yaffs_Device *dev)
4971 if(yaffs_CheckStructures() != YAFFS_OK)
4973 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
4977 yaffs_TnodeTest(dev);
4978 yaffs_ObjectTest(dev);