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.16 2003-01-14 23:15:29 charles Exp $";
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
25 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
29 // External functions for ECC on data
30 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
31 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
34 // countBits is a quick way of counting the number of bits in a byte.
35 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
37 static const char yaffs_countBitsTable[256] =
39 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
40 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
41 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
42 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
43 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
44 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
45 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
46 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
47 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
48 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
49 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
50 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
51 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
52 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
53 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
54 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
57 static int yaffs_CountBits(__u8 x)
60 retVal = yaffs_countBitsTable[x];
67 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
68 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
69 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
70 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
72 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
73 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
74 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force);
75 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND);
76 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
77 static int yaffs_CheckStructures(void);
78 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
84 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
85 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
86 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
87 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare);
88 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare);
90 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
92 static int yaffs_UnlinkWorker(yaffs_Object *obj);
93 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj);
95 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1);
99 loff_t yaffs_GetFileSize(yaffs_Object *obj);
101 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
102 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
105 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
107 #ifdef YAFFS_PARANOID
108 static int yaffs_CheckFileSanity(yaffs_Object *in);
110 #define yaffs_CheckFileSanity(in)
113 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
114 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
116 // Chunk bitmap manipulations
118 static __inline __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
120 if(blk < dev->startBlock || blk > dev->endBlock)
122 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
125 return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->startBlock));
128 static __inline__ void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
130 __u8 *blkBits = yaffs_BlockBits(dev,blk);
132 memset(blkBits,0,dev->chunkBitmapStride);
135 static __inline__ void yaffs_ClearChunkBit(yaffs_Device *dev,int blk,int chunk)
137 __u8 *blkBits = yaffs_BlockBits(dev,blk);
139 blkBits[chunk/8] &= ~ (1<<(chunk & 7));
142 static __inline__ void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
144 __u8 *blkBits = yaffs_BlockBits(dev,blk);
146 blkBits[chunk/8] |= (1<<(chunk & 7));
149 static __inline__ int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
151 __u8 *blkBits = yaffs_BlockBits(dev,blk);
152 return (blkBits[chunk/8] & (1<<(chunk & 7))) ? 1 :0;
155 static __inline__ int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
157 __u8 *blkBits = yaffs_BlockBits(dev,blk);
159 for(i = 0; i < dev->chunkBitmapStride; i++)
161 if(*blkBits) return 1;
167 // Function to manipulate block info
168 static __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
170 if(blk < dev->startBlock || blk > dev->endBlock)
172 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),blk));
175 return &dev->blockInfo[blk - dev->startBlock];
179 static __inline__ int yaffs_HashFunction(int n)
181 return (n % YAFFS_NOBJECT_BUCKETS);
185 yaffs_Object *yaffs_Root(yaffs_Device *dev)
190 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
192 return dev->lostNFoundDir;
196 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
198 if(chunkInNAND < dev->startBlock * YAFFS_CHUNKS_PER_BLOCK)
200 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
205 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
210 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
214 int doErrorCorrection)
217 yaffs_Spare localSpare;
220 int eccResult1,eccResult2;
221 struct yaffs_NANDSpare nspare;
230 // If we don't have a real spare, then we use a local one.
231 // Need this for the calculation of the ecc
238 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
239 if(data && doErrorCorrection)
242 //Todo handle any errors
243 nand_calculate_ecc(data,calcEcc);
244 eccResult1 = nand_correct_data (data,spare->ecc1, calcEcc);
245 nand_calculate_ecc(&data[256],calcEcc);
246 eccResult2 = nand_correct_data (&data[256],spare->ecc2, calcEcc);
250 T(YAFFS_TRACE_ERROR, (TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
253 else if(eccResult1<0)
255 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
261 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
264 else if(eccResult2<0)
266 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
270 if(eccResult1 || eccResult2)
272 // Hoosterman, we had a data problem on this page
273 yaffs_HandleReadDataError(dev,chunkInNAND);
279 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
280 memcpy (spare, &nspare, sizeof(yaffs_Spare));
281 if(data && doErrorCorrection)
285 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
287 else if(nspare.eccres1<0)
289 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
294 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
296 else if(nspare.eccres2<0)
298 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
301 if(nspare.eccres2 || nspare.eccres2)
303 // Hoosterman, we had a data problem on this page
304 yaffs_HandleReadDataError(dev,chunkInNAND);
313 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
317 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
318 static __u8 data[YAFFS_BYTES_PER_CHUNK];
319 static __u8 spare[16];
322 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
328 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
332 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL;
333 if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
342 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
344 dev->nBlockErasures++;
345 return dev->eraseBlockInNAND(dev,blockInNAND);
348 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
350 return dev->initialiseNAND(dev);
353 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
360 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
364 chunk = yaffs_AllocateChunk(dev,useReserve);
369 // First check this chunk is erased...
370 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
371 writeOk = yaffs_CheckChunkErased(dev,chunk);
375 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
379 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
385 // If verify fails, then delete this chunk and try again
386 // To verify we compare everything except the block and
387 // page status bytes.
388 // NB We check a raw read without ECC correction applied
389 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
391 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
392 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
395 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
404 // Copy the data into the write buffer.
405 // NB We do this at the end to prevent duplicates in the case of a write error.
407 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
411 yaffs_HandleWriteChunkError(dev,chunk);
415 } while(chunk >= 0 && ! writeOk);
419 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
420 dev->nRetriedWrites+= (attempts - 1);
427 // Functions for robustisizing
431 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
433 // Ding the blockStatus in the first two pages of the block.
437 memset(&spare, 0xff,sizeof(yaffs_Spare));
439 spare.blockStatus = 0;
441 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK, NULL , &spare);
442 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK + 1, NULL , &spare);
444 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
445 dev->nRetiredBlocks++;
450 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
452 dev->doingBufferedBlockRewrite = 1;
454 // Remove erased chunks
455 // Rewrite existing chunks to a new block
456 // Set current write block to the new block
458 dev->doingBufferedBlockRewrite = 0;
464 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
466 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
468 // Mark the block for retirement
469 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
470 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
474 // Just do a garbage collection on the affected block then retire the block
479 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
483 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare)
487 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare)
491 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
493 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
495 // Mark the block for retirement
496 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
498 yaffs_DeleteChunk(dev,chunkInNAND,1);
504 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1)
508 if( memcmp(d0,d1,YAFFS_BYTES_PER_CHUNK) != 0 ||
509 s0->tagByte0 != s1->tagByte0 ||
510 s0->tagByte1 != s1->tagByte1 ||
511 s0->tagByte2 != s1->tagByte2 ||
512 s0->tagByte3 != s1->tagByte3 ||
513 s0->tagByte4 != s1->tagByte4 ||
514 s0->tagByte5 != s1->tagByte5 ||
515 s0->tagByte6 != s1->tagByte6 ||
516 s0->tagByte7 != s1->tagByte7 ||
517 s0->ecc1[0] != s1->ecc1[0] ||
518 s0->ecc1[1] != s1->ecc1[1] ||
519 s0->ecc1[2] != s1->ecc1[2] ||
520 s0->ecc2[0] != s1->ecc2[0] ||
521 s0->ecc2[1] != s1->ecc2[1] ||
522 s0->ecc2[2] != s1->ecc2[2] )
531 ///////////////////////// Object management //////////////////
532 // List of spare objects
533 // The list is hooked together using the first pointer
536 // static yaffs_Object *yaffs_freeObjects = NULL;
538 // static int yaffs_nFreeObjects;
540 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
542 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
545 static __u16 yaffs_CalcNameSum(const char *name)
550 __u8 *bname = (__u8 *)name;
553 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
556 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
557 sum += toupper(*bname) * i;
568 void yaffs_SetObjectName(yaffs_Object *obj, const char *name)
570 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
571 if(name && strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
573 strcpy(obj->shortName,name);
577 obj->shortName[0]='\0';
580 obj->sum = yaffs_CalcNameSum(name);
583 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
585 nand_calculate_ecc (data , spare->ecc1);
586 nand_calculate_ecc (&data[256] , spare->ecc2);
589 void yaffs_CalcTagsECC(yaffs_Tags *tags)
593 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
600 for(i = 0; i < 8; i++)
602 for(j = 1; j &0xff; j<<=1)
617 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
619 unsigned ecc = tags->ecc;
621 yaffs_CalcTagsECC(tags);
627 // TODO: Handle the failure better. Retire?
628 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
632 b[ecc / 8] ^= (1 << (ecc & 7));
634 // Now recvalc the ecc
635 yaffs_CalcTagsECC(tags);
637 return 1; // recovered error
641 // Wierd ecc failure value
642 // TODO Need to do somethiong here
643 return -1; //unrecovered error
650 ///////////////////////// TNODES ///////////////////////
652 // List of spare tnodes
653 // The list is hooked together using the first pointer
656 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
658 // static int yaffs_nFreeTnodes;
660 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
664 // yaffs_CreateTnodes creates a bunch more tnodes and
665 // adds them to the tnode free list.
666 // Don't use this function directly
668 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
671 yaffs_Tnode *newTnodes;
672 yaffs_TnodeList *tnl;
674 if(nTnodes < 1) return YAFFS_OK;
678 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
682 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
686 // Hook them into the free list
687 for(i = 0; i < nTnodes - 1; i++)
689 newTnodes[i].internal[0] = &newTnodes[i+1];
690 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
691 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = 1;
695 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
696 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
697 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = 1;
699 dev->freeTnodes = newTnodes;
700 dev->nFreeTnodes+= nTnodes;
701 dev->nTnodesCreated += nTnodes;
703 // Now add this bunch of tnodes to a list for freeing up.
704 // NB If we can't add this to the management list it isn't fatal
705 // but it just means we can't free this bunch of tnodes later.
706 tnl = YMALLOC(sizeof(yaffs_TnodeList));
709 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
714 tnl->tnodes = newTnodes;
715 tnl->next = dev->allocatedTnodeList;
716 dev->allocatedTnodeList = tnl;
720 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
727 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
728 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
730 yaffs_Tnode *tn = NULL;
732 // If there are none left make more
735 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
740 tn = dev->freeTnodes;
741 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
742 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 1)
744 // Hoosterman, this thing looks like it isn't in the list
745 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 1" TENDSTR)));
748 dev->freeTnodes = dev->freeTnodes->internal[0];
751 memset(tn,0,sizeof(yaffs_Tnode));
759 // FreeTnode frees up a tnode and puts it back on the free list
760 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
764 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
765 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 0)
767 // Hoosterman, this thing looks like it is already in the list
768 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 2" TENDSTR)));
770 tn->internal[YAFFS_NTNODES_INTERNAL] = 1;
772 tn->internal[0] = dev->freeTnodes;
773 dev->freeTnodes = tn;
779 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
781 // Free the list of allocated tnodes
783 while(dev->allocatedTnodeList)
785 YFREE(dev->allocatedTnodeList->tnodes);
786 dev->allocatedTnodeList = dev->allocatedTnodeList->next;
789 dev->freeTnodes = NULL;
790 dev->nFreeTnodes = 0;
793 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
795 dev->allocatedTnodeList = NULL;
796 dev->freeTnodes = NULL;
797 dev->nFreeTnodes = 0;
798 dev->nTnodesCreated = 0;
803 void yaffs_TnodeTest(yaffs_Device *dev)
808 yaffs_Tnode *tn[1000];
810 YINFO("Testing TNodes");
812 for(j = 0; j < 50; j++)
814 for(i = 0; i < 1000; i++)
816 tn[i] = yaffs_GetTnode(dev);
819 YALERT("Getting tnode failed");
822 for(i = 0; i < 1000; i+=3)
824 yaffs_FreeTnode(dev,tn[i]);
833 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
835 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
836 // The look up tree is represented by the top tnode and the number of topLevel
837 // in the tree. 0 means only the level 0 tnode is in the tree.
840 // FindLevel0Tnode finds the level 0 tnode, if one exists.
841 // Used when reading.....
842 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
845 yaffs_Tnode *tn = fStruct->top;
847 int requiredTallness;
848 int level = fStruct->topLevel;
850 // Check sane level and chunk Id
851 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
854 // sprintf(str,"Bad level %d",level);
859 if(chunkId > YAFFS_MAX_CHUNK_ID)
862 // sprintf(str,"Bad chunkId %d",chunkId);
867 // First check we're tall enough (ie enough topLevel)
869 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
870 requiredTallness = 0;
873 i >>= YAFFS_TNODES_INTERNAL_BITS;
878 if(requiredTallness > fStruct->topLevel)
880 // Not tall enough, so we can't find it, return NULL.
885 // Traverse down to level 0
886 while (level > 0 && tn)
888 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
889 YAFFS_TNODES_INTERNAL_MASK];
897 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
898 // This happens in two steps:
899 // 1. If the tree isn't tall enough, then make it taller.
900 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
902 // Used when modifying the tree.
904 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
909 int requiredTallness;
916 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
918 // Check sane level and page Id
919 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
922 // sprintf(str,"Bad level %d",fStruct->topLevel);
927 if(chunkId > YAFFS_MAX_CHUNK_ID)
930 // sprintf(str,"Bad chunkId %d",chunkId);
935 // First check we're tall enough (ie enough topLevel)
937 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
938 requiredTallness = 0;
941 x >>= YAFFS_TNODES_INTERNAL_BITS;
945 //T((TSTR(" required=%d"),requiredTallness));
948 if(requiredTallness > fStruct->topLevel)
950 // Not tall enough,gotta make the tree taller
951 for(i = fStruct->topLevel; i < requiredTallness; i++)
953 //T((TSTR(" add new top")));
955 tn = yaffs_GetTnode(dev);
959 tn->internal[0] = fStruct->top;
964 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
968 fStruct->topLevel = requiredTallness;
972 // Traverse down to level 0, adding anything we need
974 l = fStruct->topLevel;
978 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
979 YAFFS_TNODES_INTERNAL_MASK;
981 //T((TSTR(" [%d:%d]"),l,i));
985 //T((TSTR(" added")));
987 tn->internal[x] = yaffs_GetTnode(dev);
990 tn = tn->internal[x];
1000 // DeleteWorker scans backwards through the tnode tree and deletes all the
1001 // chunks and tnodes in the file
1002 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1004 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1020 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1024 if(limit && (*limit) < 0)
1030 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1031 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1035 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1036 tn->internal[i] = NULL;
1041 return (allDone) ? 1 : 0;
1047 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1053 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1055 theChunk = tn->level0[i] << in->myDev->chunkGroupBits;
1057 // Now we need to search for it
1058 for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
1060 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
1061 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
1075 yaffs_DeleteChunk(in->myDev,theChunk,1);
1092 return (i < 0) ? 1 : 0;
1103 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1104 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1106 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1108 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1113 yaffs_BlockInfo *theBlock;
1125 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1129 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1130 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1133 yaffs_FreeTnode(in->myDev,tn->internal[i]);
1134 tn->internal[i] = NULL;
1138 //Hoosterman... how could this happen.
1142 return (allDone) ? 1 : 0;
1147 for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1152 theChunk = (tn->level0[i] << in->myDev->chunkGroupBits);
1153 theBlock = yaffs_GetBlockInfo(in->myDev, theChunk/ YAFFS_CHUNKS_PER_BLOCK);
1156 theBlock->softDeletions++;
1174 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1177 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1180 if(obj->nDataChunks <= 0)
1182 // Empty file, just delete it immediately
1183 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1184 obj->variant.fileVariant.top = NULL;
1185 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1186 yaffs_DoGenericObjectDeletion(obj);
1190 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1191 obj->softDeleted = 1;
1200 // Pruning removes any part of the file structure tree that is beyond the
1201 // bounds of the file (ie that does not point to chunks).
1203 // A file should only get pruned when its size is reduced.
1205 // Before pruning, the chunks must be pulled from the tree and the
1206 // level 0 tnode entries must be zeroed out.
1207 // Could also use this for file deletion, but that's probably better handled
1208 // by a special case.
1210 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1212 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1221 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1223 if(tn->internal[i] && level > 0)
1225 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1234 if(hasData == 0 && del0)
1236 // Free and return NULL
1238 yaffs_FreeTnode(dev,tn);
1248 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1255 if(fStruct->topLevel > 0)
1257 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1259 // Now we have a tree with all the non-zero branches NULL but the height
1260 // is the same as it was.
1261 // Let's see if we can trim internal tnodes to shorten the tree.
1262 // We can do this if only the 0th element in the tnode is in use
1263 // (ie all the non-zero are NULL)
1265 while(fStruct->topLevel && !done)
1270 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1280 fStruct->top = tn->internal[0];
1281 fStruct->topLevel--;
1282 yaffs_FreeTnode(dev,tn);
1298 /////////////////////// End of File Structure functions. /////////////////
1300 // yaffs_CreateFreeObjects creates a bunch more objects and
1301 // adds them to the object free list.
1302 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1305 yaffs_Object *newObjects;
1306 yaffs_ObjectList *list;
1308 if(nObjects < 1) return YAFFS_OK;
1310 // make these things
1312 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1316 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1320 // Hook them into the free list
1321 for(i = 0; i < nObjects - 1; i++)
1323 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1326 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1327 dev->freeObjects = newObjects;
1328 dev->nFreeObjects+= nObjects;
1329 dev->nObjectsCreated+= nObjects;
1331 // Now add this bunch of Objects to a list for freeing up.
1333 list = YMALLOC(sizeof(yaffs_ObjectList));
1336 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1340 list->objects = newObjects;
1341 list->next = dev->allocatedObjectList;
1342 dev->allocatedObjectList = list;
1351 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1352 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1354 yaffs_Object *tn = NULL;
1356 // If there are none left make more
1357 if(!dev->freeObjects)
1359 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1362 if(dev->freeObjects)
1364 tn = dev->freeObjects;
1365 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1366 dev->nFreeObjects--;
1368 // Now sweeten it up...
1370 memset(tn,0,sizeof(yaffs_Object));
1373 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1374 INIT_LIST_HEAD(&(tn->hardLinks));
1375 INIT_LIST_HEAD(&(tn->hashLink));
1376 INIT_LIST_HEAD(&tn->siblings);
1378 // Add it to the lost and found directory.
1379 // NB Can't put root or lostNFound in lostNFound so
1380 // check if lostNFound exists first
1381 if(dev->lostNFoundDir)
1383 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1391 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1394 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1397 obj->fake = 1; // it is fake so it has no NAND presence...
1398 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1399 obj->unlinkAllowed= 0; // ... or unlink it
1402 obj->st_mode = mode;
1404 obj->chunkId = 0; // Not a valid chunk.
1412 static void yaffs_UnhashObject(yaffs_Object *tn)
1415 yaffs_Device *dev = tn->myDev;
1418 // If it is still linked into the bucket list, free from the list
1419 if(!list_empty(&tn->hashLink))
1421 list_del_init(&tn->hashLink);
1422 bucket = yaffs_HashFunction(tn->objectId);
1423 dev->objectBucket[bucket].count--;
1429 // FreeObject frees up a Object and puts it back on the free list
1430 static void yaffs_FreeObject(yaffs_Object *tn)
1433 yaffs_Device *dev = tn->myDev;
1435 yaffs_UnhashObject(tn);
1437 // Link into the free list.
1438 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1439 dev->freeObjects = tn;
1440 dev->nFreeObjects++;
1446 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1448 // Free the list of allocated Objects
1450 while( dev->allocatedObjectList)
1452 YFREE(dev->allocatedObjectList->objects);
1453 dev->allocatedObjectList = dev->allocatedObjectList->next;
1456 dev->freeObjects = NULL;
1457 dev->nFreeObjects = 0;
1460 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1464 dev->allocatedObjectList = NULL;
1465 dev->freeObjects = NULL;
1466 dev->nFreeObjects = 0;
1468 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1470 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1471 dev->objectBucket[i].count = 0;
1481 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1486 int lowest = 999999;
1489 // First let's see if we can find one that's empty.
1491 for(i = 0; i < 10 && lowest > 0; i++)
1494 x %= YAFFS_NOBJECT_BUCKETS;
1495 if(dev->objectBucket[x].count < lowest)
1497 lowest = dev->objectBucket[x].count;
1503 // If we didn't find an empty list, then try
1504 // looking a bit further for a short one
1506 for(i = 0; i < 10 && lowest > 3; i++)
1509 x %= YAFFS_NOBJECT_BUCKETS;
1510 if(dev->objectBucket[x].count < lowest)
1512 lowest = dev->objectBucket[x].count;
1521 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1523 int bucket = yaffs_FindNiceObjectBucket(dev);
1525 // Now find an object value that has not already been taken
1526 // by scanning the list.
1529 struct list_head *i;
1531 __u32 n = (__u32)bucket;
1533 //yaffs_CheckObjectHashSanity();
1538 n += YAFFS_NOBJECT_BUCKETS;
1539 if(1 ||dev->objectBucket[bucket].count > 0)
1541 list_for_each(i,&dev->objectBucket[bucket].list)
1543 // If there is already one in the list
1544 if(list_entry(i, yaffs_Object,hashLink)->objectId == n)
1552 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1557 void yaffs_HashObject(yaffs_Object *in)
1559 int bucket = yaffs_HashFunction(in->objectId);
1560 yaffs_Device *dev = in->myDev;
1562 if(!list_empty(&in->hashLink))
1568 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1569 dev->objectBucket[bucket].count++;
1573 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1575 int bucket = yaffs_HashFunction(number);
1576 struct list_head *i;
1579 list_for_each(i,&dev->objectBucket[bucket].list)
1581 // Look if it is in the list
1582 in = list_entry(i, yaffs_Object,hashLink);
1583 if(in->objectId == number)
1594 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1597 yaffs_Object *theObject;
1601 number = yaffs_CreateNewObjectNumber(dev);
1604 theObject = yaffs_AllocateEmptyObject(dev);
1608 theObject->fake = 0;
1609 theObject->renameAllowed = 1;
1610 theObject->unlinkAllowed = 1;
1611 theObject->objectId = number;
1612 yaffs_HashObject(theObject);
1613 theObject->variantType = type;
1614 #ifdef CONFIG_YAFFS_WINCE
1615 yfsd_WinFileTimeNow(theObject->win_atime);
1616 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1617 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1620 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1624 case YAFFS_OBJECT_TYPE_FILE:
1625 theObject->variant.fileVariant.fileSize = 0;
1626 theObject->variant.fileVariant.scannedFileSize = 0;
1627 theObject->variant.fileVariant.topLevel = 0;
1628 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1630 case YAFFS_OBJECT_TYPE_DIRECTORY:
1631 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1633 case YAFFS_OBJECT_TYPE_SYMLINK:
1634 // No action required
1636 case YAFFS_OBJECT_TYPE_HARDLINK:
1637 // No action required
1639 case YAFFS_OBJECT_TYPE_SPECIAL:
1640 // No action required
1642 case YAFFS_OBJECT_TYPE_UNKNOWN:
1643 // todo this should not happen
1651 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1653 yaffs_Object *theObject = NULL;
1657 theObject = yaffs_FindObjectByNumber(dev,number);
1662 theObject = yaffs_CreateNewObject(dev,number,type);
1669 char *yaffs_CloneString(const char *str)
1671 char *newStr = NULL;
1675 newStr = YMALLOC(strlen(str) + 1);
1684 // Mknod (create) a new object.
1685 // equivalentObject only has meaning for a hard link;
1686 // aliasString only has meaning for a sumlink.
1687 // rdev only has meaning for devices (a subset of special objects)
1688 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1689 yaffs_Object *parent,
1694 yaffs_Object *equivalentObject,
1695 const char *aliasString,
1700 yaffs_Device *dev = parent->myDev;
1702 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1703 if(yaffs_FindObjectByName(parent,name))
1708 in = yaffs_CreateNewObject(dev,-1,type);
1714 in->variantType = type;
1718 #ifdef CONFIG_YAFFS_WINCE
1719 yfsd_WinFileTimeNow(in->win_atime);
1720 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1721 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[0];
1724 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1729 in->nDataChunks = 0;
1731 yaffs_SetObjectName(in,name);
1734 yaffs_AddObjectToDirectory(parent,in);
1736 in->myDev = parent->myDev;
1741 case YAFFS_OBJECT_TYPE_SYMLINK:
1742 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1744 case YAFFS_OBJECT_TYPE_HARDLINK:
1745 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1746 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1747 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1749 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1750 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1751 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1752 case YAFFS_OBJECT_TYPE_UNKNOWN:
1756 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1757 yaffs_UpdateObjectHeader(in,name,0) < 0)
1759 // Could not create the object header, fail the creation
1760 yaffs_AbortHalfCreatedObject(in);
1769 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1771 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1774 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1776 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1779 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1781 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1784 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1786 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1789 // NB yaffs_Link returns the object id of the equivalent object.
1790 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1792 // Get the real object in case we were fed a hard link as an equivalent object
1793 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1795 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1797 return equivalentObject;
1807 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1813 newDir = obj->parent; // use the old directory
1816 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1818 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1819 // duplicate names are allowed.
1820 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1823 !yaffs_FindObjectByName(newDir,newName)) &&
1824 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1826 yaffs_SetObjectName(obj,newName);
1829 yaffs_AddObjectToDirectory(newDir,obj);
1831 if(unlinkOp) obj->unlinked = 1;
1834 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1845 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1850 #ifdef YAFFS_CASE_INSENSITIVE
1851 // Special case for WinCE.
1852 // While look-up is case insensitive, the name isn't.
1853 // THerefore we might want to change x.txt to X.txt
1854 if(oldDir == newDir && _stricmp(oldName,newName) == 0)
1860 obj = yaffs_FindObjectByName(oldDir,oldName);
1861 if(obj && obj->renameAllowed)
1863 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1870 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1872 // Scan the buckets and check that the lists
1873 // have as many members as the count says there are
1876 struct list_head *j;
1879 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1883 list_for_each(j,&dev->objectBucket[bucket].list)
1888 if(countEm != dev->objectBucket[bucket].count)
1890 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1899 void yaffs_ObjectTest(yaffs_Device *dev)
1901 yaffs_Object *in[1000];
1903 yaffs_Object *inold[1000];
1907 memset(in,0,1000*sizeof(yaffs_Object *));
1908 memset(inold,0,1000*sizeof(yaffs_Object *));
1910 yaffs_CheckObjectHashSanity(dev);
1912 for(j = 0; j < 10; j++)
1916 for(i = 0; i < 1000; i++)
1918 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1921 YINFO("No more inodes");
1925 inNo[i] = in[i]->objectId;
1929 for(i = 0; i < 1000; i++)
1931 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1933 //T(("Differnce in look up test\n"));
1937 // T(("Look up ok\n"));
1941 yaffs_CheckObjectHashSanity(dev);
1943 for(i = 0; i < 1000; i+=3)
1945 yaffs_FreeObject(in[i]);
1950 yaffs_CheckObjectHashSanity(dev);
1957 /////////////////////////// Block Management and Page Allocation ///////////////////
1960 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1962 dev->allocationBlock = -1; // force it to get a new one
1963 //Todo we're assuming the malloc will pass.
1964 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1965 // Set up dynamic blockinfo stuff.
1966 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
1967 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1968 if(dev->blockInfo && dev->chunkBits)
1970 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1971 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
1979 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1981 YFREE(dev->blockInfo);
1982 dev->blockInfo = NULL;
1983 YFREE(dev->chunkBits);
1984 dev->chunkBits = NULL;
1987 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1988 // for garbage collection.
1990 static int yaffs_FindDirtiestBlock(yaffs_Device *dev)
1993 int b = dev->currentDirtyChecker;
1997 int pagesInUse = dev->nChunksPerBlock;
1998 yaffs_BlockInfo *bi;
2000 for(i = dev->startBlock; i <= dev->endBlock && pagesInUse > 2 ; i++)
2003 if ( b < dev->startBlock || b > dev->endBlock)
2005 b = dev->startBlock;
2008 if(b < dev->startBlock || b > dev->endBlock)
2010 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2014 bi = yaffs_GetBlockInfo(dev,b);
2016 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2017 (bi->pagesInUse - bi->softDeletions )< pagesInUse)
2020 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2024 dev->currentDirtyChecker = b;
2030 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2032 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2036 // If the block is still healthy erase it and mark as clean.
2037 // If the block has had a data failure, then retire it.
2038 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2040 if(!bi->needsRetiring)
2042 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2045 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2052 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2053 dev->nErasedBlocks++;
2055 bi->softDeletions = 0;
2056 yaffs_ClearChunkBits(dev,blockNo);
2058 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2062 yaffs_RetireBlock(dev,blockNo);
2063 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2068 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2072 yaffs_BlockInfo *bi;
2074 if(dev->nErasedBlocks < 1)
2076 // Hoosterman we've got a problem.
2077 // Can't get space to gc
2078 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during gc" TENDSTR)));
2083 // Find an empty block.
2085 for(i = dev->startBlock; i <= dev->endBlock; i++)
2087 dev->allocationBlockFinder++;
2088 if(dev->allocationBlockFinder <dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2090 dev->allocationBlockFinder = dev->startBlock;
2093 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2095 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2097 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2098 dev->nErasedBlocks--;
2099 return dev->allocationBlockFinder;
2108 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2111 yaffs_BlockInfo *bi;
2113 if(dev->allocationBlock < 0)
2115 // Get next block to allocate off
2116 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2117 dev->allocationPage = 0;
2120 if(!useReserve && dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
2122 // Not enough space to allocate unless we're allowed to use the reserve.
2126 // Next page please....
2127 if(dev->allocationBlock >= 0)
2129 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2131 retVal = (dev->allocationBlock * YAFFS_CHUNKS_PER_BLOCK) +
2132 dev->allocationPage;
2134 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2136 dev->allocationPage++;
2140 // If the block is full set the state to full
2141 if(dev->allocationPage >= YAFFS_CHUNKS_PER_BLOCK)
2143 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2144 dev->allocationBlock = -1;
2151 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2156 // To determine if we have enough space we just look at the
2157 // number of erased blocks.
2158 // The cache is allowed to use reserved blocks.
2160 int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2162 return (dev->nErasedBlocks >= YAFFS_RESERVED_BLOCKS);
2166 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2176 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
2178 // yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2180 yaffs_Object *object;
2182 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2184 for(chunkInBlock = 0,oldChunk = block * YAFFS_CHUNKS_PER_BLOCK;
2185 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2186 chunkInBlock++, oldChunk++ )
2188 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2191 // This page is in use and might need to be copied off
2195 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2197 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
2199 yaffs_GetTagsFromSpare(dev,&spare,&tags);
2201 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2203 if(object && object->deleted && tags.chunkId != 0)
2205 // Data chunk in a deleted file, throw it away
2206 // It's a deleted data chunk,
2207 // No need to copy this, just forget about it and fix up the
2210 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2211 object->nDataChunks--;
2213 if(object->nDataChunks <= 0)
2215 // Time to delete the file too
2216 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2217 object->variant.fileVariant.top = NULL;
2218 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2219 yaffs_DoGenericObjectDeletion(object);
2223 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2225 // Deleted object header with no data chunks.
2226 // Can be discarded and the file deleted.
2227 object->chunkId = 0;
2228 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2229 object->variant.fileVariant.top = NULL;
2230 yaffs_DoGenericObjectDeletion(object);
2235 // It's either a data chunk in a live file or
2236 // an ObjectHeader, so we're interested in it.
2237 // NB Need to keep the ObjectHeaders of deleted files
2238 // until the whole file has been deleted off
2239 tags.serialNumber++;
2240 yaffs_LoadTagsIntoSpare(&spare,&tags);
2244 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
2251 // Ok, now fix up the Tnodes etc.
2253 if(tags.chunkId == 0)
2256 object->chunkId = newChunk;
2260 // It's a data chunk
2261 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2265 yaffs_DeleteChunk(dev,oldChunk,markNAND);
2274 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2276 // find a file to delete
2277 struct list_head *i;
2281 //Scan the unlinked files looking for one to delete
2282 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2284 l = list_entry(i, yaffs_Object,siblings);
2294 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2296 // This does background deletion on unlinked files.. only deleted ones.
2297 // If we don't have a file we're working on then find one
2298 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2300 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2303 // OK, we're working on a file...
2304 if(dev->unlinkedDeletion)
2306 yaffs_Object *obj = dev->unlinkedDeletion;
2308 int limit; // Number of chunks to delete in a file.
2309 // NB this can be exceeded, but not by much.
2313 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2315 if(obj->nDataChunks == 0)
2317 // Done all the deleting of data chunks.
2318 // Now dump the header and clean up
2319 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2320 obj->variant.fileVariant.top = NULL;
2321 yaffs_DoGenericObjectDeletion(obj);
2322 dev->nDeletedFiles--;
2323 dev->nUnlinkedFiles--;
2324 dev->nBackgroundDeletions++;
2325 dev->unlinkedDeletion = NULL;
2332 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2336 //yaffs_DoUnlinkedFileDeletion(dev);
2338 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2340 dev->garbageCollectionRequired = 1;
2343 if(dev->garbageCollectionRequired)
2345 dev->garbageCollections++;
2346 dev->garbageCollectionRequired = 0;
2347 if(dev->blockSelectedForGC >= 0)
2349 block = dev->blockSelectedForGC;
2353 block = yaffs_FindDirtiestBlock(dev);
2358 return yaffs_GarbageCollectBlock(dev,block);
2370 //////////////////////////// TAGS ///////////////////////////////////////
2372 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2374 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2376 yaffs_CalcTagsECC(tagsPtr);
2378 sparePtr->tagByte0 = tu->asBytes[0];
2379 sparePtr->tagByte1 = tu->asBytes[1];
2380 sparePtr->tagByte2 = tu->asBytes[2];
2381 sparePtr->tagByte3 = tu->asBytes[3];
2382 sparePtr->tagByte4 = tu->asBytes[4];
2383 sparePtr->tagByte5 = tu->asBytes[5];
2384 sparePtr->tagByte6 = tu->asBytes[6];
2385 sparePtr->tagByte7 = tu->asBytes[7];
2388 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2390 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2393 tu->asBytes[0]= sparePtr->tagByte0;
2394 tu->asBytes[1]= sparePtr->tagByte1;
2395 tu->asBytes[2]= sparePtr->tagByte2;
2396 tu->asBytes[3]= sparePtr->tagByte3;
2397 tu->asBytes[4]= sparePtr->tagByte4;
2398 tu->asBytes[5]= sparePtr->tagByte5;
2399 tu->asBytes[6]= sparePtr->tagByte6;
2400 tu->asBytes[7]= sparePtr->tagByte7;
2402 result = yaffs_CheckECCOnTags(tagsPtr);
2405 dev->tagsEccFixed++;
2409 dev->tagsEccUnfixed++;
2413 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2415 memset(spare,0xFF,sizeof(yaffs_Spare));
2418 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2423 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2425 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2426 yaffs_GetTagsFromSpare(dev,&spare,tags);
2439 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2441 // NB There must be tags, data is optional
2442 // If there is data, then an ECC is calculated on it.
2451 yaffs_SpareInitialise(&spare);
2453 if(!dev->useNANDECC && buffer)
2455 yaffs_CalcECC(buffer,&spare);
2458 yaffs_LoadTagsIntoSpare(&spare,tags);
2460 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2466 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2468 // NB There must be tags, data is optional
2469 // If there is data, then an ECC is calculated on it.
2478 yaffs_SpareInitialise(&spare);
2480 if(!dev->useNANDECC && buffer)
2482 yaffs_CalcECC(buffer,&spare);
2485 yaffs_LoadTagsIntoSpare(&spare,tags);
2487 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2491 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2493 return ( tags->chunkId == chunkInObject &&
2494 tags->objectId == objectId &&
2495 !chunkDeleted) ? 1 : 0;
2501 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2503 //Get the Tnode, then get the level 0 offset chunk offset
2506 yaffs_Tags localTags;
2511 yaffs_Device *dev = in->myDev;
2516 // Passed a NULL, so use our own tags space
2520 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2524 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2526 // Now we need to do the shifting etc and search for it
2527 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2529 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2530 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2541 return found ? theChunk : -1;
2544 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2546 //Get the Tnode, then get the level 0 offset chunk offset
2549 yaffs_Tags localTags;
2552 yaffs_Device *dev = in->myDev;
2557 // Passed a NULL, so use our own tags space
2561 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2566 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2568 // Now we need to do the shifting etc and search for it
2569 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2571 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2572 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2583 // Delete the entry in the filestructure
2586 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2591 //T(("No level 0 found for %d\n", chunkInInode));
2596 //T(("Could not find %d to delete\n",chunkInInode));
2598 return found ? theChunk : -1;
2602 #ifdef YAFFS_PARANOID
2604 static int yaffs_CheckFileSanity(yaffs_Object *in)
2612 yaffs_Tags localTags;
2613 yaffs_Tags *tags = &localTags;
2618 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2620 //T(("Object not a file\n"));
2624 objId = in->objectId;
2625 fSize = in->variant.fileVariant.fileSize;
2626 nChunks = (fSize + YAFFS_BYTES_PER_CHUNK -1)/YAFFS_BYTES_PER_CHUNK;
2628 for(chunk = 1; chunk <= nChunks; chunk++)
2630 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2635 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2638 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2639 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2646 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2647 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2656 //T(("No level 0 found for %d\n", chunk));
2660 return failed ? YAFFS_FAIL : YAFFS_OK;
2665 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2668 yaffs_Device *dev = in->myDev;
2670 yaffs_Tags existingTags;
2672 unsigned existingSerial, newSerial;
2674 int newChunkDeleted;
2677 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2683 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2687 // If we're scanning then we need to test for duplicates
2688 // NB This does not need to be efficient since it should only ever
2689 // happen when the power fails during a write, then only one
2690 // chunk should ever be affected.
2693 if(existingChunk != 0)
2695 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2696 // thus we have to do a FindChunkInFile to get the real chunk id.
2698 // We have a duplicate now we need to decide which one to use
2699 // To do this we get both sets of tags and compare serial numbers.
2700 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2704 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2706 if(existingChunk <=0)
2708 //Hoosterman - how did this happen?
2710 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
2715 // NB The deleted flags should be false, otherwise the chunks will
2716 // not be loaded during a scan
2718 newSerial = newTags.serialNumber;
2719 existingSerial = existingTags.serialNumber;
2721 if( existingChunk <= 0 ||
2722 ((existingSerial+1) & 3) == newSerial)
2725 // Delete the old one and drop through to update the tnode
2726 yaffs_DeleteChunk(dev,existingChunk,1);
2731 // Delete the new one and return early so that the tnode isn't changed
2732 yaffs_DeleteChunk(dev,chunkInNAND,1);
2739 if(existingChunk == 0)
2744 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2751 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2753 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2755 if(chunkInNAND >= 0)
2757 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2767 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND)
2772 yaffs_BlockInfo *bi;
2774 if(chunkId <= 0) return;
2777 block = chunkId / YAFFS_CHUNKS_PER_BLOCK;
2778 page = chunkId % YAFFS_CHUNKS_PER_BLOCK;
2782 yaffs_SpareInitialise(&spare);
2784 spare.pageStatus = 0; // To mark it as deleted.
2787 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2788 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2792 dev->nUnmarkedDeletions++;
2795 bi = yaffs_GetBlockInfo(dev,block);
2798 // Pull out of the management area.
2799 // If the whole block became dirty, this will kick off an erasure.
2800 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2801 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2805 yaffs_ClearChunkBit(dev,block,page);
2808 if(bi->pagesInUse == 0 &&
2809 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2811 yaffs_BlockBecameDirty(dev,block);
2817 // T(("Bad news deleting chunk %d\n",chunkId));
2825 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2827 // Find old chunk Need to do this to get serial number
2828 // Write new one and patch into tree.
2829 // Invalidate old tags.
2832 yaffs_Tags prevTags;
2837 yaffs_Device *dev = in->myDev;
2839 yaffs_CheckGarbageCollection(dev);
2841 // Get the previous chunk at this location in the file if it exists
2842 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2845 newTags.chunkId = chunkInInode;
2846 newTags.objectId = in->objectId;
2847 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2848 newTags.byteCount = nBytes;
2849 newTags.unusedStuff = 0xFFFFFFFF;
2851 yaffs_CalcTagsECC(&newTags);
2853 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2856 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2859 if(prevChunkId >= 0)
2861 yaffs_DeleteChunk(dev,prevChunkId,1);
2865 yaffs_CheckFileSanity(in);
2876 // UpdateObjectHeader updates the header on NAND for an object.
2877 // If name is not NULL, then that new name is used.
2879 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2882 yaffs_Device *dev = in->myDev;
2888 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2889 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2891 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2892 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2895 if(!in->fake || force)
2898 yaffs_CheckGarbageCollection(dev);
2900 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2902 prevChunkId = in->chunkId;
2904 if(prevChunkId >= 0)
2906 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2910 oh->type = in->variantType;
2912 oh->st_mode = in->st_mode;
2914 #ifdef CONFIG_YAFFS_WINCE
2915 oh->win_atime[0] = in->win_atime[0];
2916 oh->win_ctime[0] = in->win_ctime[0];
2917 oh->win_mtime[0] = in->win_mtime[0];
2918 oh->win_atime[1] = in->win_atime[1];
2919 oh->win_ctime[1] = in->win_ctime[1];
2920 oh->win_mtime[1] = in->win_mtime[1];
2922 oh->st_uid = in->st_uid;
2923 oh->st_gid = in->st_gid;
2924 oh->st_atime = in->st_atime;
2925 oh->st_mtime = in->st_mtime;
2926 oh->st_ctime = in->st_ctime;
2927 oh->st_rdev = in->st_rdev;
2931 oh->parentObjectId = in->parent->objectId;
2935 oh->parentObjectId = 0;
2938 //oh->sum = in->sum;
2941 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2942 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
2944 else if(prevChunkId)
2946 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
2950 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2953 switch(in->variantType)
2955 case YAFFS_OBJECT_TYPE_UNKNOWN:
2956 // Should not happen
2958 case YAFFS_OBJECT_TYPE_FILE:
2959 oh->fileSize = in->variant.fileVariant.fileSize;
2961 case YAFFS_OBJECT_TYPE_HARDLINK:
2962 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
2964 case YAFFS_OBJECT_TYPE_SPECIAL:
2967 case YAFFS_OBJECT_TYPE_DIRECTORY:
2970 case YAFFS_OBJECT_TYPE_SYMLINK:
2971 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
2972 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2978 newTags.chunkId = 0;
2979 newTags.objectId = in->objectId;
2980 newTags.serialNumber = in->serial;
2981 newTags.byteCount = 0xFFFFFFFF;
2982 newTags.unusedStuff = 0xFFFFFFFF;
2984 yaffs_CalcTagsECC(&newTags);
2987 // Create new chunk in NAND
2988 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags, (prevChunkId >= 0) ? 1 : 0 );
2993 in->chunkId = newChunkId;
2995 if(prevChunkId >= 0)
2997 yaffs_DeleteChunk(dev,prevChunkId,1);
3010 /////////////////////// Short Operations Cache ////////////////////////////////
3011 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3012 // reads might be short sequential reads, and a lot of writes may be short
3013 // sequential writes. eg. scanning/writing a jpeg file.
3014 // In these cases, a short read/write cache can provide a huge perfomance benefit
3015 // with dumb-as-a-rock code.
3016 // There are a limited number (~10) of cache chunks per device so that we don't
3017 // need a very intelligent search.
3023 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3025 yaffs_Device *dev = obj->myDev;
3028 yaffs_ChunkCache *cache;
3031 int nCaches = obj->myDev->nShortOpCaches;
3038 // Find the dirty cache for this object with the lowest chunk id.
3039 for(i = 0; i < nCaches; i++)
3041 if(dev->srCache[i].object == obj &&
3042 dev->srCache[i].dirty)
3044 if(!cache || dev->srCache[i].chunkId < lowest)
3046 cache = &dev->srCache[i];
3047 lowest = cache->chunkId;
3057 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3059 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3061 nBytes= YAFFS_BYTES_PER_CHUNK;
3064 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3072 } while(cache && chunkWritten > 0);
3076 //Hoosterman, disk full while writing cache out.
3077 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3085 // Grab us a chunk for use.
3086 // First look for an empty one.
3087 // Then look for the least recently used non-dirty one.
3088 // Then look for the least recently used dirty one...., flush and look again.
3089 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3095 if(dev->nShortOpCaches > 0)
3097 for(i = 0; i < dev->nShortOpCaches; i++)
3099 if(!dev->srCache[i].object)
3101 //T(("Grabbing empty %d\n",i));
3103 return &dev->srCache[i];
3108 usage = 0; // just to stop the compiler grizzling
3110 for(i = 0; i < dev->nShortOpCaches; i++)
3112 if(!dev->srCache[i].dirty &&
3113 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3116 usage = dev->srCache[i].lastUse;
3121 //T(("Grabbing non-empty %d\n",theOne));
3122 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3132 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3134 yaffs_ChunkCache *cache;
3135 yaffs_Object *theObj;
3139 if(dev->nShortOpCaches > 0)
3141 // Try find a non-dirty one...
3143 cache = yaffs_GrabChunkCacheWorker(dev);
3147 // They were all dirty, find the last recently used object and flush
3148 // its cache, then find again.
3149 // NB what's here is not very accurate, we actually flush the object
3150 // the last recently used page.
3152 theObj = dev->srCache[0].object;
3153 usage = dev->srCache[0].lastUse;
3155 for(i = 1; i < dev->nShortOpCaches; i++)
3157 if( dev->srCache[i].object &&
3158 dev->srCache[i].lastUse < usage)
3160 usage = dev->srCache[i].lastUse;
3161 theObj = dev->srCache[i].object;
3165 yaffs_FlushFilesChunkCache(theObj);
3168 cache = yaffs_GrabChunkCacheWorker(dev);
3179 // Find a cached chunk
3180 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3182 yaffs_Device *dev = obj->myDev;
3184 if(dev->nShortOpCaches > 0)
3186 for(i = 0; i < dev->nShortOpCaches; i++)
3188 if(dev->srCache[i].object == obj &&
3189 dev->srCache[i].chunkId == chunkId)
3193 return &dev->srCache[i];
3200 // Mark the chunk for the least recently used algorithym
3201 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3204 if(dev->nShortOpCaches > 0)
3206 if( dev->srLastUse < 0 ||
3207 dev->srLastUse > 100000000)
3209 // Reset the cache usages
3211 for(i = 1; i < dev->nShortOpCaches; i++)
3213 dev->srCache[i].lastUse = 0;
3220 cache->lastUse = dev->srLastUse;
3229 // Invalidate a single cache page.
3230 // Do this when a whole page gets written,
3231 // ie the short cache for this page is no longer valid.
3232 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3234 if(object->myDev->nShortOpCaches > 0)
3236 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3240 cache->object = NULL;
3246 // Invalidate all the cache pages associated with this object
3247 // Do this whenever ther file is deleted or resized.
3248 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3251 yaffs_Device *dev = in->myDev;
3253 if(dev->nShortOpCaches > 0)
3255 // Now invalidate it.
3256 for(i = 0; i < dev->nShortOpCaches; i++)
3258 if(dev->srCache[i].object == in)
3260 dev->srCache[i].object = NULL;
3270 ///////////////////////// File read/write ///////////////////////////////
3271 // Read and write have very similar structures.
3272 // In general the read/write has three parts to it
3273 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3274 // * Some complete chunks
3275 // * An incomplete chunk to end off with
3277 // Curve-balls: the first chunk might also be the last chunk.
3279 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3295 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
3296 start = offset % YAFFS_BYTES_PER_CHUNK;
3298 // OK now check for the curveball where the start and end are in
3300 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3306 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3309 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3311 // An incomplete start or end chunk (or maybe both start and end chunk)
3312 if(dev->nShortOpCaches > 0)
3314 yaffs_ChunkCache *cache;
3315 // If we can't find the data in the cache, then load it up.
3316 cache = yaffs_FindChunkCache(in,chunk);
3319 cache = yaffs_GrabChunkCache(in->myDev);
3321 cache->chunkId = chunk;
3323 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3327 yaffs_UseChunkCache(dev,cache,0);
3329 memcpy(buffer,&cache->data[start],nToCopy);
3333 // Read into the local buffer then copy...
3334 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3335 memcpy(buffer,&dev->localBuffer[start],nToCopy);
3341 #ifdef CONFIG_YAFFS_WINCE
3343 // Under WinCE can't do direct transfer. Need to use a local buffer.
3344 // This is because we otherwise screw up WinCE's memory mapper
3345 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3346 memcpy(buffer,dev->localBuffer,YAFFS_BYTES_PER_CHUNK);
3348 // A full chunk. Read directly into the supplied buffer.
3349 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3365 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3374 int startOfWrite = offset;
3375 int chunkWritten = 0;
3383 while(n > 0 && chunkWritten >= 0)
3385 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
3386 start = offset % YAFFS_BYTES_PER_CHUNK;
3389 // OK now check for the curveball where the start and end are in
3392 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3396 // Now folks, to calculate how many bytes to write back....
3397 // If we're overwriting and not writing to then end of file then
3398 // we need to write back as much as was there before.
3400 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
3402 if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
3404 nBytesRead = YAFFS_BYTES_PER_CHUNK;
3407 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3412 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3413 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3416 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3418 // An incomplete start or end chunk (or maybe both start and end chunk)
3419 if(dev->nShortOpCaches > 0)
3421 yaffs_ChunkCache *cache;
3422 // If we can't find the data in the cache, then load it up.
3423 cache = yaffs_FindChunkCache(in,chunk);
3424 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3426 cache = yaffs_GrabChunkCache(in->myDev);
3428 cache->chunkId = chunk;
3430 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3435 yaffs_UseChunkCache(dev,cache,1);
3436 memcpy(&cache->data[start],buffer,nToCopy);
3437 cache->nBytes = nToWriteBack;
3441 chunkWritten = -1; // fail the write
3446 // An incomplete start or end chunk (or maybe both start and end chunk)
3447 // Read into the local buffer then copy, then copy over and write back.
3449 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3451 memcpy(&dev->localBuffer[start],buffer,nToCopy);
3453 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,nToWriteBack,0);
3455 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3462 #ifdef CONFIG_YAFFS_WINCE
3463 // Under WinCE can't do direct transfer. Need to use a local buffer.
3464 // This is because we otherwise screw up WinCE's memory mapper
3465 memcpy(dev->localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3466 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3468 // A full chunk. Write directly from the supplied buffer.
3469 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3471 // Since we've overwritten the cached data, we better invalidate it.
3472 yaffs_InvalidateChunkCache(in,chunk);
3473 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3476 if(chunkWritten >= 0)
3486 // Update file object
3488 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3490 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3499 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3503 int oldFileSize = in->variant.fileVariant.fileSize;
3504 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3506 yaffs_Device *dev = in->myDev;
3509 yaffs_FlushFilesChunkCache(in);
3510 yaffs_InvalidateWholeChunkCache(in);
3512 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3514 return yaffs_GetFileSize(in);
3517 if(newSize < oldFileSize)
3520 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3522 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3523 YAFFS_BYTES_PER_CHUNK;
3525 // Delete backwards so that we don't end up with holes if
3526 // power is lost part-way through the operation.
3527 for(i = lastDel; i >= startDel; i--)
3529 // NB this could be optimised somewhat,
3530 // eg. could retrieve the tags and write them without
3531 // using yaffs_DeleteChunk
3533 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3534 if(chunkId <= 0 || chunkId >= (dev->endBlock * 32))
3536 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3541 yaffs_DeleteChunk(dev,chunkId,1);
3546 if(sizeOfPartialChunk != 0)
3548 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3550 // Got to read and rewrite the last chunk with its new size.
3551 yaffs_ReadChunkDataFromObject(in,lastChunk,dev->localBuffer);
3553 yaffs_WriteChunkDataToObject(in,lastChunk,dev->localBuffer,sizeOfPartialChunk,1);
3557 in->variant.fileVariant.fileSize = newSize;
3559 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3571 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3573 obj = yaffs_GetEquivalentObject(obj);
3575 switch(obj->variantType)
3577 case YAFFS_OBJECT_TYPE_FILE:
3578 return obj->variant.fileVariant.fileSize;
3579 case YAFFS_OBJECT_TYPE_SYMLINK:
3580 return strlen(obj->variant.symLinkVariant.alias);
3588 // yaffs_FlushFile() updates the file's
3591 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
3596 //T(("flushing object header\n"));
3598 yaffs_FlushFilesChunkCache(in);
3601 #ifdef CONFIG_YAFFS_WINCE
3602 yfsd_WinFileTimeNow(in->win_mtime);
3604 in->st_mtime = CURRENT_TIME;
3608 retVal = yaffs_UpdateObjectHeader(in,NULL,0);
3620 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3623 // First off, invalidate the file's data in the cache, without flushing.
3624 yaffs_InvalidateWholeChunkCache(in);
3626 yaffs_RemoveObjectFromDirectory(in);
3627 yaffs_DeleteChunk(in->myDev,in->chunkId,1);
3631 in->myInode->u.generic_ip = NULL;
3635 yaffs_FreeObject(in);
3640 // yaffs_DeleteFile deletes the whole file data
3641 // and the inode associated with the file.
3642 // It does not delete the links associated with the file.
3643 static int yaffs_UnlinkFile(yaffs_Object *in)
3646 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3648 // Delete the file data & tnodes
3650 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3653 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3655 return yaffs_DoGenericObjectDeletion(in);
3658 int immediateDeletion=0;
3659 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3660 if(1 || // Ignore the result of the change name. This will only fail
3661 // if the disk was completely full (an error condition)
3662 // We ignore the error so we can delete files to recover the disk
3666 //in->myDev->nUnlinkedFiles++;
3667 //in->renameAllowed = 0;
3671 immediateDeletion = 1;
3677 immediateDeletion = 1;
3682 if(immediateDeletion)
3684 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3686 in->myDev->nDeletedFiles++;
3687 yaffs_SoftDeleteFile(in);
3697 int yaffs_DeleteFile(yaffs_Object *in)
3699 int retVal = YAFFS_OK;
3701 if(in->nDataChunks > 0)
3703 // Use soft deletion
3706 retVal = yaffs_UnlinkFile(in);
3708 if(retVal == YAFFS_OK &&
3713 in->myDev->nDeletedFiles++;
3714 yaffs_SoftDeleteFile(in);
3716 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3720 // The file has no data chunks so we toss it immediately
3721 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3722 in->variant.fileVariant.top = NULL;
3723 yaffs_DoGenericObjectDeletion(in);
3729 static int yaffs_DeleteDirectory(yaffs_Object *in)
3731 //First check that the directory is empty.
3732 if(list_empty(&in->variant.directoryVariant.children))
3734 return yaffs_DoGenericObjectDeletion(in);
3741 static int yaffs_DeleteSymLink(yaffs_Object *in)
3743 YFREE(in->variant.symLinkVariant.alias);
3745 return yaffs_DoGenericObjectDeletion(in);
3748 static int yaffs_DeleteHardLink(yaffs_Object *in)
3750 // remove this hardlink from the list assocaited with the equivalent
3752 list_del(&in->hardLinks);
3753 return yaffs_DoGenericObjectDeletion(in);
3757 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj)
3759 switch(obj->variantType)
3761 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
3762 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
3763 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
3764 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
3765 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
3766 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
3771 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3775 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3777 return yaffs_DeleteHardLink(obj);
3779 else if(!list_empty(&obj->hardLinks))
3781 // Curve ball: We're unlinking an object that has a hardlink.
3783 // This problem arises because we are not strictly following
3784 // The Linux link/inode model.
3786 // We can't really delete the object.
3787 // Instead, we do the following:
3788 // - Select a hardlink.
3789 // - Unhook it from the hard links
3790 // - Unhook it from its parent directory (so that the rename can work)
3791 // - Rename the object to the hardlink's name.
3792 // - Delete the hardlink
3797 char name[YAFFS_MAX_NAME_LENGTH+1];
3799 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3801 list_del_init(&hl->hardLinks);
3802 list_del_init(&hl->siblings);
3804 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3806 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3808 if(retVal == YAFFS_OK)
3810 retVal = yaffs_DoGenericObjectDeletion(hl);
3817 switch(obj->variantType)
3819 case YAFFS_OBJECT_TYPE_FILE:
3820 return yaffs_UnlinkFile(obj);
3822 case YAFFS_OBJECT_TYPE_DIRECTORY:
3823 return yaffs_DeleteDirectory(obj);
3825 case YAFFS_OBJECT_TYPE_SYMLINK:
3826 return yaffs_DeleteSymLink(obj);
3828 case YAFFS_OBJECT_TYPE_HARDLINK:
3829 case YAFFS_OBJECT_TYPE_UNKNOWN:
3836 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3840 obj = yaffs_FindObjectByName(dir,name);
3842 if(obj && obj->unlinkAllowed)
3844 return yaffs_UnlinkWorker(obj);
3851 //////////////// Initialisation Scanning /////////////////
3855 // For now we use the SmartMedia check.
3856 // We look at the blockStatus byte in the first two chunks
3857 // These must be 0xFF to pass as OK.
3858 // todo: this function needs to be modifyable foir different NAND types
3859 // and different chunk sizes. Suggest make this into a per-device configurable
3861 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3865 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK,NULL,&spare,1);
3867 if(yaffs_CountBits(spare.blockStatus) < 7)
3872 if(spare.blockStatus != 0xFF)
3877 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK + 1,NULL,&spare,1);
3880 if(yaffs_CountBits(spare.blockStatus) < 7)
3885 if(spare.blockStatus != 0xFF)
3895 static int yaffs_Scan(yaffs_Device *dev)
3903 yaffs_BlockState state;
3904 yaffs_Object *hardList = NULL;
3906 yaffs_BlockInfo *bi;
3909 yaffs_ObjectHeader *oh;
3911 yaffs_Object *parent;
3913 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
3916 // Scan all the blocks...
3918 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
3921 bi = yaffs_GetBlockInfo(dev,blk);
3922 yaffs_ClearChunkBits(dev,blk);
3924 bi->softDeletions = 0;
3925 state = YAFFS_BLOCK_STATE_SCANNING;
3928 if(yaffs_IsBlockBad(dev,blk))
3930 state = YAFFS_BLOCK_STATE_DEAD;
3931 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
3934 // Read each chunk in the block.
3936 for(c = 0; c < YAFFS_CHUNKS_PER_BLOCK &&
3937 state == YAFFS_BLOCK_STATE_SCANNING; c++)
3939 // Read the spare area and decide what to do
3940 chunk = blk * YAFFS_CHUNKS_PER_BLOCK + c;
3942 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
3945 // This block looks ok, now what's in this chunk?
3946 yaffs_GetTagsFromSpare(dev,&spare,&tags);
3948 if(yaffs_CountBits(spare.pageStatus) < 6)
3952 dev->nFreeChunks ++;
3953 //T((" %d %d deleted\n",blk,c));
3955 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
3957 // An unassigned chunk in the block
3958 // This means that either the block is empty or
3959 // this is the one being allocated from
3963 // the block is unused
3964 state = YAFFS_BLOCK_STATE_EMPTY;
3965 dev->nErasedBlocks++;
3969 // this is the block being allocated from
3970 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
3971 state = YAFFS_BLOCK_STATE_ALLOCATING;
3972 dev->allocationBlock = blk;
3973 dev->allocationPage = c;
3976 dev->nFreeChunks += (YAFFS_CHUNKS_PER_BLOCK - c);
3978 else if(tags.chunkId > 0)
3982 yaffs_SetChunkBit(dev,blk,c);
3985 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
3986 // PutChunkIntoFIle checks for a clash (two data chunks with
3987 // the same chunkId).
3988 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
3989 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
3990 if(in->variant.fileVariant.scannedFileSize <endpos)
3992 in->variant.fileVariant.scannedFileSize = endpos;
3993 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3994 in->variant.fileVariant.fileSize =
3995 in->variant.fileVariant.scannedFileSize;
3999 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4003 // chunkId == 0, so it is an ObjectHeader.
4004 // Thus, we read in the object header and make the object
4005 yaffs_SetChunkBit(dev,blk,c);
4008 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
4010 oh = (yaffs_ObjectHeader *)chunkData;
4012 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4016 // We have already filled this one. We have a duplicate and need to resolve it.
4018 unsigned existingSerial = in->serial;
4019 unsigned newSerial = tags.serialNumber;
4021 if(((existingSerial+1) & 3) == newSerial)
4023 // Use new one - destroy the exisiting one
4024 yaffs_DeleteChunk(dev,in->chunkId,1);
4029 // Use existing - destroy this one.
4030 yaffs_DeleteChunk(dev,chunk,1);
4035 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4036 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4038 // We only load some info, don't fiddle with directory structure
4040 in->variantType = oh->type;
4042 in->st_mode = oh->st_mode;
4043 #ifdef CONFIG_YAFFS_WINCE
4044 in->win_atime[0] = oh->win_atime[0];
4045 in->win_ctime[0] = oh->win_ctime[0];
4046 in->win_mtime[0] = oh->win_mtime[0];
4047 in->win_atime[1] = oh->win_atime[1];
4048 in->win_ctime[1] = oh->win_ctime[1];
4049 in->win_mtime[1] = oh->win_mtime[1];
4051 in->st_uid = oh->st_uid;
4052 in->st_gid = oh->st_gid;
4053 in->st_atime = oh->st_atime;
4054 in->st_mtime = oh->st_mtime;
4055 in->st_ctime = oh->st_ctime;
4056 in->st_rdev = oh->st_rdev;
4058 in->chunkId = chunk;
4063 // we need to load this info
4066 in->variantType = oh->type;
4068 in->st_mode = oh->st_mode;
4069 #ifdef CONFIG_YAFFS_WINCE
4070 in->win_atime[0] = oh->win_atime[0];
4071 in->win_ctime[0] = oh->win_ctime[0];
4072 in->win_mtime[0] = oh->win_mtime[0];
4073 in->win_atime[1] = oh->win_atime[1];
4074 in->win_ctime[1] = oh->win_ctime[1];
4075 in->win_mtime[1] = oh->win_mtime[1];
4077 in->st_uid = oh->st_uid;
4078 in->st_gid = oh->st_gid;
4079 in->st_atime = oh->st_atime;
4080 in->st_mtime = oh->st_mtime;
4081 in->st_ctime = oh->st_ctime;
4082 in->st_rdev = oh->st_rdev;
4084 in->chunkId = chunk;
4086 yaffs_SetObjectName(in,oh->name);
4089 // directory stuff...
4090 // hook up to parent
4092 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4093 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4095 // Set up as a directory
4096 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4097 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4099 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4101 // Hoosterman, another problem....
4102 // We're trying to use a non-directory as a directory
4104 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan" TENDSTR)));
4108 yaffs_AddObjectToDirectory(parent,in);
4109 if(parent == dev->unlinkedDir)
4111 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4112 dev->nDeletedFiles++;
4115 // Note re hardlinks.
4116 // Since we might scan a hardlink before its equivalent object is scanned
4117 // we put them all in a list.
4118 // After scanning is complete, we should have all the objects, so we run through this
4119 // list and fix up all the chains.
4121 switch(in->variantType)
4123 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4125 case YAFFS_OBJECT_TYPE_FILE:
4126 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4127 in->variant.fileVariant.fileSize = oh->fileSize;
4130 case YAFFS_OBJECT_TYPE_HARDLINK:
4131 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4132 in->hardLinks.next = (struct list_head *)hardList;
4135 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4137 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4139 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4140 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4143 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4148 if(state == YAFFS_BLOCK_STATE_SCANNING)
4150 // If we got this far while scanning, then the block is fully allocated.
4151 state = YAFFS_BLOCK_STATE_FULL;
4154 bi->blockState = state;
4156 // Now let's see if it was dirty
4157 if( bi->pagesInUse == 0 &&
4158 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4160 yaffs_BlockBecameDirty(dev,blk);
4165 // Fix up the hard link chains.
4166 // We should now have scanned all the objects, now it's time to add these
4171 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4173 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4177 // Add the hardlink pointers
4178 hl->variant.hardLinkVariant.equivalentObject=in;
4179 list_add(&hl->hardLinks,&in->hardLinks);
4183 //Todo Need to report/handle this better.
4184 // Got a problem... hardlink to a non-existant object
4185 hl->variant.hardLinkVariant.equivalentObject=NULL;
4186 INIT_LIST_HEAD(&hl->hardLinks);
4193 struct list_head *i;
4195 // Soft delete all the unlinked files
4196 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4198 l = list_entry(i, yaffs_Object,siblings);
4201 yaffs_SoftDeleteFile(l);
4211 ////////////////////////// Directory Functions /////////////////////////
4214 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
4217 if(obj->siblings.prev == NULL)
4220 INIT_LIST_HEAD(&obj->siblings);
4223 else if(!list_empty(&obj->siblings))
4225 // If it is holed up somewhere else, un hook it
4226 list_del_init(&obj->siblings);
4229 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
4230 obj->parent = directory;
4232 if(directory == obj->myDev->unlinkedDir)
4235 obj->myDev->nUnlinkedFiles++;
4236 obj->renameAllowed = 0;
4240 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4242 list_del_init(&obj->siblings);
4246 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
4250 struct list_head *i;
4251 char buffer[YAFFS_MAX_NAME_LENGTH+1];
4255 sum = yaffs_CalcNameSum(name);
4257 list_for_each(i,&directory->variant.directoryVariant.children)
4259 l = list_entry(i, yaffs_Object,siblings);
4261 // Special case for lost-n-found
4262 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4264 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
4269 else if(yaffs_SumCompare(l->sum, sum))
4272 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
4273 if(yaffs_strcmp(name,buffer) == 0)
4286 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
4288 struct list_head *i;
4292 list_for_each(i,&theDir->variant.directoryVariant.children)
4294 l = list_entry(i, yaffs_Object,siblings);
4306 // GetEquivalentObject dereferences any hard links to get to the
4309 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4311 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4313 // We want the object id of the equivalent object, not this one
4314 obj = obj->variant.hardLinkVariant.equivalentObject;
4320 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
4322 memset(name,0,buffSize);
4324 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4326 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
4328 else if(obj->chunkId <= 0)
4332 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
4333 strncpy(name,locName,buffSize - 1);
4336 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4337 else if(obj->shortName[0])
4339 strcpy(name,obj->shortName);
4344 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4345 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4347 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4349 if(obj->chunkId >= 0)
4351 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
4353 strncpy(name,oh->name,buffSize - 1);
4356 return strlen(name);
4359 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4362 // Dereference any hard linking
4363 obj = yaffs_GetEquivalentObject(obj);
4365 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4367 return obj->variant.fileVariant.fileSize;
4369 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4371 return strlen(obj->variant.symLinkVariant.alias);
4375 // Only a directory should drop through to here
4376 return YAFFS_BYTES_PER_CHUNK;
4380 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4383 struct list_head *i;
4387 count++; // the object itself
4389 list_for_each(i,&obj->hardLinks)
4391 count++; // add the hard links;
4398 int yaffs_GetObjectInode(yaffs_Object *obj)
4400 obj = yaffs_GetEquivalentObject(obj);
4402 return obj->objectId;
4405 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4407 obj = yaffs_GetEquivalentObject(obj);
4409 switch(obj->variantType)
4411 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
4412 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
4413 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
4414 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
4415 case YAFFS_OBJECT_TYPE_SPECIAL:
4416 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
4417 if(S_ISCHR(obj->st_mode)) return DT_CHR;
4418 if(S_ISBLK(obj->st_mode)) return DT_BLK;
4419 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
4420 default: return DT_REG; break;
4424 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4426 obj = yaffs_GetEquivalentObject(obj);
4427 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4429 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4433 return yaffs_CloneString("");
4437 #ifndef CONFIG_YAFFS_WINCE
4439 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4441 unsigned int valid = attr->ia_valid;
4443 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4444 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4445 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4447 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
4448 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
4449 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
4451 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4453 yaffs_UpdateObjectHeader(obj,NULL,1);
4458 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4460 unsigned int valid = 0;
4462 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
4463 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
4464 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
4466 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
4467 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
4468 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
4470 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4472 attr->ia_valid = valid;
4480 int yaffs_DumpObject(yaffs_Object *obj)
4482 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4484 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4486 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4488 // if(obj->chunkId >= 0)
4490 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4493 yaffs_GetObjectName(obj,name,256);
4495 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),
4496 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
4497 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4500 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4501 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
4502 obj->sum, obj->chunkId));
4503 switch(obj->variantType)
4505 case YAFFS_OBJECT_TYPE_FILE:
4506 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4508 case YAFFS_OBJECT_TYPE_DIRECTORY:
4509 YPRINTF((" DIRECTORY\n"));
4511 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4512 case YAFFS_OBJECT_TYPE_SYMLINK:
4513 case YAFFS_OBJECT_TYPE_UNKNOWN:
4522 ///////////////////////// Initialisation code ///////////////////////////
4526 int yaffs_GutsInitialise(yaffs_Device *dev)
4535 if(!yaffs_CheckStructures())
4537 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
4543 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
4549 if(dev->startBlock <= 0 ||
4550 (dev->endBlock - dev->startBlock) < 10)
4552 T(YAFFS_TRACE_ALWAYS,(TSTR("startBlock %d or endBlock %d invalid\n" TENDSTR),
4553 dev->startBlock, dev->endBlock));
4557 nBlocks = dev->endBlock - dev->startBlock + 1;
4561 // OK now calculate a few things for the device
4562 // Calculate chunkGroupBits.
4563 // We need to find the next power of 2 > than endBlock
4565 x = YAFFS_CHUNKS_PER_BLOCK * (dev->endBlock+1);
4567 for(bits = extraBits = 0; x > 1; bits++)
4569 if(x & 1) extraBits++;
4573 if(extraBits > 0) bits++;
4576 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4577 // chunk range we're using is greater than 16 we need
4578 // to figure out chunk shift and chunkGroupSize
4581 dev->chunkGroupBits = 0;
4585 dev->chunkGroupBits = bits - 16;
4587 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4589 // Stuff to be taken out later
4590 dev->nBytesPerChunk = YAFFS_BYTES_PER_CHUNK;
4591 dev->nChunksPerBlock = YAFFS_CHUNKS_PER_BLOCK;
4594 // More device initialisation
4595 dev->garbageCollectionRequired = 0;
4596 dev->garbageCollections = 0;
4597 dev->currentDirtyChecker = 0;
4598 dev->bufferedBlock = -1;
4599 dev->doingBufferedBlockRewrite = 0;
4600 dev->blockSelectedForGC = -1;
4601 dev->nDeletedFiles = 0;
4602 dev->nBackgroundDeletions=0;
4603 dev->nUnlinkedFiles = 0;
4606 dev->tagsEccFixed=0;
4607 dev->tagsEccUnfixed=0;
4609 dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
4614 yaffs_InitialiseBlocks(dev,nBlocks);
4616 yaffs_InitialiseTnodes(dev);
4618 yaffs_InitialiseObjects(dev);
4620 if(dev->nShortOpCaches > 0)
4624 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
4626 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
4629 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
4631 for(i=0; i < dev->nShortOpCaches; i++)
4633 dev->srCache[i].object = NULL;
4634 dev->srCache[i].lastUse = 0;
4635 dev->srCache[i].dirty = 0;
4643 // Initialise the unlinked, root and lost and found directories
4644 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4646 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4648 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4649 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4650 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4653 // Now scan the flash.
4657 dev->nPageReads = 0;
4658 dev->nPageWrites = 0;
4659 dev->nBlockErasures = 0;
4661 dev->nRetriedWrites = 0;
4662 dev->nRetiredBlocks = 0;
4669 void yaffs_Deinitialise(yaffs_Device *dev)
4674 yaffs_DeinitialiseBlocks(dev);
4675 yaffs_DeinitialiseTnodes(dev);
4676 yaffs_DeinitialiseObjects(dev);
4683 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4685 int nFree = dev->nFreeChunks - (YAFFS_CHUNKS_PER_BLOCK * YAFFS_RESERVED_BLOCKS);
4687 struct list_head *i;
4691 // To the free chunks add the chunks that are in the deleted unlinked files.
4692 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4694 l = list_entry(i, yaffs_Object,siblings);
4698 nFree += l->nDataChunks;
4703 printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
4705 if(nFree < 0) nFree = 0;
4713 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4719 yaffs_BlockInfo *blk;
4721 struct list_head *i;
4724 for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
4726 blk = yaffs_GetBlockInfo(dev,b);
4728 switch(blk->blockState)
4730 case YAFFS_BLOCK_STATE_EMPTY:
4731 case YAFFS_BLOCK_STATE_ALLOCATING:
4732 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
4740 // To the free chunks add the chunks that are in the deleted unlinked files.
4741 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4743 l = list_entry(i, yaffs_Object,siblings);
4747 pending += l->nDataChunks;
4753 //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
4755 if(nFree != dev->nFreeChunks)
4757 // printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
4762 if(nFree < 0) nFree = 0;
4770 /////////////////// YAFFS test code //////////////////////////////////
4772 #define yaffs_CheckStruct(structure,syze, name) \
4773 if(sizeof(structure) != syze) \
4775 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
4776 return YAFFS_FAIL; \
4780 static int yaffs_CheckStructures(void)
4782 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4783 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4784 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4785 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
4786 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4788 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4795 void yaffs_GutsTest(yaffs_Device *dev)
4798 if(yaffs_CheckStructures() != YAFFS_OK)
4800 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
4804 yaffs_TnodeTest(dev);
4805 yaffs_ObjectTest(dev);