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.28 2003-08-20 03:53:39 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 theChunk = (tn->level0[i] << in->myDev->chunkGroupBits);
1160 T(YAFFS_TRACE_SCAN,(TSTR("soft delete tch %d cgb %d chunk %d" TENDSTR),
1161 tn->level0[i],in->myDev->chunkGroupBits,theChunk));
1163 theBlock = yaffs_GetBlockInfo(in->myDev, theChunk/in->myDev->nChunksPerBlock);
1166 theBlock->softDeletions++;
1184 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1187 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1190 if(obj->nDataChunks <= 0)
1192 // Empty file, just delete it immediately
1193 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1194 obj->variant.fileVariant.top = NULL;
1195 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1196 yaffs_DoGenericObjectDeletion(obj);
1200 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1201 obj->softDeleted = 1;
1210 // Pruning removes any part of the file structure tree that is beyond the
1211 // bounds of the file (ie that does not point to chunks).
1213 // A file should only get pruned when its size is reduced.
1215 // Before pruning, the chunks must be pulled from the tree and the
1216 // level 0 tnode entries must be zeroed out.
1217 // Could also use this for file deletion, but that's probably better handled
1218 // by a special case.
1220 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1222 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1231 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1233 if(tn->internal[i] && level > 0)
1235 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1244 if(hasData == 0 && del0)
1246 // Free and return NULL
1248 yaffs_FreeTnode(dev,tn);
1258 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1265 if(fStruct->topLevel > 0)
1267 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1269 // Now we have a tree with all the non-zero branches NULL but the height
1270 // is the same as it was.
1271 // Let's see if we can trim internal tnodes to shorten the tree.
1272 // We can do this if only the 0th element in the tnode is in use
1273 // (ie all the non-zero are NULL)
1275 while(fStruct->topLevel && !done)
1280 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1290 fStruct->top = tn->internal[0];
1291 fStruct->topLevel--;
1292 yaffs_FreeTnode(dev,tn);
1308 /////////////////////// End of File Structure functions. /////////////////
1310 // yaffs_CreateFreeObjects creates a bunch more objects and
1311 // adds them to the object free list.
1312 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1315 yaffs_Object *newObjects;
1316 yaffs_ObjectList *list;
1318 if(nObjects < 1) return YAFFS_OK;
1320 // make these things
1322 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1326 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1330 // Hook them into the free list
1331 for(i = 0; i < nObjects - 1; i++)
1333 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1336 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1337 dev->freeObjects = newObjects;
1338 dev->nFreeObjects+= nObjects;
1339 dev->nObjectsCreated+= nObjects;
1341 // Now add this bunch of Objects to a list for freeing up.
1343 list = YMALLOC(sizeof(yaffs_ObjectList));
1346 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1350 list->objects = newObjects;
1351 list->next = dev->allocatedObjectList;
1352 dev->allocatedObjectList = list;
1361 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1362 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1364 yaffs_Object *tn = NULL;
1366 // If there are none left make more
1367 if(!dev->freeObjects)
1369 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1372 if(dev->freeObjects)
1374 tn = dev->freeObjects;
1375 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1376 dev->nFreeObjects--;
1378 // Now sweeten it up...
1380 memset(tn,0,sizeof(yaffs_Object));
1383 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1384 INIT_LIST_HEAD(&(tn->hardLinks));
1385 INIT_LIST_HEAD(&(tn->hashLink));
1386 INIT_LIST_HEAD(&tn->siblings);
1388 // Add it to the lost and found directory.
1389 // NB Can't put root or lostNFound in lostNFound so
1390 // check if lostNFound exists first
1391 if(dev->lostNFoundDir)
1393 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1401 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1404 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1407 obj->fake = 1; // it is fake so it has no NAND presence...
1408 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1409 obj->unlinkAllowed= 0; // ... or unlink it
1412 obj->st_mode = mode;
1414 obj->chunkId = 0; // Not a valid chunk.
1422 static void yaffs_UnhashObject(yaffs_Object *tn)
1425 yaffs_Device *dev = tn->myDev;
1428 // If it is still linked into the bucket list, free from the list
1429 if(!list_empty(&tn->hashLink))
1431 list_del_init(&tn->hashLink);
1432 bucket = yaffs_HashFunction(tn->objectId);
1433 dev->objectBucket[bucket].count--;
1439 // FreeObject frees up a Object and puts it back on the free list
1440 static void yaffs_FreeObject(yaffs_Object *tn)
1443 yaffs_Device *dev = tn->myDev;
1445 yaffs_UnhashObject(tn);
1447 // Link into the free list.
1448 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1449 dev->freeObjects = tn;
1450 dev->nFreeObjects++;
1456 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1458 // Free the list of allocated Objects
1460 yaffs_ObjectList *tmp;
1462 while( dev->allocatedObjectList)
1464 tmp = dev->allocatedObjectList->next;
1465 YFREE(dev->allocatedObjectList->objects);
1466 YFREE(dev->allocatedObjectList);
1468 dev->allocatedObjectList = tmp;
1471 dev->freeObjects = NULL;
1472 dev->nFreeObjects = 0;
1475 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1479 dev->allocatedObjectList = NULL;
1480 dev->freeObjects = NULL;
1481 dev->nFreeObjects = 0;
1483 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1485 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1486 dev->objectBucket[i].count = 0;
1496 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1501 int lowest = 999999;
1504 // First let's see if we can find one that's empty.
1506 for(i = 0; i < 10 && lowest > 0; i++)
1509 x %= YAFFS_NOBJECT_BUCKETS;
1510 if(dev->objectBucket[x].count < lowest)
1512 lowest = dev->objectBucket[x].count;
1518 // If we didn't find an empty list, then try
1519 // looking a bit further for a short one
1521 for(i = 0; i < 10 && lowest > 3; i++)
1524 x %= YAFFS_NOBJECT_BUCKETS;
1525 if(dev->objectBucket[x].count < lowest)
1527 lowest = dev->objectBucket[x].count;
1536 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1538 int bucket = yaffs_FindNiceObjectBucket(dev);
1540 // Now find an object value that has not already been taken
1541 // by scanning the list.
1544 struct list_head *i;
1546 __u32 n = (__u32)bucket;
1548 //yaffs_CheckObjectHashSanity();
1553 n += YAFFS_NOBJECT_BUCKETS;
1554 if(1 ||dev->objectBucket[bucket].count > 0)
1556 list_for_each(i,&dev->objectBucket[bucket].list)
1558 // If there is already one in the list
1559 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1567 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1572 void yaffs_HashObject(yaffs_Object *in)
1574 int bucket = yaffs_HashFunction(in->objectId);
1575 yaffs_Device *dev = in->myDev;
1577 if(!list_empty(&in->hashLink))
1583 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1584 dev->objectBucket[bucket].count++;
1588 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1590 int bucket = yaffs_HashFunction(number);
1591 struct list_head *i;
1594 list_for_each(i,&dev->objectBucket[bucket].list)
1596 // Look if it is in the list
1599 in = list_entry(i, yaffs_Object,hashLink);
1600 if(in->objectId == number)
1612 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1615 yaffs_Object *theObject;
1619 number = yaffs_CreateNewObjectNumber(dev);
1622 theObject = yaffs_AllocateEmptyObject(dev);
1626 theObject->fake = 0;
1627 theObject->renameAllowed = 1;
1628 theObject->unlinkAllowed = 1;
1629 theObject->objectId = number;
1630 yaffs_HashObject(theObject);
1631 theObject->variantType = type;
1632 #ifdef CONFIG_YAFFS_WINCE
1633 yfsd_WinFileTimeNow(theObject->win_atime);
1634 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1635 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1639 #if defined(CONFIG_KERNEL_2_5)
1640 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME.tv_sec;
1642 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1647 case YAFFS_OBJECT_TYPE_FILE:
1648 theObject->variant.fileVariant.fileSize = 0;
1649 theObject->variant.fileVariant.scannedFileSize = 0;
1650 theObject->variant.fileVariant.topLevel = 0;
1651 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1653 case YAFFS_OBJECT_TYPE_DIRECTORY:
1654 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1656 case YAFFS_OBJECT_TYPE_SYMLINK:
1657 // No action required
1659 case YAFFS_OBJECT_TYPE_HARDLINK:
1660 // No action required
1662 case YAFFS_OBJECT_TYPE_SPECIAL:
1663 // No action required
1665 case YAFFS_OBJECT_TYPE_UNKNOWN:
1666 // todo this should not happen
1674 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1676 yaffs_Object *theObject = NULL;
1680 theObject = yaffs_FindObjectByNumber(dev,number);
1685 theObject = yaffs_CreateNewObject(dev,number,type);
1692 char *yaffs_CloneString(const char *str)
1694 char *newStr = NULL;
1698 newStr = YMALLOC(strlen(str) + 1);
1707 // Mknod (create) a new object.
1708 // equivalentObject only has meaning for a hard link;
1709 // aliasString only has meaning for a sumlink.
1710 // rdev only has meaning for devices (a subset of special objects)
1711 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1712 yaffs_Object *parent,
1717 yaffs_Object *equivalentObject,
1718 const char *aliasString,
1723 yaffs_Device *dev = parent->myDev;
1725 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1726 if(yaffs_FindObjectByName(parent,name))
1731 in = yaffs_CreateNewObject(dev,-1,type);
1737 in->variantType = type;
1741 #ifdef CONFIG_YAFFS_WINCE
1742 yfsd_WinFileTimeNow(in->win_atime);
1743 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1744 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[0];
1747 #if defined(CONFIG_KERNEL_2_5)
1748 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME.tv_sec;
1750 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1756 in->nDataChunks = 0;
1758 yaffs_SetObjectName(in,name);
1761 yaffs_AddObjectToDirectory(parent,in);
1763 in->myDev = parent->myDev;
1768 case YAFFS_OBJECT_TYPE_SYMLINK:
1769 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1771 case YAFFS_OBJECT_TYPE_HARDLINK:
1772 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1773 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1774 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1776 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1777 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1778 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1779 case YAFFS_OBJECT_TYPE_UNKNOWN:
1783 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1784 yaffs_UpdateObjectHeader(in,name,0) < 0)
1786 // Could not create the object header, fail the creation
1787 yaffs_AbortHalfCreatedObject(in);
1796 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1798 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1801 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1803 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1806 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1808 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1811 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1813 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1816 // NB yaffs_Link returns the object id of the equivalent object.
1817 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1819 // Get the real object in case we were fed a hard link as an equivalent object
1820 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1822 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1824 return equivalentObject;
1834 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1840 newDir = obj->parent; // use the old directory
1843 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1845 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1846 // duplicate names are allowed.
1847 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1850 !yaffs_FindObjectByName(newDir,newName)) &&
1851 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1853 yaffs_SetObjectName(obj,newName);
1856 yaffs_AddObjectToDirectory(newDir,obj);
1858 if(unlinkOp) obj->unlinked = 1;
1861 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1872 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1877 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1878 // Special case for WinCE.
1879 // While look-up is case insensitive, the name isn't.
1880 // THerefore we might want to change x.txt to X.txt
1881 if(oldDir == newDir && _stricmp(oldName,newName) == 0)
1887 obj = yaffs_FindObjectByName(oldDir,oldName);
1888 if(obj && obj->renameAllowed)
1890 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1897 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1899 // Scan the buckets and check that the lists
1900 // have as many members as the count says there are
1903 struct list_head *j;
1906 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1910 list_for_each(j,&dev->objectBucket[bucket].list)
1915 if(countEm != dev->objectBucket[bucket].count)
1917 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1926 void yaffs_ObjectTest(yaffs_Device *dev)
1928 yaffs_Object *in[1000];
1930 yaffs_Object *inold[1000];
1934 memset(in,0,1000*sizeof(yaffs_Object *));
1935 memset(inold,0,1000*sizeof(yaffs_Object *));
1937 yaffs_CheckObjectHashSanity(dev);
1939 for(j = 0; j < 10; j++)
1943 for(i = 0; i < 1000; i++)
1945 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1948 YINFO("No more inodes");
1952 inNo[i] = in[i]->objectId;
1956 for(i = 0; i < 1000; i++)
1958 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1960 //T(("Differnce in look up test\n"));
1964 // T(("Look up ok\n"));
1968 yaffs_CheckObjectHashSanity(dev);
1970 for(i = 0; i < 1000; i+=3)
1972 yaffs_FreeObject(in[i]);
1977 yaffs_CheckObjectHashSanity(dev);
1984 /////////////////////////// Block Management and Page Allocation ///////////////////
1987 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1989 dev->allocationBlock = -1; // force it to get a new one
1990 //Todo we're assuming the malloc will pass.
1991 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1992 // Set up dynamic blockinfo stuff.
1993 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
1994 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1995 if(dev->blockInfo && dev->chunkBits)
1997 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1998 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
2006 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2008 YFREE(dev->blockInfo);
2009 dev->blockInfo = NULL;
2010 YFREE(dev->chunkBits);
2011 dev->chunkBits = NULL;
2014 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
2015 // for garbage collection.
2017 static int yaffs_FindDirtiestBlock(yaffs_Device *dev,int aggressive)
2020 int b = dev->currentDirtyChecker;
2026 yaffs_BlockInfo *bi;
2028 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2031 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2034 iterations = dev->endBlock - dev->startBlock + 1;
2038 iterations = dev->endBlock - dev->startBlock + 1;
2039 iterations = iterations / 16;
2040 if(iterations > 200)
2046 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2049 if ( b < dev->startBlock || b > dev->endBlock)
2051 b = dev->startBlock;
2054 if(b < dev->startBlock || b > dev->endBlock)
2056 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2060 bi = yaffs_GetBlockInfo(dev,b);
2062 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2063 (bi->pagesInUse - bi->softDeletions )< pagesInUse)
2066 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2070 dev->currentDirtyChecker = b;
2076 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2078 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2082 // If the block is still healthy erase it and mark as clean.
2083 // If the block has had a data failure, then retire it.
2084 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2086 if(!bi->needsRetiring)
2088 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2091 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2098 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2099 dev->nErasedBlocks++;
2101 bi->softDeletions = 0;
2102 yaffs_ClearChunkBits(dev,blockNo);
2104 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2108 yaffs_RetireBlock(dev,blockNo);
2109 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2114 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2118 yaffs_BlockInfo *bi;
2120 if(dev->nErasedBlocks < 1)
2122 // Hoosterman we've got a problem.
2123 // Can't get space to gc
2124 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during gc" TENDSTR)));
2129 // Find an empty block.
2131 for(i = dev->startBlock; i <= dev->endBlock; i++)
2133 dev->allocationBlockFinder++;
2134 if(dev->allocationBlockFinder <dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2136 dev->allocationBlockFinder = dev->startBlock;
2139 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2141 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2143 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2144 dev->nErasedBlocks--;
2145 return dev->allocationBlockFinder;
2154 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2157 yaffs_BlockInfo *bi;
2159 if(dev->allocationBlock < 0)
2161 // Get next block to allocate off
2162 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2163 dev->allocationPage = 0;
2166 if(!useReserve && dev->nErasedBlocks <= dev->nReservedBlocks)
2168 // Not enough space to allocate unless we're allowed to use the reserve.
2172 // Next page please....
2173 if(dev->allocationBlock >= 0)
2175 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2177 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2178 dev->allocationPage;
2180 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2182 dev->allocationPage++;
2186 // If the block is full set the state to full
2187 if(dev->allocationPage >= dev->nChunksPerBlock)
2189 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2190 dev->allocationBlock = -1;
2197 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2202 // To determine if we have enough space we just look at the
2203 // number of erased blocks.
2204 // The cache is allowed to use reserved blocks.
2206 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2208 return (dev->nErasedBlocks >= dev->nReservedBlocks);
2212 static int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2222 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
2224 // yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2226 yaffs_Object *object;
2228 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2230 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2231 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2232 chunkInBlock++, oldChunk++ )
2234 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2237 // This page is in use and might need to be copied off
2241 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2243 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
2245 yaffs_GetTagsFromSpare(dev,&spare,&tags);
2247 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2249 if(object && object->deleted && tags.chunkId != 0)
2251 // Data chunk in a deleted file, throw it away
2252 // It's a deleted data chunk,
2253 // No need to copy this, just forget about it and fix up the
2256 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2257 object->nDataChunks--;
2259 if(object->nDataChunks <= 0)
2261 // Time to delete the file too
2262 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2263 object->variant.fileVariant.top = NULL;
2264 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2265 yaffs_DoGenericObjectDeletion(object);
2269 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2271 // Deleted object header with no data chunks.
2272 // Can be discarded and the file deleted.
2273 object->chunkId = 0;
2274 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2275 object->variant.fileVariant.top = NULL;
2276 yaffs_DoGenericObjectDeletion(object);
2281 // It's either a data chunk in a live file or
2282 // an ObjectHeader, so we're interested in it.
2283 // NB Need to keep the ObjectHeaders of deleted files
2284 // until the whole file has been deleted off
2285 tags.serialNumber++;
2286 yaffs_LoadTagsIntoSpare(&spare,&tags);
2290 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
2297 // Ok, now fix up the Tnodes etc.
2299 if(tags.chunkId == 0)
2302 object->chunkId = newChunk;
2306 // It's a data chunk
2307 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2311 yaffs_DeleteChunk(dev,oldChunk,markNAND);
2320 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2322 // find a file to delete
2323 struct list_head *i;
2327 //Scan the unlinked files looking for one to delete
2328 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2332 l = list_entry(i, yaffs_Object,siblings);
2343 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2345 // This does background deletion on unlinked files.. only deleted ones.
2346 // If we don't have a file we're working on then find one
2347 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2349 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2352 // OK, we're working on a file...
2353 if(dev->unlinkedDeletion)
2355 yaffs_Object *obj = dev->unlinkedDeletion;
2357 int limit; // Number of chunks to delete in a file.
2358 // NB this can be exceeded, but not by much.
2362 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2364 if(obj->nDataChunks == 0)
2366 // Done all the deleting of data chunks.
2367 // Now dump the header and clean up
2368 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2369 obj->variant.fileVariant.top = NULL;
2370 yaffs_DoGenericObjectDeletion(obj);
2371 dev->nDeletedFiles--;
2372 dev->nUnlinkedFiles--;
2373 dev->nBackgroundDeletions++;
2374 dev->unlinkedDeletion = NULL;
2381 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
2382 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2387 //yaffs_DoUnlinkedFileDeletion(dev);
2389 if(dev->nErasedBlocks <= (dev->nReservedBlocks + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2396 block = yaffs_FindDirtiestBlock(dev,aggressive);
2400 dev->garbageCollections++;
2401 return yaffs_GarbageCollectBlock(dev,block);
2413 // New garbage collector
2414 // If we're very low on erased blocks then we do aggressive garbage collection
2415 // otherwise we do "passive" garbage collection.
2416 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2417 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2419 // The idea is to help clear out space in a more spread-out manner.
2420 // Dunno if it really does anything useful.
2422 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2427 //yaffs_DoUnlinkedFileDeletion(dev);
2429 if(dev->nErasedBlocks <= (dev->nReservedBlocks + 1))
2434 block = yaffs_FindDirtiestBlock(dev,aggressive);
2438 dev->garbageCollections++;
2441 dev->passiveGarbageCollections++;
2444 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2446 return yaffs_GarbageCollectBlock(dev,block);
2449 return aggressive ? YAFFS_FAIL : YAFFS_OK;
2453 //////////////////////////// TAGS ///////////////////////////////////////
2455 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2457 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2459 yaffs_CalcTagsECC(tagsPtr);
2461 sparePtr->tagByte0 = tu->asBytes[0];
2462 sparePtr->tagByte1 = tu->asBytes[1];
2463 sparePtr->tagByte2 = tu->asBytes[2];
2464 sparePtr->tagByte3 = tu->asBytes[3];
2465 sparePtr->tagByte4 = tu->asBytes[4];
2466 sparePtr->tagByte5 = tu->asBytes[5];
2467 sparePtr->tagByte6 = tu->asBytes[6];
2468 sparePtr->tagByte7 = tu->asBytes[7];
2471 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2473 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2476 tu->asBytes[0]= sparePtr->tagByte0;
2477 tu->asBytes[1]= sparePtr->tagByte1;
2478 tu->asBytes[2]= sparePtr->tagByte2;
2479 tu->asBytes[3]= sparePtr->tagByte3;
2480 tu->asBytes[4]= sparePtr->tagByte4;
2481 tu->asBytes[5]= sparePtr->tagByte5;
2482 tu->asBytes[6]= sparePtr->tagByte6;
2483 tu->asBytes[7]= sparePtr->tagByte7;
2485 result = yaffs_CheckECCOnTags(tagsPtr);
2488 dev->tagsEccFixed++;
2492 dev->tagsEccUnfixed++;
2496 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2498 memset(spare,0xFF,sizeof(yaffs_Spare));
2501 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2506 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2508 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2509 yaffs_GetTagsFromSpare(dev,&spare,tags);
2522 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2524 // NB There must be tags, data is optional
2525 // If there is data, then an ECC is calculated on it.
2534 yaffs_SpareInitialise(&spare);
2536 if(!dev->useNANDECC && buffer)
2538 yaffs_CalcECC(buffer,&spare);
2541 yaffs_LoadTagsIntoSpare(&spare,tags);
2543 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2549 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2551 // NB There must be tags, data is optional
2552 // If there is data, then an ECC is calculated on it.
2561 yaffs_SpareInitialise(&spare);
2563 if(!dev->useNANDECC && buffer)
2565 yaffs_CalcECC(buffer,&spare);
2568 yaffs_LoadTagsIntoSpare(&spare,tags);
2570 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2574 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2576 return ( tags->chunkId == chunkInObject &&
2577 tags->objectId == objectId &&
2578 !chunkDeleted) ? 1 : 0;
2584 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2586 //Get the Tnode, then get the level 0 offset chunk offset
2589 yaffs_Tags localTags;
2594 yaffs_Device *dev = in->myDev;
2599 // Passed a NULL, so use our own tags space
2603 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2607 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2609 // Now we need to do the shifting etc and search for it
2610 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2612 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2613 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2624 return found ? theChunk : -1;
2627 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2629 //Get the Tnode, then get the level 0 offset chunk offset
2632 yaffs_Tags localTags;
2635 yaffs_Device *dev = in->myDev;
2640 // Passed a NULL, so use our own tags space
2644 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2649 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2651 // Now we need to do the shifting etc and search for it
2652 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2654 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2655 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2666 // Delete the entry in the filestructure
2669 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2674 //T(("No level 0 found for %d\n", chunkInInode));
2679 //T(("Could not find %d to delete\n",chunkInInode));
2681 return found ? theChunk : -1;
2685 #ifdef YAFFS_PARANOID
2687 static int yaffs_CheckFileSanity(yaffs_Object *in)
2695 yaffs_Tags localTags;
2696 yaffs_Tags *tags = &localTags;
2701 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2703 //T(("Object not a file\n"));
2707 objId = in->objectId;
2708 fSize = in->variant.fileVariant.fileSize;
2709 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
2711 for(chunk = 1; chunk <= nChunks; chunk++)
2713 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2718 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2721 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2722 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2729 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2730 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2739 //T(("No level 0 found for %d\n", chunk));
2743 return failed ? YAFFS_FAIL : YAFFS_OK;
2748 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2751 yaffs_Device *dev = in->myDev;
2753 yaffs_Tags existingTags;
2755 unsigned existingSerial, newSerial;
2757 int newChunkDeleted;
2760 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2766 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2770 // If we're scanning then we need to test for duplicates
2771 // NB This does not need to be efficient since it should only ever
2772 // happen when the power fails during a write, then only one
2773 // chunk should ever be affected.
2776 if(existingChunk != 0)
2778 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2779 // thus we have to do a FindChunkInFile to get the real chunk id.
2781 // We have a duplicate now we need to decide which one to use
2782 // To do this we get both sets of tags and compare serial numbers.
2783 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2787 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2789 if(existingChunk <=0)
2791 //Hoosterman - how did this happen?
2793 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
2798 // NB The deleted flags should be false, otherwise the chunks will
2799 // not be loaded during a scan
2801 newSerial = newTags.serialNumber;
2802 existingSerial = existingTags.serialNumber;
2804 if( existingChunk <= 0 ||
2805 ((existingSerial+1) & 3) == newSerial)
2808 // Delete the old one and drop through to update the tnode
2809 yaffs_DeleteChunk(dev,existingChunk,1);
2814 // Delete the new one and return early so that the tnode isn't changed
2815 yaffs_DeleteChunk(dev,chunkInNAND,1);
2822 if(existingChunk == 0)
2827 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2834 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2836 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2838 if(chunkInNAND >= 0)
2840 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2850 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND)
2855 yaffs_BlockInfo *bi;
2857 if(chunkId <= 0) return;
2860 block = chunkId / dev->nChunksPerBlock;
2861 page = chunkId % dev->nChunksPerBlock;
2865 yaffs_SpareInitialise(&spare);
2867 spare.pageStatus = 0; // To mark it as deleted.
2870 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2871 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2875 dev->nUnmarkedDeletions++;
2878 bi = yaffs_GetBlockInfo(dev,block);
2881 // Pull out of the management area.
2882 // If the whole block became dirty, this will kick off an erasure.
2883 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2884 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2888 yaffs_ClearChunkBit(dev,block,page);
2891 if(bi->pagesInUse == 0 &&
2892 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2894 yaffs_BlockBecameDirty(dev,block);
2900 // T(("Bad news deleting chunk %d\n",chunkId));
2908 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2910 // Find old chunk Need to do this to get serial number
2911 // Write new one and patch into tree.
2912 // Invalidate old tags.
2915 yaffs_Tags prevTags;
2920 yaffs_Device *dev = in->myDev;
2922 yaffs_CheckGarbageCollection(dev);
2924 // Get the previous chunk at this location in the file if it exists
2925 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2928 newTags.chunkId = chunkInInode;
2929 newTags.objectId = in->objectId;
2930 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2931 newTags.byteCount = nBytes;
2932 newTags.unusedStuff = 0xFFFFFFFF;
2934 yaffs_CalcTagsECC(&newTags);
2936 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2939 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2942 if(prevChunkId >= 0)
2944 yaffs_DeleteChunk(dev,prevChunkId,1);
2948 yaffs_CheckFileSanity(in);
2959 // UpdateObjectHeader updates the header on NAND for an object.
2960 // If name is not NULL, then that new name is used.
2962 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2965 yaffs_Device *dev = in->myDev;
2971 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2972 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2974 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2975 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2978 if(!in->fake || force)
2981 yaffs_CheckGarbageCollection(dev);
2983 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2985 prevChunkId = in->chunkId;
2987 if(prevChunkId >= 0)
2989 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2993 oh->type = in->variantType;
2995 oh->st_mode = in->st_mode;
2997 #ifdef CONFIG_YAFFS_WINCE
2998 oh->win_atime[0] = in->win_atime[0];
2999 oh->win_ctime[0] = in->win_ctime[0];
3000 oh->win_mtime[0] = in->win_mtime[0];
3001 oh->win_atime[1] = in->win_atime[1];
3002 oh->win_ctime[1] = in->win_ctime[1];
3003 oh->win_mtime[1] = in->win_mtime[1];
3005 oh->st_uid = in->st_uid;
3006 oh->st_gid = in->st_gid;
3007 oh->st_atime = in->st_atime;
3008 oh->st_mtime = in->st_mtime;
3009 oh->st_ctime = in->st_ctime;
3010 oh->st_rdev = in->st_rdev;
3014 oh->parentObjectId = in->parent->objectId;
3018 oh->parentObjectId = 0;
3021 //oh->sum = in->sum;
3024 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3025 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3027 else if(prevChunkId)
3029 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
3033 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3036 switch(in->variantType)
3038 case YAFFS_OBJECT_TYPE_UNKNOWN:
3039 // Should not happen
3041 case YAFFS_OBJECT_TYPE_FILE:
3042 oh->fileSize = in->variant.fileVariant.fileSize;
3044 case YAFFS_OBJECT_TYPE_HARDLINK:
3045 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3047 case YAFFS_OBJECT_TYPE_SPECIAL:
3050 case YAFFS_OBJECT_TYPE_DIRECTORY:
3053 case YAFFS_OBJECT_TYPE_SYMLINK:
3054 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3055 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3061 newTags.chunkId = 0;
3062 newTags.objectId = in->objectId;
3063 newTags.serialNumber = in->serial;
3064 newTags.byteCount = 0xFFFFFFFF;
3065 newTags.unusedStuff = 0xFFFFFFFF;
3067 yaffs_CalcTagsECC(&newTags);
3070 // Create new chunk in NAND
3071 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3076 in->chunkId = newChunkId;
3078 if(prevChunkId >= 0)
3080 yaffs_DeleteChunk(dev,prevChunkId,1);
3093 /////////////////////// Short Operations Cache ////////////////////////////////
3094 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3095 // reads might be short sequential reads, and a lot of writes may be short
3096 // sequential writes. eg. scanning/writing a jpeg file.
3097 // In these cases, a short read/write cache can provide a huge perfomance benefit
3098 // with dumb-as-a-rock code.
3099 // There are a limited number (~10) of cache chunks per device so that we don't
3100 // need a very intelligent search.
3106 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3108 yaffs_Device *dev = obj->myDev;
3111 yaffs_ChunkCache *cache;
3114 int nCaches = obj->myDev->nShortOpCaches;
3121 // Find the dirty cache for this object with the lowest chunk id.
3122 for(i = 0; i < nCaches; i++)
3124 if(dev->srCache[i].object == obj &&
3125 dev->srCache[i].dirty)
3127 if(!cache || dev->srCache[i].chunkId < lowest)
3129 cache = &dev->srCache[i];
3130 lowest = cache->chunkId;
3140 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3142 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3144 nBytes= YAFFS_BYTES_PER_CHUNK;
3147 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3153 cache->object = NULL;
3156 } while(cache && chunkWritten > 0);
3160 //Hoosterman, disk full while writing cache out.
3161 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3169 // Grab us a chunk for use.
3170 // First look for an empty one.
3171 // Then look for the least recently used non-dirty one.
3172 // Then look for the least recently used dirty one...., flush and look again.
3173 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3179 if(dev->nShortOpCaches > 0)
3181 for(i = 0; i < dev->nShortOpCaches; i++)
3183 if(!dev->srCache[i].object)
3185 //T(("Grabbing empty %d\n",i));
3187 //printf("Grabbing empty %d\n",i);
3189 return &dev->srCache[i];
3196 usage = 0; // just to stop the compiler grizzling
3198 for(i = 0; i < dev->nShortOpCaches; i++)
3200 if(!dev->srCache[i].dirty &&
3201 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3204 usage = dev->srCache[i].lastUse;
3209 //T(("Grabbing non-empty %d\n",theOne));
3211 //if(theOne >= 0) printf("Grabbed non-empty cache %d\n",theOne);
3213 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3223 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3225 yaffs_ChunkCache *cache;
3226 yaffs_Object *theObj;
3231 if(dev->nShortOpCaches > 0)
3233 // Try find a non-dirty one...
3235 cache = yaffs_GrabChunkCacheWorker(dev);
3239 // They were all dirty, find the last recently used object and flush
3240 // its cache, then find again.
3241 // NB what's here is not very accurate, we actually flush the object
3242 // the last recently used page.
3244 theObj = dev->srCache[0].object;
3245 usage = dev->srCache[0].lastUse;
3246 cache = &dev->srCache[0];
3249 for(i = 1; i < dev->nShortOpCaches; i++)
3251 if( dev->srCache[i].object &&
3252 dev->srCache[i].lastUse < usage)
3254 usage = dev->srCache[i].lastUse;
3255 theObj = dev->srCache[i].object;
3256 cache = &dev->srCache[i];
3261 if(!cache || cache->dirty)
3265 yaffs_FlushFilesChunkCache(theObj);
3268 cache = yaffs_GrabChunkCacheWorker(dev);
3272 //printf(" pushout %d\n",pushout);
3285 // Find a cached chunk
3286 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3288 yaffs_Device *dev = obj->myDev;
3290 if(dev->nShortOpCaches > 0)
3292 for(i = 0; i < dev->nShortOpCaches; i++)
3294 if(dev->srCache[i].object == obj &&
3295 dev->srCache[i].chunkId == chunkId)
3299 return &dev->srCache[i];
3306 // Mark the chunk for the least recently used algorithym
3307 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3310 if(dev->nShortOpCaches > 0)
3312 if( dev->srLastUse < 0 ||
3313 dev->srLastUse > 100000000)
3315 // Reset the cache usages
3317 for(i = 1; i < dev->nShortOpCaches; i++)
3319 dev->srCache[i].lastUse = 0;
3326 cache->lastUse = dev->srLastUse;
3335 // Invalidate a single cache page.
3336 // Do this when a whole page gets written,
3337 // ie the short cache for this page is no longer valid.
3338 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3340 if(object->myDev->nShortOpCaches > 0)
3342 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3346 cache->object = NULL;
3352 // Invalidate all the cache pages associated with this object
3353 // Do this whenever ther file is deleted or resized.
3354 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3357 yaffs_Device *dev = in->myDev;
3359 if(dev->nShortOpCaches > 0)
3361 // Now invalidate it.
3362 for(i = 0; i < dev->nShortOpCaches; i++)
3364 if(dev->srCache[i].object == in)
3366 dev->srCache[i].object = NULL;
3376 ///////////////////////// File read/write ///////////////////////////////
3377 // Read and write have very similar structures.
3378 // In general the read/write has three parts to it
3379 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3380 // * Some complete chunks
3381 // * An incomplete chunk to end off with
3383 // Curve-balls: the first chunk might also be the last chunk.
3385 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3394 yaffs_ChunkCache *cache;
3402 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
3403 start = offset % YAFFS_BYTES_PER_CHUNK;
3405 // OK now check for the curveball where the start and end are in
3407 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3413 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3416 cache = yaffs_FindChunkCache(in,chunk);
3418 // If the chunk is already in the cache or it is less than a whole chunk
3419 // then use the cache (if there is caching)
3420 // else bypass the cache.
3421 if( cache || nToCopy != YAFFS_BYTES_PER_CHUNK)
3423 if(dev->nShortOpCaches > 0)
3426 // If we can't find the data in the cache, then load it up.
3430 cache = yaffs_GrabChunkCache(in->myDev);
3432 cache->chunkId = chunk;
3434 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3438 yaffs_UseChunkCache(dev,cache,0);
3440 memcpy(buffer,&cache->data[start],nToCopy);
3444 // Read into the local buffer then copy...
3445 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3446 memcpy(buffer,&dev->localBuffer[start],nToCopy);
3452 #ifdef CONFIG_YAFFS_WINCE
3454 // Under WinCE can't do direct transfer. Need to use a local buffer.
3455 // This is because we otherwise screw up WinCE's memory mapper
3456 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3457 memcpy(buffer,dev->localBuffer,YAFFS_BYTES_PER_CHUNK);
3459 // A full chunk. Read directly into the supplied buffer.
3460 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3476 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3485 int startOfWrite = offset;
3486 int chunkWritten = 0;
3494 while(n > 0 && chunkWritten >= 0)
3496 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
3497 start = offset % YAFFS_BYTES_PER_CHUNK;
3500 // OK now check for the curveball where the start and end are in
3503 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3507 // Now folks, to calculate how many bytes to write back....
3508 // If we're overwriting and not writing to then end of file then
3509 // we need to write back as much as was there before.
3511 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
3513 if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
3515 nBytesRead = YAFFS_BYTES_PER_CHUNK;
3518 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3523 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3524 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3527 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3529 // An incomplete start or end chunk (or maybe both start and end chunk)
3530 if(dev->nShortOpCaches > 0)
3532 yaffs_ChunkCache *cache;
3533 // If we can't find the data in the cache, then load it up.
3534 cache = yaffs_FindChunkCache(in,chunk);
3535 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3537 cache = yaffs_GrabChunkCache(in->myDev);
3539 cache->chunkId = chunk;
3541 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3546 yaffs_UseChunkCache(dev,cache,1);
3547 memcpy(&cache->data[start],buffer,nToCopy);
3548 cache->nBytes = nToWriteBack;
3552 chunkWritten = -1; // fail the write
3557 // An incomplete start or end chunk (or maybe both start and end chunk)
3558 // Read into the local buffer then copy, then copy over and write back.
3560 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3562 memcpy(&dev->localBuffer[start],buffer,nToCopy);
3564 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,nToWriteBack,0);
3566 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3573 #ifdef CONFIG_YAFFS_WINCE
3574 // Under WinCE can't do direct transfer. Need to use a local buffer.
3575 // This is because we otherwise screw up WinCE's memory mapper
3576 memcpy(dev->localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3577 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3579 // A full chunk. Write directly from the supplied buffer.
3580 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3582 // Since we've overwritten the cached data, we better invalidate it.
3583 yaffs_InvalidateChunkCache(in,chunk);
3584 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3587 if(chunkWritten >= 0)
3597 // Update file object
3599 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3601 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3610 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3614 int oldFileSize = in->variant.fileVariant.fileSize;
3615 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3617 yaffs_Device *dev = in->myDev;
3620 yaffs_FlushFilesChunkCache(in);
3621 yaffs_InvalidateWholeChunkCache(in);
3623 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3625 return yaffs_GetFileSize(in);
3628 if(newSize < oldFileSize)
3631 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3633 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3634 YAFFS_BYTES_PER_CHUNK;
3636 // Delete backwards so that we don't end up with holes if
3637 // power is lost part-way through the operation.
3638 for(i = lastDel; i >= startDel; i--)
3640 // NB this could be optimised somewhat,
3641 // eg. could retrieve the tags and write them without
3642 // using yaffs_DeleteChunk
3644 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3645 if(chunkId < (dev->startBlock * 32) || chunkId >= ((dev->endBlock+1) * 32))
3647 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3652 yaffs_DeleteChunk(dev,chunkId,1);
3657 if(sizeOfPartialChunk != 0)
3659 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3661 // Got to read and rewrite the last chunk with its new size.
3662 yaffs_ReadChunkDataFromObject(in,lastChunk,dev->localBuffer);
3664 yaffs_WriteChunkDataToObject(in,lastChunk,dev->localBuffer,sizeOfPartialChunk,1);
3668 in->variant.fileVariant.fileSize = newSize;
3670 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3682 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3684 obj = yaffs_GetEquivalentObject(obj);
3686 switch(obj->variantType)
3688 case YAFFS_OBJECT_TYPE_FILE:
3689 return obj->variant.fileVariant.fileSize;
3690 case YAFFS_OBJECT_TYPE_SYMLINK:
3691 return strlen(obj->variant.symLinkVariant.alias);
3699 // yaffs_FlushFile() updates the file's
3702 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
3707 //T(("flushing object header\n"));
3709 yaffs_FlushFilesChunkCache(in);
3712 #ifdef CONFIG_YAFFS_WINCE
3713 yfsd_WinFileTimeNow(in->win_mtime);
3715 #if defined(CONFIG_KERNEL_2_5)
3716 in->st_mtime = CURRENT_TIME.tv_sec;
3718 in->st_mtime = CURRENT_TIME;
3723 retVal = (yaffs_UpdateObjectHeader(in,NULL,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
3735 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3738 // First off, invalidate the file's data in the cache, without flushing.
3739 yaffs_InvalidateWholeChunkCache(in);
3741 yaffs_RemoveObjectFromDirectory(in);
3742 yaffs_DeleteChunk(in->myDev,in->chunkId,1);
3746 in->myInode->u.generic_ip = NULL;
3750 yaffs_FreeObject(in);
3755 // yaffs_DeleteFile deletes the whole file data
3756 // and the inode associated with the file.
3757 // It does not delete the links associated with the file.
3758 static int yaffs_UnlinkFile(yaffs_Object *in)
3761 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3763 // Delete the file data & tnodes
3765 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3768 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3770 return yaffs_DoGenericObjectDeletion(in);
3773 int immediateDeletion=0;
3774 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3775 if(1 || // Ignore the result of the change name. This will only fail
3776 // if the disk was completely full (an error condition)
3777 // We ignore the error so we can delete files to recover the disk
3781 //in->myDev->nUnlinkedFiles++;
3782 //in->renameAllowed = 0;
3786 immediateDeletion = 1;
3792 immediateDeletion = 1;
3797 if(immediateDeletion)
3799 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3801 in->myDev->nDeletedFiles++;
3802 yaffs_SoftDeleteFile(in);
3812 int yaffs_DeleteFile(yaffs_Object *in)
3814 int retVal = YAFFS_OK;
3816 if(in->nDataChunks > 0)
3818 // Use soft deletion
3821 retVal = yaffs_UnlinkFile(in);
3823 if(retVal == YAFFS_OK &&
3828 in->myDev->nDeletedFiles++;
3829 yaffs_SoftDeleteFile(in);
3831 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3835 // The file has no data chunks so we toss it immediately
3836 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3837 in->variant.fileVariant.top = NULL;
3838 yaffs_DoGenericObjectDeletion(in);
3844 static int yaffs_DeleteDirectory(yaffs_Object *in)
3846 //First check that the directory is empty.
3847 if(list_empty(&in->variant.directoryVariant.children))
3849 return yaffs_DoGenericObjectDeletion(in);
3856 static int yaffs_DeleteSymLink(yaffs_Object *in)
3858 YFREE(in->variant.symLinkVariant.alias);
3860 return yaffs_DoGenericObjectDeletion(in);
3863 static int yaffs_DeleteHardLink(yaffs_Object *in)
3865 // remove this hardlink from the list assocaited with the equivalent
3867 list_del(&in->hardLinks);
3868 return yaffs_DoGenericObjectDeletion(in);
3872 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj)
3874 switch(obj->variantType)
3876 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
3877 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
3878 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
3879 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
3880 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
3881 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
3886 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3890 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3892 return yaffs_DeleteHardLink(obj);
3894 else if(!list_empty(&obj->hardLinks))
3896 // Curve ball: We're unlinking an object that has a hardlink.
3898 // This problem arises because we are not strictly following
3899 // The Linux link/inode model.
3901 // We can't really delete the object.
3902 // Instead, we do the following:
3903 // - Select a hardlink.
3904 // - Unhook it from the hard links
3905 // - Unhook it from its parent directory (so that the rename can work)
3906 // - Rename the object to the hardlink's name.
3907 // - Delete the hardlink
3912 char name[YAFFS_MAX_NAME_LENGTH+1];
3914 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3916 list_del_init(&hl->hardLinks);
3917 list_del_init(&hl->siblings);
3919 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3921 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3923 if(retVal == YAFFS_OK)
3925 retVal = yaffs_DoGenericObjectDeletion(hl);
3932 switch(obj->variantType)
3934 case YAFFS_OBJECT_TYPE_FILE:
3935 return yaffs_UnlinkFile(obj);
3937 case YAFFS_OBJECT_TYPE_DIRECTORY:
3938 return yaffs_DeleteDirectory(obj);
3940 case YAFFS_OBJECT_TYPE_SYMLINK:
3941 return yaffs_DeleteSymLink(obj);
3943 case YAFFS_OBJECT_TYPE_HARDLINK:
3944 case YAFFS_OBJECT_TYPE_UNKNOWN:
3951 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3955 obj = yaffs_FindObjectByName(dir,name);
3957 if(obj && obj->unlinkAllowed)
3959 return yaffs_UnlinkWorker(obj);
3966 //////////////// Initialisation Scanning /////////////////
3970 // For now we use the SmartMedia check.
3971 // We look at the blockStatus byte in the first two chunks
3972 // These must be 0xFF to pass as OK.
3973 // todo: this function needs to be modifyable foir different NAND types
3974 // and different chunk sizes. Suggest make this into a per-device configurable
3976 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3980 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&spare,1);
3982 if(yaffs_CountBits(spare.blockStatus) < 7)
3987 if(spare.blockStatus != 0xFF)
3992 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
3995 if(yaffs_CountBits(spare.blockStatus) < 7)
4000 if(spare.blockStatus != 0xFF)
4010 static int yaffs_Scan(yaffs_Device *dev)
4018 yaffs_BlockState state;
4019 yaffs_Object *hardList = NULL;
4021 yaffs_BlockInfo *bi;
4024 yaffs_ObjectHeader *oh;
4026 yaffs_Object *parent;
4028 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
4031 // Scan all the blocks...
4033 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
4036 bi = yaffs_GetBlockInfo(dev,blk);
4037 yaffs_ClearChunkBits(dev,blk);
4039 bi->softDeletions = 0;
4040 state = YAFFS_BLOCK_STATE_SCANNING;
4043 if(yaffs_IsBlockBad(dev,blk))
4045 state = YAFFS_BLOCK_STATE_DEAD;
4046 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
4049 // Read each chunk in the block.
4051 for(c = 0; c < dev->nChunksPerBlock &&
4052 state == YAFFS_BLOCK_STATE_SCANNING; c++)
4054 // Read the spare area and decide what to do
4055 chunk = blk * dev->nChunksPerBlock + c;
4057 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
4060 // This block looks ok, now what's in this chunk?
4061 yaffs_GetTagsFromSpare(dev,&spare,&tags);
4063 if(yaffs_CountBits(spare.pageStatus) < 6)
4067 dev->nFreeChunks ++;
4068 //T((" %d %d deleted\n",blk,c));
4070 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
4072 // An unassigned chunk in the block
4073 // This means that either the block is empty or
4074 // this is the one being allocated from
4078 // the block is unused
4079 state = YAFFS_BLOCK_STATE_EMPTY;
4080 dev->nErasedBlocks++;
4084 // this is the block being allocated from
4085 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4086 state = YAFFS_BLOCK_STATE_ALLOCATING;
4087 dev->allocationBlock = blk;
4088 dev->allocationPage = c;
4091 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4093 else if(tags.chunkId > 0)
4097 yaffs_SetChunkBit(dev,blk,c);
4100 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4101 // PutChunkIntoFIle checks for a clash (two data chunks with
4102 // the same chunkId).
4103 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4104 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
4105 if(in->variant.fileVariant.scannedFileSize <endpos)
4107 in->variant.fileVariant.scannedFileSize = endpos;
4108 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4109 in->variant.fileVariant.fileSize =
4110 in->variant.fileVariant.scannedFileSize;
4114 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4118 // chunkId == 0, so it is an ObjectHeader.
4119 // Thus, we read in the object header and make the object
4120 yaffs_SetChunkBit(dev,blk,c);
4123 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
4125 oh = (yaffs_ObjectHeader *)chunkData;
4127 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4131 // We have already filled this one. We have a duplicate and need to resolve it.
4133 unsigned existingSerial = in->serial;
4134 unsigned newSerial = tags.serialNumber;
4136 if(((existingSerial+1) & 3) == newSerial)
4138 // Use new one - destroy the exisiting one
4139 yaffs_DeleteChunk(dev,in->chunkId,1);
4144 // Use existing - destroy this one.
4145 yaffs_DeleteChunk(dev,chunk,1);
4150 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4151 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4153 // We only load some info, don't fiddle with directory structure
4155 in->variantType = oh->type;
4157 in->st_mode = oh->st_mode;
4158 #ifdef CONFIG_YAFFS_WINCE
4159 in->win_atime[0] = oh->win_atime[0];
4160 in->win_ctime[0] = oh->win_ctime[0];
4161 in->win_mtime[0] = oh->win_mtime[0];
4162 in->win_atime[1] = oh->win_atime[1];
4163 in->win_ctime[1] = oh->win_ctime[1];
4164 in->win_mtime[1] = oh->win_mtime[1];
4166 in->st_uid = oh->st_uid;
4167 in->st_gid = oh->st_gid;
4168 in->st_atime = oh->st_atime;
4169 in->st_mtime = oh->st_mtime;
4170 in->st_ctime = oh->st_ctime;
4171 in->st_rdev = oh->st_rdev;
4173 in->chunkId = chunk;
4178 // we need to load this info
4181 in->variantType = oh->type;
4183 in->st_mode = oh->st_mode;
4184 #ifdef CONFIG_YAFFS_WINCE
4185 in->win_atime[0] = oh->win_atime[0];
4186 in->win_ctime[0] = oh->win_ctime[0];
4187 in->win_mtime[0] = oh->win_mtime[0];
4188 in->win_atime[1] = oh->win_atime[1];
4189 in->win_ctime[1] = oh->win_ctime[1];
4190 in->win_mtime[1] = oh->win_mtime[1];
4192 in->st_uid = oh->st_uid;
4193 in->st_gid = oh->st_gid;
4194 in->st_atime = oh->st_atime;
4195 in->st_mtime = oh->st_mtime;
4196 in->st_ctime = oh->st_ctime;
4197 in->st_rdev = oh->st_rdev;
4199 in->chunkId = chunk;
4201 yaffs_SetObjectName(in,oh->name);
4204 // directory stuff...
4205 // hook up to parent
4207 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4208 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4210 // Set up as a directory
4211 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4212 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4214 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4216 // Hoosterman, another problem....
4217 // We're trying to use a non-directory as a directory
4219 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan" TENDSTR)));
4223 yaffs_AddObjectToDirectory(parent,in);
4224 if(parent == dev->unlinkedDir)
4226 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4227 dev->nDeletedFiles++;
4230 // Note re hardlinks.
4231 // Since we might scan a hardlink before its equivalent object is scanned
4232 // we put them all in a list.
4233 // After scanning is complete, we should have all the objects, so we run through this
4234 // list and fix up all the chains.
4236 switch(in->variantType)
4238 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4240 case YAFFS_OBJECT_TYPE_FILE:
4241 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4242 in->variant.fileVariant.fileSize = oh->fileSize;
4245 case YAFFS_OBJECT_TYPE_HARDLINK:
4246 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4247 in->hardLinks.next = (struct list_head *)hardList;
4250 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4252 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4254 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4255 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4258 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4263 if(state == YAFFS_BLOCK_STATE_SCANNING)
4265 // If we got this far while scanning, then the block is fully allocated.
4266 state = YAFFS_BLOCK_STATE_FULL;
4269 bi->blockState = state;
4271 // Now let's see if it was dirty
4272 if( bi->pagesInUse == 0 &&
4273 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4275 yaffs_BlockBecameDirty(dev,blk);
4280 // Fix up the hard link chains.
4281 // We should now have scanned all the objects, now it's time to add these
4286 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4288 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4292 // Add the hardlink pointers
4293 hl->variant.hardLinkVariant.equivalentObject=in;
4294 list_add(&hl->hardLinks,&in->hardLinks);
4298 //Todo Need to report/handle this better.
4299 // Got a problem... hardlink to a non-existant object
4300 hl->variant.hardLinkVariant.equivalentObject=NULL;
4301 INIT_LIST_HEAD(&hl->hardLinks);
4308 struct list_head *i;
4309 struct list_head *n;
4312 // Soft delete all the unlinked files
4313 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
4317 l = list_entry(i, yaffs_Object,siblings);
4320 yaffs_SoftDeleteFile(l);
4331 ////////////////////////// Directory Functions /////////////////////////
4334 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
4337 if(obj->siblings.prev == NULL)
4340 INIT_LIST_HEAD(&obj->siblings);
4343 else if(!list_empty(&obj->siblings))
4345 // If it is holed up somewhere else, un hook it
4346 list_del_init(&obj->siblings);
4349 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
4350 obj->parent = directory;
4352 if(directory == obj->myDev->unlinkedDir)
4355 obj->myDev->nUnlinkedFiles++;
4356 obj->renameAllowed = 0;
4360 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4362 list_del_init(&obj->siblings);
4366 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
4370 struct list_head *i;
4371 char buffer[YAFFS_MAX_NAME_LENGTH+1];
4375 sum = yaffs_CalcNameSum(name);
4377 list_for_each(i,&directory->variant.directoryVariant.children)
4381 l = list_entry(i, yaffs_Object,siblings);
4383 // Special case for lost-n-found
4384 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4386 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
4391 else if(yaffs_SumCompare(l->sum, sum))
4394 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
4395 if(yaffs_strcmp(name,buffer) == 0)
4408 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
4410 struct list_head *i;
4414 list_for_each(i,&theDir->variant.directoryVariant.children)
4418 l = list_entry(i, yaffs_Object,siblings);
4431 // GetEquivalentObject dereferences any hard links to get to the
4434 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4436 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4438 // We want the object id of the equivalent object, not this one
4439 obj = obj->variant.hardLinkVariant.equivalentObject;
4445 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
4447 memset(name,0,buffSize);
4449 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4451 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
4453 else if(obj->chunkId <= 0)
4457 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
4458 strncpy(name,locName,buffSize - 1);
4461 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4462 else if(obj->shortName[0])
4464 strcpy(name,obj->shortName);
4469 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4470 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4472 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4474 if(obj->chunkId >= 0)
4476 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
4478 strncpy(name,oh->name,buffSize - 1);
4481 return strlen(name);
4484 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4487 // Dereference any hard linking
4488 obj = yaffs_GetEquivalentObject(obj);
4490 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4492 return obj->variant.fileVariant.fileSize;
4494 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4496 return strlen(obj->variant.symLinkVariant.alias);
4500 // Only a directory should drop through to here
4501 return YAFFS_BYTES_PER_CHUNK;
4505 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4508 struct list_head *i;
4512 count++; // the object itself
4514 list_for_each(i,&obj->hardLinks)
4516 count++; // add the hard links;
4523 int yaffs_GetObjectInode(yaffs_Object *obj)
4525 obj = yaffs_GetEquivalentObject(obj);
4527 return obj->objectId;
4530 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4532 obj = yaffs_GetEquivalentObject(obj);
4534 switch(obj->variantType)
4536 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
4537 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
4538 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
4539 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
4540 case YAFFS_OBJECT_TYPE_SPECIAL:
4541 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
4542 if(S_ISCHR(obj->st_mode)) return DT_CHR;
4543 if(S_ISBLK(obj->st_mode)) return DT_BLK;
4544 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
4545 default: return DT_REG; break;
4549 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4551 obj = yaffs_GetEquivalentObject(obj);
4552 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4554 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4558 return yaffs_CloneString("");
4562 #ifndef CONFIG_YAFFS_WINCE
4564 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4566 unsigned int valid = attr->ia_valid;
4568 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4569 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4570 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4572 #if defined(CONFIG_KERNEL_2_5)
4573 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime.tv_sec;
4574 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime.tv_sec;
4575 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime.tv_sec;
4577 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
4578 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
4579 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
4582 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4584 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;
4597 #if defined(CONFIG_KERNEL_2_5)
4598 attr->ia_atime.tv_sec = obj->st_atime; valid |= ATTR_ATIME;
4599 attr->ia_ctime.tv_sec = obj->st_ctime; valid |= ATTR_CTIME;
4600 attr->ia_mtime.tv_sec = obj->st_mtime; valid |= ATTR_MTIME;
4602 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
4603 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
4604 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
4606 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4608 attr->ia_valid = valid;
4616 int yaffs_DumpObject(yaffs_Object *obj)
4618 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4620 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4622 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4624 // if(obj->chunkId >= 0)
4626 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4629 yaffs_GetObjectName(obj,name,256);
4631 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),
4632 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
4633 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4636 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4637 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
4638 obj->sum, obj->chunkId));
4639 switch(obj->variantType)
4641 case YAFFS_OBJECT_TYPE_FILE:
4642 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4644 case YAFFS_OBJECT_TYPE_DIRECTORY:
4645 YPRINTF((" DIRECTORY\n"));
4647 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4648 case YAFFS_OBJECT_TYPE_SYMLINK:
4649 case YAFFS_OBJECT_TYPE_UNKNOWN:
4658 ///////////////////////// Initialisation code ///////////////////////////
4662 int yaffs_GutsInitialise(yaffs_Device *dev)
4669 if( dev->nBytesPerChunk != YAFFS_BYTES_PER_CHUNK ||
4671 dev->nChunksPerBlock < 2 ||
4672 dev->nReservedBlocks < 2 ||
4673 dev->startBlock <= 0 ||
4674 dev->endBlock <= 0 ||
4675 dev->endBlock <= (dev->startBlock + dev->nReservedBlocks)
4678 //these parameters must be set before stating yaffs
4679 // Other parameters startBlock,
4685 if(!yaffs_CheckStructures())
4687 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
4693 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
4699 if(dev->startBlock <= 0 ||
4700 (dev->endBlock - dev->startBlock) < 10)
4702 T(YAFFS_TRACE_ALWAYS,(TSTR("startBlock %d or endBlock %d invalid\n" TENDSTR),
4703 dev->startBlock, dev->endBlock));
4707 nBlocks = dev->endBlock - dev->startBlock + 1;
4711 // OK now calculate a few things for the device
4712 // Calculate chunkGroupBits.
4713 // We need to find the next power of 2 > than endBlock
4715 x = dev->nChunksPerBlock * (dev->endBlock+1);
4717 for(bits = extraBits = 0; x > 1; bits++)
4719 if(x & 1) extraBits++;
4723 if(extraBits > 0) bits++;
4726 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4727 // chunk range we're using is greater than 16 we need
4728 // to figure out chunk shift and chunkGroupSize
4731 dev->chunkGroupBits = 0;
4735 dev->chunkGroupBits = bits - 16;
4737 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4741 // More device initialisation
4742 dev->garbageCollections = 0;
4743 dev->passiveGarbageCollections = 0;
4744 dev->currentDirtyChecker = 0;
4745 dev->bufferedBlock = -1;
4746 dev->doingBufferedBlockRewrite = 0;
4747 dev->nDeletedFiles = 0;
4748 dev->nBackgroundDeletions=0;
4749 dev->nUnlinkedFiles = 0;
4752 dev->tagsEccFixed=0;
4753 dev->tagsEccUnfixed=0;
4755 dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
4760 yaffs_InitialiseBlocks(dev,nBlocks);
4762 yaffs_InitialiseTnodes(dev);
4764 yaffs_InitialiseObjects(dev);
4766 if(dev->nShortOpCaches > 0)
4770 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
4772 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
4775 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
4777 for(i=0; i < dev->nShortOpCaches; i++)
4779 dev->srCache[i].object = NULL;
4780 dev->srCache[i].lastUse = 0;
4781 dev->srCache[i].dirty = 0;
4789 // Initialise the unlinked, root and lost and found directories
4790 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4792 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4794 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4795 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4796 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4799 // Now scan the flash.
4803 dev->nPageReads = 0;
4804 dev->nPageWrites = 0;
4805 dev->nBlockErasures = 0;
4807 dev->nRetriedWrites = 0;
4808 dev->nRetiredBlocks = 0;
4815 void yaffs_Deinitialise(yaffs_Device *dev)
4820 yaffs_DeinitialiseBlocks(dev);
4821 yaffs_DeinitialiseTnodes(dev);
4822 yaffs_DeinitialiseObjects(dev);
4823 YFREE(dev->localBuffer);
4830 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4832 int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
4834 struct list_head *i;
4838 // To the free chunks add the chunks that are in the deleted unlinked files.
4839 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4841 l = list_entry(i, yaffs_Object,siblings);
4845 nFree += l->nDataChunks;
4850 // printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
4852 if(nFree < 0) nFree = 0;
4860 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4865 int nDirtyCacheChunks=0;
4867 yaffs_BlockInfo *blk;
4869 struct list_head *i;
4872 for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
4874 blk = yaffs_GetBlockInfo(dev,b);
4876 switch(blk->blockState)
4878 case YAFFS_BLOCK_STATE_EMPTY:
4879 case YAFFS_BLOCK_STATE_ALLOCATING:
4880 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
4888 // To the free chunks add the chunks that are in the deleted unlinked files.
4889 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4893 l = list_entry(i, yaffs_Object,siblings);
4897 pending += l->nDataChunks;
4904 //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
4906 if(nFree != dev->nFreeChunks)
4908 // printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
4913 // Now count the number of dirty chunks in the cache and subtract those
4917 for(i = 0; i < dev->nShortOpCaches; i++)
4919 if(dev->srCache[i].dirty) nDirtyCacheChunks++;
4923 nFree -= nDirtyCacheChunks;
4925 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
4927 if(nFree < 0) nFree = 0;
4935 /////////////////// YAFFS test code //////////////////////////////////
4937 #define yaffs_CheckStruct(structure,syze, name) \
4938 if(sizeof(structure) != syze) \
4940 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
4941 return YAFFS_FAIL; \
4945 static int yaffs_CheckStructures(void)
4947 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4948 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4949 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4950 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
4951 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4953 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4960 void yaffs_GutsTest(yaffs_Device *dev)
4963 if(yaffs_CheckStructures() != YAFFS_OK)
4965 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
4969 yaffs_TnodeTest(dev);
4970 yaffs_ObjectTest(dev);