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.24 2003-04-03 17:58:56 charles Exp $";
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
27 #define YAFFS_PASSIVE_GC_CHUNKS 2
29 // External functions for ECC on data
30 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
31 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
34 // countBits is a quick way of counting the number of bits in a byte.
35 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
37 static const char yaffs_countBitsTable[256] =
39 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
40 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
41 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
42 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
43 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
44 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
45 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
46 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
47 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
48 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
49 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
50 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
51 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
52 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
53 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
54 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
57 static int yaffs_CountBits(__u8 x)
60 retVal = yaffs_countBitsTable[x];
67 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
68 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
69 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
70 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
72 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
73 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
74 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force);
75 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND);
76 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
77 static int yaffs_CheckStructures(void);
78 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
84 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
85 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
86 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
87 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare);
88 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare);
90 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
92 static int yaffs_UnlinkWorker(yaffs_Object *obj);
93 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj);
95 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1);
99 loff_t yaffs_GetFileSize(yaffs_Object *obj);
101 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
102 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
105 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
107 #ifdef YAFFS_PARANOID
108 static int yaffs_CheckFileSanity(yaffs_Object *in);
110 #define yaffs_CheckFileSanity(in)
113 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
114 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
116 // Chunk bitmap manipulations
118 static __inline __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
120 if(blk < dev->startBlock || blk > dev->endBlock)
122 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
125 return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->startBlock));
128 static __inline__ void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
130 __u8 *blkBits = yaffs_BlockBits(dev,blk);
132 memset(blkBits,0,dev->chunkBitmapStride);
135 static __inline__ void yaffs_ClearChunkBit(yaffs_Device *dev,int blk,int chunk)
137 __u8 *blkBits = yaffs_BlockBits(dev,blk);
139 blkBits[chunk/8] &= ~ (1<<(chunk & 7));
142 static __inline__ void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
144 __u8 *blkBits = yaffs_BlockBits(dev,blk);
146 blkBits[chunk/8] |= (1<<(chunk & 7));
149 static __inline__ int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
151 __u8 *blkBits = yaffs_BlockBits(dev,blk);
152 return (blkBits[chunk/8] & (1<<(chunk & 7))) ? 1 :0;
155 static __inline__ int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
157 __u8 *blkBits = yaffs_BlockBits(dev,blk);
159 for(i = 0; i < dev->chunkBitmapStride; i++)
161 if(*blkBits) return 1;
167 // Function to manipulate block info
168 static __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
170 if(blk < dev->startBlock || blk > dev->endBlock)
172 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),blk));
175 return &dev->blockInfo[blk - dev->startBlock];
179 static __inline__ int yaffs_HashFunction(int n)
181 return (n % YAFFS_NOBJECT_BUCKETS);
185 yaffs_Object *yaffs_Root(yaffs_Device *dev)
190 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
192 return dev->lostNFoundDir;
196 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
198 if(chunkInNAND < dev->startBlock * dev->nChunksPerBlock)
200 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
205 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
210 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
214 int doErrorCorrection)
217 yaffs_Spare localSpare;
226 // If we don't have a real spare, then we use a local one.
227 // Need this for the calculation of the ecc
234 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
235 if(data && doErrorCorrection)
238 //Todo handle any errors
239 int eccResult1,eccResult2;
242 nand_calculate_ecc(data,calcEcc);
243 eccResult1 = nand_correct_data (data,spare->ecc1, calcEcc);
244 nand_calculate_ecc(&data[256],calcEcc);
245 eccResult2 = nand_correct_data (&data[256],spare->ecc2, calcEcc);
249 T(YAFFS_TRACE_ERROR, (TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
252 else if(eccResult1<0)
254 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
260 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
263 else if(eccResult2<0)
265 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
269 if(eccResult1 || eccResult2)
271 // Hoosterman, we had a data problem on this page
272 yaffs_HandleReadDataError(dev,chunkInNAND);
278 // Must allocate enough memory for spare+2*sizeof(int) for ecc results from device.
279 struct yaffs_NANDSpare nspare;
280 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
281 memcpy (spare, &nspare, sizeof(yaffs_Spare));
282 if(data && doErrorCorrection)
286 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
288 else if(nspare.eccres1<0)
290 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
295 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
297 else if(nspare.eccres2<0)
299 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
302 if(nspare.eccres1 || nspare.eccres2)
304 // Hoosterman, we had a data problem on this page
305 yaffs_HandleReadDataError(dev,chunkInNAND);
314 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
318 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
319 static __u8 data[YAFFS_BYTES_PER_CHUNK];
320 // Might as well always allocate the larger size for dev->useNANDECC == true;
321 static __u8 spare[sizeof(struct yaffs_NANDSpare)];
323 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
327 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
331 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL;
332 if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
341 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
343 dev->nBlockErasures++;
344 return dev->eraseBlockInNAND(dev,blockInNAND);
347 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
349 return dev->initialiseNAND(dev);
352 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
359 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
363 chunk = yaffs_AllocateChunk(dev,useReserve);
368 // First check this chunk is erased...
369 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
370 writeOk = yaffs_CheckChunkErased(dev,chunk);
374 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
378 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
384 // If verify fails, then delete this chunk and try again
385 // To verify we compare everything except the block and
386 // page status bytes.
387 // NB We check a raw read without ECC correction applied
388 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
390 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
391 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
394 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
403 // Copy the data into the write buffer.
404 // NB We do this at the end to prevent duplicates in the case of a write error.
406 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
410 yaffs_HandleWriteChunkError(dev,chunk);
414 } while(chunk >= 0 && ! writeOk);
418 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
419 dev->nRetriedWrites+= (attempts - 1);
426 // Functions for robustisizing
430 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
432 // Ding the blockStatus in the first two pages of the block.
436 memset(&spare, 0xff,sizeof(yaffs_Spare));
438 spare.blockStatus = 0;
440 // TODO change this retirement marking for other NAND types
441 yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock, NULL , &spare);
442 yaffs_WriteChunkToNAND(dev, blockInNAND * dev->nChunksPerBlock + 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/dev->nChunksPerBlock;
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/dev->nChunksPerBlock;
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--)
1151 theChunk = (tn->level0[i] << in->myDev->chunkGroupBits);
1152 T(YAFFS_TRACE_SCAN,(TSTR("soft delete tch %d cgb %d chunk %d" TENDSTR),
1153 tn->level0[i],in->myDev->chunkGroupBits,theChunk));
1155 theBlock = yaffs_GetBlockInfo(in->myDev, theChunk/in->myDev->nChunksPerBlock);
1158 theBlock->softDeletions++;
1176 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1179 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1182 if(obj->nDataChunks <= 0)
1184 // Empty file, just delete it immediately
1185 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1186 obj->variant.fileVariant.top = NULL;
1187 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1188 yaffs_DoGenericObjectDeletion(obj);
1192 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1193 obj->softDeleted = 1;
1202 // Pruning removes any part of the file structure tree that is beyond the
1203 // bounds of the file (ie that does not point to chunks).
1205 // A file should only get pruned when its size is reduced.
1207 // Before pruning, the chunks must be pulled from the tree and the
1208 // level 0 tnode entries must be zeroed out.
1209 // Could also use this for file deletion, but that's probably better handled
1210 // by a special case.
1212 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1214 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1223 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1225 if(tn->internal[i] && level > 0)
1227 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1236 if(hasData == 0 && del0)
1238 // Free and return NULL
1240 yaffs_FreeTnode(dev,tn);
1250 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1257 if(fStruct->topLevel > 0)
1259 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1261 // Now we have a tree with all the non-zero branches NULL but the height
1262 // is the same as it was.
1263 // Let's see if we can trim internal tnodes to shorten the tree.
1264 // We can do this if only the 0th element in the tnode is in use
1265 // (ie all the non-zero are NULL)
1267 while(fStruct->topLevel && !done)
1272 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1282 fStruct->top = tn->internal[0];
1283 fStruct->topLevel--;
1284 yaffs_FreeTnode(dev,tn);
1300 /////////////////////// End of File Structure functions. /////////////////
1302 // yaffs_CreateFreeObjects creates a bunch more objects and
1303 // adds them to the object free list.
1304 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1307 yaffs_Object *newObjects;
1308 yaffs_ObjectList *list;
1310 if(nObjects < 1) return YAFFS_OK;
1312 // make these things
1314 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1318 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1322 // Hook them into the free list
1323 for(i = 0; i < nObjects - 1; i++)
1325 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1328 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1329 dev->freeObjects = newObjects;
1330 dev->nFreeObjects+= nObjects;
1331 dev->nObjectsCreated+= nObjects;
1333 // Now add this bunch of Objects to a list for freeing up.
1335 list = YMALLOC(sizeof(yaffs_ObjectList));
1338 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1342 list->objects = newObjects;
1343 list->next = dev->allocatedObjectList;
1344 dev->allocatedObjectList = list;
1353 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1354 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1356 yaffs_Object *tn = NULL;
1358 // If there are none left make more
1359 if(!dev->freeObjects)
1361 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1364 if(dev->freeObjects)
1366 tn = dev->freeObjects;
1367 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1368 dev->nFreeObjects--;
1370 // Now sweeten it up...
1372 memset(tn,0,sizeof(yaffs_Object));
1375 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1376 INIT_LIST_HEAD(&(tn->hardLinks));
1377 INIT_LIST_HEAD(&(tn->hashLink));
1378 INIT_LIST_HEAD(&tn->siblings);
1380 // Add it to the lost and found directory.
1381 // NB Can't put root or lostNFound in lostNFound so
1382 // check if lostNFound exists first
1383 if(dev->lostNFoundDir)
1385 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1393 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1396 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1399 obj->fake = 1; // it is fake so it has no NAND presence...
1400 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1401 obj->unlinkAllowed= 0; // ... or unlink it
1404 obj->st_mode = mode;
1406 obj->chunkId = 0; // Not a valid chunk.
1414 static void yaffs_UnhashObject(yaffs_Object *tn)
1417 yaffs_Device *dev = tn->myDev;
1420 // If it is still linked into the bucket list, free from the list
1421 if(!list_empty(&tn->hashLink))
1423 list_del_init(&tn->hashLink);
1424 bucket = yaffs_HashFunction(tn->objectId);
1425 dev->objectBucket[bucket].count--;
1431 // FreeObject frees up a Object and puts it back on the free list
1432 static void yaffs_FreeObject(yaffs_Object *tn)
1435 yaffs_Device *dev = tn->myDev;
1437 yaffs_UnhashObject(tn);
1439 // Link into the free list.
1440 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1441 dev->freeObjects = tn;
1442 dev->nFreeObjects++;
1448 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1450 // Free the list of allocated Objects
1452 while( dev->allocatedObjectList)
1454 YFREE(dev->allocatedObjectList->objects);
1455 dev->allocatedObjectList = dev->allocatedObjectList->next;
1458 dev->freeObjects = NULL;
1459 dev->nFreeObjects = 0;
1462 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1466 dev->allocatedObjectList = NULL;
1467 dev->freeObjects = NULL;
1468 dev->nFreeObjects = 0;
1470 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1472 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1473 dev->objectBucket[i].count = 0;
1483 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1488 int lowest = 999999;
1491 // First let's see if we can find one that's empty.
1493 for(i = 0; i < 10 && lowest > 0; i++)
1496 x %= YAFFS_NOBJECT_BUCKETS;
1497 if(dev->objectBucket[x].count < lowest)
1499 lowest = dev->objectBucket[x].count;
1505 // If we didn't find an empty list, then try
1506 // looking a bit further for a short one
1508 for(i = 0; i < 10 && lowest > 3; i++)
1511 x %= YAFFS_NOBJECT_BUCKETS;
1512 if(dev->objectBucket[x].count < lowest)
1514 lowest = dev->objectBucket[x].count;
1523 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1525 int bucket = yaffs_FindNiceObjectBucket(dev);
1527 // Now find an object value that has not already been taken
1528 // by scanning the list.
1531 struct list_head *i;
1533 __u32 n = (__u32)bucket;
1535 //yaffs_CheckObjectHashSanity();
1540 n += YAFFS_NOBJECT_BUCKETS;
1541 if(1 ||dev->objectBucket[bucket].count > 0)
1543 list_for_each(i,&dev->objectBucket[bucket].list)
1545 // If there is already one in the list
1546 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1554 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1559 void yaffs_HashObject(yaffs_Object *in)
1561 int bucket = yaffs_HashFunction(in->objectId);
1562 yaffs_Device *dev = in->myDev;
1564 if(!list_empty(&in->hashLink))
1570 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1571 dev->objectBucket[bucket].count++;
1575 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1577 int bucket = yaffs_HashFunction(number);
1578 struct list_head *i;
1581 list_for_each(i,&dev->objectBucket[bucket].list)
1583 // Look if it is in the list
1586 in = list_entry(i, yaffs_Object,hashLink);
1587 if(in->objectId == number)
1599 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1602 yaffs_Object *theObject;
1606 number = yaffs_CreateNewObjectNumber(dev);
1609 theObject = yaffs_AllocateEmptyObject(dev);
1613 theObject->fake = 0;
1614 theObject->renameAllowed = 1;
1615 theObject->unlinkAllowed = 1;
1616 theObject->objectId = number;
1617 yaffs_HashObject(theObject);
1618 theObject->variantType = type;
1619 #ifdef CONFIG_YAFFS_WINCE
1620 yfsd_WinFileTimeNow(theObject->win_atime);
1621 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1622 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1625 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1629 case YAFFS_OBJECT_TYPE_FILE:
1630 theObject->variant.fileVariant.fileSize = 0;
1631 theObject->variant.fileVariant.scannedFileSize = 0;
1632 theObject->variant.fileVariant.topLevel = 0;
1633 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1635 case YAFFS_OBJECT_TYPE_DIRECTORY:
1636 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1638 case YAFFS_OBJECT_TYPE_SYMLINK:
1639 // No action required
1641 case YAFFS_OBJECT_TYPE_HARDLINK:
1642 // No action required
1644 case YAFFS_OBJECT_TYPE_SPECIAL:
1645 // No action required
1647 case YAFFS_OBJECT_TYPE_UNKNOWN:
1648 // todo this should not happen
1656 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1658 yaffs_Object *theObject = NULL;
1662 theObject = yaffs_FindObjectByNumber(dev,number);
1667 theObject = yaffs_CreateNewObject(dev,number,type);
1674 char *yaffs_CloneString(const char *str)
1676 char *newStr = NULL;
1680 newStr = YMALLOC(strlen(str) + 1);
1689 // Mknod (create) a new object.
1690 // equivalentObject only has meaning for a hard link;
1691 // aliasString only has meaning for a sumlink.
1692 // rdev only has meaning for devices (a subset of special objects)
1693 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1694 yaffs_Object *parent,
1699 yaffs_Object *equivalentObject,
1700 const char *aliasString,
1705 yaffs_Device *dev = parent->myDev;
1707 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1708 if(yaffs_FindObjectByName(parent,name))
1713 in = yaffs_CreateNewObject(dev,-1,type);
1719 in->variantType = type;
1723 #ifdef CONFIG_YAFFS_WINCE
1724 yfsd_WinFileTimeNow(in->win_atime);
1725 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1726 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[0];
1729 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1734 in->nDataChunks = 0;
1736 yaffs_SetObjectName(in,name);
1739 yaffs_AddObjectToDirectory(parent,in);
1741 in->myDev = parent->myDev;
1746 case YAFFS_OBJECT_TYPE_SYMLINK:
1747 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1749 case YAFFS_OBJECT_TYPE_HARDLINK:
1750 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1751 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1752 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1754 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1755 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1756 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1757 case YAFFS_OBJECT_TYPE_UNKNOWN:
1761 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1762 yaffs_UpdateObjectHeader(in,name,0) < 0)
1764 // Could not create the object header, fail the creation
1765 yaffs_AbortHalfCreatedObject(in);
1774 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1776 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1779 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1781 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1784 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1786 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1789 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1791 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1794 // NB yaffs_Link returns the object id of the equivalent object.
1795 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1797 // Get the real object in case we were fed a hard link as an equivalent object
1798 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1800 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1802 return equivalentObject;
1812 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1818 newDir = obj->parent; // use the old directory
1821 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1823 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1824 // duplicate names are allowed.
1825 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1828 !yaffs_FindObjectByName(newDir,newName)) &&
1829 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1831 yaffs_SetObjectName(obj,newName);
1834 yaffs_AddObjectToDirectory(newDir,obj);
1836 if(unlinkOp) obj->unlinked = 1;
1839 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1850 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1855 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1856 // Special case for WinCE.
1857 // While look-up is case insensitive, the name isn't.
1858 // THerefore we might want to change x.txt to X.txt
1859 if(oldDir == newDir && _stricmp(oldName,newName) == 0)
1865 obj = yaffs_FindObjectByName(oldDir,oldName);
1866 if(obj && obj->renameAllowed)
1868 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1875 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1877 // Scan the buckets and check that the lists
1878 // have as many members as the count says there are
1881 struct list_head *j;
1884 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1888 list_for_each(j,&dev->objectBucket[bucket].list)
1893 if(countEm != dev->objectBucket[bucket].count)
1895 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1904 void yaffs_ObjectTest(yaffs_Device *dev)
1906 yaffs_Object *in[1000];
1908 yaffs_Object *inold[1000];
1912 memset(in,0,1000*sizeof(yaffs_Object *));
1913 memset(inold,0,1000*sizeof(yaffs_Object *));
1915 yaffs_CheckObjectHashSanity(dev);
1917 for(j = 0; j < 10; j++)
1921 for(i = 0; i < 1000; i++)
1923 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1926 YINFO("No more inodes");
1930 inNo[i] = in[i]->objectId;
1934 for(i = 0; i < 1000; i++)
1936 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1938 //T(("Differnce in look up test\n"));
1942 // T(("Look up ok\n"));
1946 yaffs_CheckObjectHashSanity(dev);
1948 for(i = 0; i < 1000; i+=3)
1950 yaffs_FreeObject(in[i]);
1955 yaffs_CheckObjectHashSanity(dev);
1962 /////////////////////////// Block Management and Page Allocation ///////////////////
1965 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1967 dev->allocationBlock = -1; // force it to get a new one
1968 //Todo we're assuming the malloc will pass.
1969 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1970 // Set up dynamic blockinfo stuff.
1971 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
1972 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1973 if(dev->blockInfo && dev->chunkBits)
1975 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1976 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
1984 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1986 YFREE(dev->blockInfo);
1987 dev->blockInfo = NULL;
1988 YFREE(dev->chunkBits);
1989 dev->chunkBits = NULL;
1992 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1993 // for garbage collection.
1995 static int yaffs_FindDirtiestBlock(yaffs_Device *dev,int aggressive)
1998 int b = dev->currentDirtyChecker;
2004 yaffs_BlockInfo *bi;
2006 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2009 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2012 iterations = dev->endBlock - dev->startBlock + 1;
2016 iterations = dev->endBlock - dev->startBlock + 1;
2017 iterations = iterations / 16;
2018 if(iterations > 200)
2024 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2027 if ( b < dev->startBlock || b > dev->endBlock)
2029 b = dev->startBlock;
2032 if(b < dev->startBlock || b > dev->endBlock)
2034 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2038 bi = yaffs_GetBlockInfo(dev,b);
2040 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2041 (bi->pagesInUse - bi->softDeletions )< pagesInUse)
2044 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2048 dev->currentDirtyChecker = b;
2054 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2056 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2060 // If the block is still healthy erase it and mark as clean.
2061 // If the block has had a data failure, then retire it.
2062 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2064 if(!bi->needsRetiring)
2066 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2069 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2076 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2077 dev->nErasedBlocks++;
2079 bi->softDeletions = 0;
2080 yaffs_ClearChunkBits(dev,blockNo);
2082 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2086 yaffs_RetireBlock(dev,blockNo);
2087 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2092 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2096 yaffs_BlockInfo *bi;
2098 if(dev->nErasedBlocks < 1)
2100 // Hoosterman we've got a problem.
2101 // Can't get space to gc
2102 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during gc" TENDSTR)));
2107 // Find an empty block.
2109 for(i = dev->startBlock; i <= dev->endBlock; i++)
2111 dev->allocationBlockFinder++;
2112 if(dev->allocationBlockFinder <dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2114 dev->allocationBlockFinder = dev->startBlock;
2117 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2119 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2121 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2122 dev->nErasedBlocks--;
2123 return dev->allocationBlockFinder;
2132 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2135 yaffs_BlockInfo *bi;
2137 if(dev->allocationBlock < 0)
2139 // Get next block to allocate off
2140 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2141 dev->allocationPage = 0;
2144 if(!useReserve && dev->nErasedBlocks <= dev->nReservedBlocks)
2146 // Not enough space to allocate unless we're allowed to use the reserve.
2150 // Next page please....
2151 if(dev->allocationBlock >= 0)
2153 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2155 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2156 dev->allocationPage;
2158 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2160 dev->allocationPage++;
2164 // If the block is full set the state to full
2165 if(dev->allocationPage >= dev->nChunksPerBlock)
2167 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2168 dev->allocationBlock = -1;
2175 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2180 // To determine if we have enough space we just look at the
2181 // number of erased blocks.
2182 // The cache is allowed to use reserved blocks.
2184 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2186 return (dev->nErasedBlocks >= dev->nReservedBlocks);
2190 static int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2200 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
2202 // yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2204 yaffs_Object *object;
2206 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2208 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2209 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2210 chunkInBlock++, oldChunk++ )
2212 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2215 // This page is in use and might need to be copied off
2219 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2221 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
2223 yaffs_GetTagsFromSpare(dev,&spare,&tags);
2225 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2227 if(object && object->deleted && tags.chunkId != 0)
2229 // Data chunk in a deleted file, throw it away
2230 // It's a deleted data chunk,
2231 // No need to copy this, just forget about it and fix up the
2234 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2235 object->nDataChunks--;
2237 if(object->nDataChunks <= 0)
2239 // Time to delete the file too
2240 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2241 object->variant.fileVariant.top = NULL;
2242 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2243 yaffs_DoGenericObjectDeletion(object);
2247 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2249 // Deleted object header with no data chunks.
2250 // Can be discarded and the file deleted.
2251 object->chunkId = 0;
2252 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2253 object->variant.fileVariant.top = NULL;
2254 yaffs_DoGenericObjectDeletion(object);
2259 // It's either a data chunk in a live file or
2260 // an ObjectHeader, so we're interested in it.
2261 // NB Need to keep the ObjectHeaders of deleted files
2262 // until the whole file has been deleted off
2263 tags.serialNumber++;
2264 yaffs_LoadTagsIntoSpare(&spare,&tags);
2268 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
2275 // Ok, now fix up the Tnodes etc.
2277 if(tags.chunkId == 0)
2280 object->chunkId = newChunk;
2284 // It's a data chunk
2285 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2289 yaffs_DeleteChunk(dev,oldChunk,markNAND);
2298 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2300 // find a file to delete
2301 struct list_head *i;
2305 //Scan the unlinked files looking for one to delete
2306 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2310 l = list_entry(i, yaffs_Object,siblings);
2321 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2323 // This does background deletion on unlinked files.. only deleted ones.
2324 // If we don't have a file we're working on then find one
2325 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2327 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2330 // OK, we're working on a file...
2331 if(dev->unlinkedDeletion)
2333 yaffs_Object *obj = dev->unlinkedDeletion;
2335 int limit; // Number of chunks to delete in a file.
2336 // NB this can be exceeded, but not by much.
2340 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2342 if(obj->nDataChunks == 0)
2344 // Done all the deleting of data chunks.
2345 // Now dump the header and clean up
2346 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2347 obj->variant.fileVariant.top = NULL;
2348 yaffs_DoGenericObjectDeletion(obj);
2349 dev->nDeletedFiles--;
2350 dev->nUnlinkedFiles--;
2351 dev->nBackgroundDeletions++;
2352 dev->unlinkedDeletion = NULL;
2359 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
2360 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2365 //yaffs_DoUnlinkedFileDeletion(dev);
2367 if(dev->nErasedBlocks <= (dev->nReservedBlocks + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2374 block = yaffs_FindDirtiestBlock(dev,aggressive);
2378 dev->garbageCollections++;
2379 return yaffs_GarbageCollectBlock(dev,block);
2391 // New garbage collector
2392 // If we're very low on erased blocks then we do aggressive garbage collection
2393 // otherwise we do "passive" garbage collection.
2394 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2395 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2397 // The idea is to help clear out space in a more spread-out manner.
2398 // Dunno if it really does anything useful.
2400 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2405 //yaffs_DoUnlinkedFileDeletion(dev);
2407 if(dev->nErasedBlocks <= (dev->nReservedBlocks + 1))
2412 block = yaffs_FindDirtiestBlock(dev,aggressive);
2416 dev->garbageCollections++;
2419 dev->passiveGarbageCollections++;
2422 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2424 return yaffs_GarbageCollectBlock(dev,block);
2427 return aggressive ? YAFFS_FAIL : YAFFS_OK;
2431 //////////////////////////// TAGS ///////////////////////////////////////
2433 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2435 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2437 yaffs_CalcTagsECC(tagsPtr);
2439 sparePtr->tagByte0 = tu->asBytes[0];
2440 sparePtr->tagByte1 = tu->asBytes[1];
2441 sparePtr->tagByte2 = tu->asBytes[2];
2442 sparePtr->tagByte3 = tu->asBytes[3];
2443 sparePtr->tagByte4 = tu->asBytes[4];
2444 sparePtr->tagByte5 = tu->asBytes[5];
2445 sparePtr->tagByte6 = tu->asBytes[6];
2446 sparePtr->tagByte7 = tu->asBytes[7];
2449 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2451 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2454 tu->asBytes[0]= sparePtr->tagByte0;
2455 tu->asBytes[1]= sparePtr->tagByte1;
2456 tu->asBytes[2]= sparePtr->tagByte2;
2457 tu->asBytes[3]= sparePtr->tagByte3;
2458 tu->asBytes[4]= sparePtr->tagByte4;
2459 tu->asBytes[5]= sparePtr->tagByte5;
2460 tu->asBytes[6]= sparePtr->tagByte6;
2461 tu->asBytes[7]= sparePtr->tagByte7;
2463 result = yaffs_CheckECCOnTags(tagsPtr);
2466 dev->tagsEccFixed++;
2470 dev->tagsEccUnfixed++;
2474 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2476 memset(spare,0xFF,sizeof(yaffs_Spare));
2479 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2484 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2486 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2487 yaffs_GetTagsFromSpare(dev,&spare,tags);
2500 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2502 // NB There must be tags, data is optional
2503 // If there is data, then an ECC is calculated on it.
2512 yaffs_SpareInitialise(&spare);
2514 if(!dev->useNANDECC && buffer)
2516 yaffs_CalcECC(buffer,&spare);
2519 yaffs_LoadTagsIntoSpare(&spare,tags);
2521 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2527 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2529 // NB There must be tags, data is optional
2530 // If there is data, then an ECC is calculated on it.
2539 yaffs_SpareInitialise(&spare);
2541 if(!dev->useNANDECC && buffer)
2543 yaffs_CalcECC(buffer,&spare);
2546 yaffs_LoadTagsIntoSpare(&spare,tags);
2548 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2552 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2554 return ( tags->chunkId == chunkInObject &&
2555 tags->objectId == objectId &&
2556 !chunkDeleted) ? 1 : 0;
2562 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2564 //Get the Tnode, then get the level 0 offset chunk offset
2567 yaffs_Tags localTags;
2572 yaffs_Device *dev = in->myDev;
2577 // Passed a NULL, so use our own tags space
2581 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2585 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2587 // Now we need to do the shifting etc and search for it
2588 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2590 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2591 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2602 return found ? theChunk : -1;
2605 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2607 //Get the Tnode, then get the level 0 offset chunk offset
2610 yaffs_Tags localTags;
2613 yaffs_Device *dev = in->myDev;
2618 // Passed a NULL, so use our own tags space
2622 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2627 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2629 // Now we need to do the shifting etc and search for it
2630 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2632 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2633 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2644 // Delete the entry in the filestructure
2647 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2652 //T(("No level 0 found for %d\n", chunkInInode));
2657 //T(("Could not find %d to delete\n",chunkInInode));
2659 return found ? theChunk : -1;
2663 #ifdef YAFFS_PARANOID
2665 static int yaffs_CheckFileSanity(yaffs_Object *in)
2673 yaffs_Tags localTags;
2674 yaffs_Tags *tags = &localTags;
2679 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2681 //T(("Object not a file\n"));
2685 objId = in->objectId;
2686 fSize = in->variant.fileVariant.fileSize;
2687 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
2689 for(chunk = 1; chunk <= nChunks; chunk++)
2691 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2696 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2699 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2700 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2707 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2708 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2717 //T(("No level 0 found for %d\n", chunk));
2721 return failed ? YAFFS_FAIL : YAFFS_OK;
2726 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2729 yaffs_Device *dev = in->myDev;
2731 yaffs_Tags existingTags;
2733 unsigned existingSerial, newSerial;
2735 int newChunkDeleted;
2738 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2744 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2748 // If we're scanning then we need to test for duplicates
2749 // NB This does not need to be efficient since it should only ever
2750 // happen when the power fails during a write, then only one
2751 // chunk should ever be affected.
2754 if(existingChunk != 0)
2756 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2757 // thus we have to do a FindChunkInFile to get the real chunk id.
2759 // We have a duplicate now we need to decide which one to use
2760 // To do this we get both sets of tags and compare serial numbers.
2761 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2765 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2767 if(existingChunk <=0)
2769 //Hoosterman - how did this happen?
2771 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
2776 // NB The deleted flags should be false, otherwise the chunks will
2777 // not be loaded during a scan
2779 newSerial = newTags.serialNumber;
2780 existingSerial = existingTags.serialNumber;
2782 if( existingChunk <= 0 ||
2783 ((existingSerial+1) & 3) == newSerial)
2786 // Delete the old one and drop through to update the tnode
2787 yaffs_DeleteChunk(dev,existingChunk,1);
2792 // Delete the new one and return early so that the tnode isn't changed
2793 yaffs_DeleteChunk(dev,chunkInNAND,1);
2800 if(existingChunk == 0)
2805 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2812 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2814 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2816 if(chunkInNAND >= 0)
2818 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2828 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND)
2833 yaffs_BlockInfo *bi;
2835 if(chunkId <= 0) return;
2838 block = chunkId / dev->nChunksPerBlock;
2839 page = chunkId % dev->nChunksPerBlock;
2843 yaffs_SpareInitialise(&spare);
2845 spare.pageStatus = 0; // To mark it as deleted.
2848 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2849 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2853 dev->nUnmarkedDeletions++;
2856 bi = yaffs_GetBlockInfo(dev,block);
2859 // Pull out of the management area.
2860 // If the whole block became dirty, this will kick off an erasure.
2861 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2862 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2866 yaffs_ClearChunkBit(dev,block,page);
2869 if(bi->pagesInUse == 0 &&
2870 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2872 yaffs_BlockBecameDirty(dev,block);
2878 // T(("Bad news deleting chunk %d\n",chunkId));
2886 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2888 // Find old chunk Need to do this to get serial number
2889 // Write new one and patch into tree.
2890 // Invalidate old tags.
2893 yaffs_Tags prevTags;
2898 yaffs_Device *dev = in->myDev;
2900 yaffs_CheckGarbageCollection(dev);
2902 // Get the previous chunk at this location in the file if it exists
2903 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2906 newTags.chunkId = chunkInInode;
2907 newTags.objectId = in->objectId;
2908 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2909 newTags.byteCount = nBytes;
2910 newTags.unusedStuff = 0xFFFFFFFF;
2912 yaffs_CalcTagsECC(&newTags);
2914 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2917 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2920 if(prevChunkId >= 0)
2922 yaffs_DeleteChunk(dev,prevChunkId,1);
2926 yaffs_CheckFileSanity(in);
2937 // UpdateObjectHeader updates the header on NAND for an object.
2938 // If name is not NULL, then that new name is used.
2940 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2943 yaffs_Device *dev = in->myDev;
2949 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2950 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2952 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2953 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2956 if(!in->fake || force)
2959 yaffs_CheckGarbageCollection(dev);
2961 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2963 prevChunkId = in->chunkId;
2965 if(prevChunkId >= 0)
2967 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2971 oh->type = in->variantType;
2973 oh->st_mode = in->st_mode;
2975 #ifdef CONFIG_YAFFS_WINCE
2976 oh->win_atime[0] = in->win_atime[0];
2977 oh->win_ctime[0] = in->win_ctime[0];
2978 oh->win_mtime[0] = in->win_mtime[0];
2979 oh->win_atime[1] = in->win_atime[1];
2980 oh->win_ctime[1] = in->win_ctime[1];
2981 oh->win_mtime[1] = in->win_mtime[1];
2983 oh->st_uid = in->st_uid;
2984 oh->st_gid = in->st_gid;
2985 oh->st_atime = in->st_atime;
2986 oh->st_mtime = in->st_mtime;
2987 oh->st_ctime = in->st_ctime;
2988 oh->st_rdev = in->st_rdev;
2992 oh->parentObjectId = in->parent->objectId;
2996 oh->parentObjectId = 0;
2999 //oh->sum = in->sum;
3002 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3003 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3005 else if(prevChunkId)
3007 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
3011 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
3014 switch(in->variantType)
3016 case YAFFS_OBJECT_TYPE_UNKNOWN:
3017 // Should not happen
3019 case YAFFS_OBJECT_TYPE_FILE:
3020 oh->fileSize = in->variant.fileVariant.fileSize;
3022 case YAFFS_OBJECT_TYPE_HARDLINK:
3023 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3025 case YAFFS_OBJECT_TYPE_SPECIAL:
3028 case YAFFS_OBJECT_TYPE_DIRECTORY:
3031 case YAFFS_OBJECT_TYPE_SYMLINK:
3032 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3033 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3039 newTags.chunkId = 0;
3040 newTags.objectId = in->objectId;
3041 newTags.serialNumber = in->serial;
3042 newTags.byteCount = 0xFFFFFFFF;
3043 newTags.unusedStuff = 0xFFFFFFFF;
3045 yaffs_CalcTagsECC(&newTags);
3048 // Create new chunk in NAND
3049 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3054 in->chunkId = newChunkId;
3056 if(prevChunkId >= 0)
3058 yaffs_DeleteChunk(dev,prevChunkId,1);
3071 /////////////////////// Short Operations Cache ////////////////////////////////
3072 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3073 // reads might be short sequential reads, and a lot of writes may be short
3074 // sequential writes. eg. scanning/writing a jpeg file.
3075 // In these cases, a short read/write cache can provide a huge perfomance benefit
3076 // with dumb-as-a-rock code.
3077 // There are a limited number (~10) of cache chunks per device so that we don't
3078 // need a very intelligent search.
3084 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3086 yaffs_Device *dev = obj->myDev;
3089 yaffs_ChunkCache *cache;
3092 int nCaches = obj->myDev->nShortOpCaches;
3099 // Find the dirty cache for this object with the lowest chunk id.
3100 for(i = 0; i < nCaches; i++)
3102 if(dev->srCache[i].object == obj &&
3103 dev->srCache[i].dirty)
3105 if(!cache || dev->srCache[i].chunkId < lowest)
3107 cache = &dev->srCache[i];
3108 lowest = cache->chunkId;
3118 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3120 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3122 nBytes= YAFFS_BYTES_PER_CHUNK;
3125 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3131 cache->object = NULL;
3134 } while(cache && chunkWritten > 0);
3138 //Hoosterman, disk full while writing cache out.
3139 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3147 // Grab us a chunk for use.
3148 // First look for an empty one.
3149 // Then look for the least recently used non-dirty one.
3150 // Then look for the least recently used dirty one...., flush and look again.
3151 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3157 if(dev->nShortOpCaches > 0)
3159 for(i = 0; i < dev->nShortOpCaches; i++)
3161 if(!dev->srCache[i].object)
3163 //T(("Grabbing empty %d\n",i));
3165 //printf("Grabbing empty %d\n",i);
3167 return &dev->srCache[i];
3174 usage = 0; // just to stop the compiler grizzling
3176 for(i = 0; i < dev->nShortOpCaches; i++)
3178 if(!dev->srCache[i].dirty &&
3179 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3182 usage = dev->srCache[i].lastUse;
3187 //T(("Grabbing non-empty %d\n",theOne));
3189 //if(theOne >= 0) printf("Grabbed non-empty cache %d\n",theOne);
3191 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3201 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3203 yaffs_ChunkCache *cache;
3204 yaffs_Object *theObj;
3209 if(dev->nShortOpCaches > 0)
3211 // Try find a non-dirty one...
3213 cache = yaffs_GrabChunkCacheWorker(dev);
3217 // They were all dirty, find the last recently used object and flush
3218 // its cache, then find again.
3219 // NB what's here is not very accurate, we actually flush the object
3220 // the last recently used page.
3222 theObj = dev->srCache[0].object;
3223 usage = dev->srCache[0].lastUse;
3224 cache = &dev->srCache[0];
3227 for(i = 1; i < dev->nShortOpCaches; i++)
3229 if( dev->srCache[i].object &&
3230 dev->srCache[i].lastUse < usage)
3232 usage = dev->srCache[i].lastUse;
3233 theObj = dev->srCache[i].object;
3234 cache = &dev->srCache[i];
3239 if(!cache || cache->dirty)
3243 yaffs_FlushFilesChunkCache(theObj);
3246 cache = yaffs_GrabChunkCacheWorker(dev);
3250 //printf(" pushout %d\n",pushout);
3263 // Find a cached chunk
3264 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3266 yaffs_Device *dev = obj->myDev;
3268 if(dev->nShortOpCaches > 0)
3270 for(i = 0; i < dev->nShortOpCaches; i++)
3272 if(dev->srCache[i].object == obj &&
3273 dev->srCache[i].chunkId == chunkId)
3277 return &dev->srCache[i];
3284 // Mark the chunk for the least recently used algorithym
3285 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3288 if(dev->nShortOpCaches > 0)
3290 if( dev->srLastUse < 0 ||
3291 dev->srLastUse > 100000000)
3293 // Reset the cache usages
3295 for(i = 1; i < dev->nShortOpCaches; i++)
3297 dev->srCache[i].lastUse = 0;
3304 cache->lastUse = dev->srLastUse;
3313 // Invalidate a single cache page.
3314 // Do this when a whole page gets written,
3315 // ie the short cache for this page is no longer valid.
3316 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3318 if(object->myDev->nShortOpCaches > 0)
3320 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3324 cache->object = NULL;
3330 // Invalidate all the cache pages associated with this object
3331 // Do this whenever ther file is deleted or resized.
3332 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3335 yaffs_Device *dev = in->myDev;
3337 if(dev->nShortOpCaches > 0)
3339 // Now invalidate it.
3340 for(i = 0; i < dev->nShortOpCaches; i++)
3342 if(dev->srCache[i].object == in)
3344 dev->srCache[i].object = NULL;
3354 ///////////////////////// File read/write ///////////////////////////////
3355 // Read and write have very similar structures.
3356 // In general the read/write has three parts to it
3357 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3358 // * Some complete chunks
3359 // * An incomplete chunk to end off with
3361 // Curve-balls: the first chunk might also be the last chunk.
3363 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3372 yaffs_ChunkCache *cache;
3380 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
3381 start = offset % YAFFS_BYTES_PER_CHUNK;
3383 // OK now check for the curveball where the start and end are in
3385 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3391 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3394 cache = yaffs_FindChunkCache(in,chunk);
3396 // If the chunk is already in the cache or it is less than a whole chunk
3397 // then use the cache (if there is caching)
3398 // else bypass the cache.
3399 if( cache || nToCopy != YAFFS_BYTES_PER_CHUNK)
3401 if(dev->nShortOpCaches > 0)
3404 // If we can't find the data in the cache, then load it up.
3408 cache = yaffs_GrabChunkCache(in->myDev);
3410 cache->chunkId = chunk;
3412 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3416 yaffs_UseChunkCache(dev,cache,0);
3418 memcpy(buffer,&cache->data[start],nToCopy);
3422 // Read into the local buffer then copy...
3423 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3424 memcpy(buffer,&dev->localBuffer[start],nToCopy);
3430 #ifdef CONFIG_YAFFS_WINCE
3432 // Under WinCE can't do direct transfer. Need to use a local buffer.
3433 // This is because we otherwise screw up WinCE's memory mapper
3434 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3435 memcpy(buffer,dev->localBuffer,YAFFS_BYTES_PER_CHUNK);
3437 // A full chunk. Read directly into the supplied buffer.
3438 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3454 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3463 int startOfWrite = offset;
3464 int chunkWritten = 0;
3472 while(n > 0 && chunkWritten >= 0)
3474 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
3475 start = offset % YAFFS_BYTES_PER_CHUNK;
3478 // OK now check for the curveball where the start and end are in
3481 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3485 // Now folks, to calculate how many bytes to write back....
3486 // If we're overwriting and not writing to then end of file then
3487 // we need to write back as much as was there before.
3489 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
3491 if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
3493 nBytesRead = YAFFS_BYTES_PER_CHUNK;
3496 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3501 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3502 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3505 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3507 // An incomplete start or end chunk (or maybe both start and end chunk)
3508 if(dev->nShortOpCaches > 0)
3510 yaffs_ChunkCache *cache;
3511 // If we can't find the data in the cache, then load it up.
3512 cache = yaffs_FindChunkCache(in,chunk);
3513 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3515 cache = yaffs_GrabChunkCache(in->myDev);
3517 cache->chunkId = chunk;
3519 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3524 yaffs_UseChunkCache(dev,cache,1);
3525 memcpy(&cache->data[start],buffer,nToCopy);
3526 cache->nBytes = nToWriteBack;
3530 chunkWritten = -1; // fail the write
3535 // An incomplete start or end chunk (or maybe both start and end chunk)
3536 // Read into the local buffer then copy, then copy over and write back.
3538 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3540 memcpy(&dev->localBuffer[start],buffer,nToCopy);
3542 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,nToWriteBack,0);
3544 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3551 #ifdef CONFIG_YAFFS_WINCE
3552 // Under WinCE can't do direct transfer. Need to use a local buffer.
3553 // This is because we otherwise screw up WinCE's memory mapper
3554 memcpy(dev->localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3555 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3557 // A full chunk. Write directly from the supplied buffer.
3558 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3560 // Since we've overwritten the cached data, we better invalidate it.
3561 yaffs_InvalidateChunkCache(in,chunk);
3562 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3565 if(chunkWritten >= 0)
3575 // Update file object
3577 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3579 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3588 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3592 int oldFileSize = in->variant.fileVariant.fileSize;
3593 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3595 yaffs_Device *dev = in->myDev;
3598 yaffs_FlushFilesChunkCache(in);
3599 yaffs_InvalidateWholeChunkCache(in);
3601 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3603 return yaffs_GetFileSize(in);
3606 if(newSize < oldFileSize)
3609 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3611 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3612 YAFFS_BYTES_PER_CHUNK;
3614 // Delete backwards so that we don't end up with holes if
3615 // power is lost part-way through the operation.
3616 for(i = lastDel; i >= startDel; i--)
3618 // NB this could be optimised somewhat,
3619 // eg. could retrieve the tags and write them without
3620 // using yaffs_DeleteChunk
3622 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3623 if(chunkId <= 0 || chunkId >= (dev->endBlock * 32))
3625 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3630 yaffs_DeleteChunk(dev,chunkId,1);
3635 if(sizeOfPartialChunk != 0)
3637 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3639 // Got to read and rewrite the last chunk with its new size.
3640 yaffs_ReadChunkDataFromObject(in,lastChunk,dev->localBuffer);
3642 yaffs_WriteChunkDataToObject(in,lastChunk,dev->localBuffer,sizeOfPartialChunk,1);
3646 in->variant.fileVariant.fileSize = newSize;
3648 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3660 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3662 obj = yaffs_GetEquivalentObject(obj);
3664 switch(obj->variantType)
3666 case YAFFS_OBJECT_TYPE_FILE:
3667 return obj->variant.fileVariant.fileSize;
3668 case YAFFS_OBJECT_TYPE_SYMLINK:
3669 return strlen(obj->variant.symLinkVariant.alias);
3677 // yaffs_FlushFile() updates the file's
3680 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
3685 //T(("flushing object header\n"));
3687 yaffs_FlushFilesChunkCache(in);
3690 #ifdef CONFIG_YAFFS_WINCE
3691 yfsd_WinFileTimeNow(in->win_mtime);
3693 in->st_mtime = CURRENT_TIME;
3697 retVal = (yaffs_UpdateObjectHeader(in,NULL,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
3709 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3712 // First off, invalidate the file's data in the cache, without flushing.
3713 yaffs_InvalidateWholeChunkCache(in);
3715 yaffs_RemoveObjectFromDirectory(in);
3716 yaffs_DeleteChunk(in->myDev,in->chunkId,1);
3720 in->myInode->u.generic_ip = NULL;
3724 yaffs_FreeObject(in);
3729 // yaffs_DeleteFile deletes the whole file data
3730 // and the inode associated with the file.
3731 // It does not delete the links associated with the file.
3732 static int yaffs_UnlinkFile(yaffs_Object *in)
3735 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3737 // Delete the file data & tnodes
3739 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3742 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3744 return yaffs_DoGenericObjectDeletion(in);
3747 int immediateDeletion=0;
3748 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3749 if(1 || // Ignore the result of the change name. This will only fail
3750 // if the disk was completely full (an error condition)
3751 // We ignore the error so we can delete files to recover the disk
3755 //in->myDev->nUnlinkedFiles++;
3756 //in->renameAllowed = 0;
3760 immediateDeletion = 1;
3766 immediateDeletion = 1;
3771 if(immediateDeletion)
3773 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3775 in->myDev->nDeletedFiles++;
3776 yaffs_SoftDeleteFile(in);
3786 int yaffs_DeleteFile(yaffs_Object *in)
3788 int retVal = YAFFS_OK;
3790 if(in->nDataChunks > 0)
3792 // Use soft deletion
3795 retVal = yaffs_UnlinkFile(in);
3797 if(retVal == YAFFS_OK &&
3802 in->myDev->nDeletedFiles++;
3803 yaffs_SoftDeleteFile(in);
3805 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3809 // The file has no data chunks so we toss it immediately
3810 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3811 in->variant.fileVariant.top = NULL;
3812 yaffs_DoGenericObjectDeletion(in);
3818 static int yaffs_DeleteDirectory(yaffs_Object *in)
3820 //First check that the directory is empty.
3821 if(list_empty(&in->variant.directoryVariant.children))
3823 return yaffs_DoGenericObjectDeletion(in);
3830 static int yaffs_DeleteSymLink(yaffs_Object *in)
3832 YFREE(in->variant.symLinkVariant.alias);
3834 return yaffs_DoGenericObjectDeletion(in);
3837 static int yaffs_DeleteHardLink(yaffs_Object *in)
3839 // remove this hardlink from the list assocaited with the equivalent
3841 list_del(&in->hardLinks);
3842 return yaffs_DoGenericObjectDeletion(in);
3846 static void yaffs_AbortHalfCreatedObject(yaffs_Object *obj)
3848 switch(obj->variantType)
3850 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
3851 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
3852 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
3853 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
3854 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
3855 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
3860 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3864 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3866 return yaffs_DeleteHardLink(obj);
3868 else if(!list_empty(&obj->hardLinks))
3870 // Curve ball: We're unlinking an object that has a hardlink.
3872 // This problem arises because we are not strictly following
3873 // The Linux link/inode model.
3875 // We can't really delete the object.
3876 // Instead, we do the following:
3877 // - Select a hardlink.
3878 // - Unhook it from the hard links
3879 // - Unhook it from its parent directory (so that the rename can work)
3880 // - Rename the object to the hardlink's name.
3881 // - Delete the hardlink
3886 char name[YAFFS_MAX_NAME_LENGTH+1];
3888 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3890 list_del_init(&hl->hardLinks);
3891 list_del_init(&hl->siblings);
3893 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3895 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3897 if(retVal == YAFFS_OK)
3899 retVal = yaffs_DoGenericObjectDeletion(hl);
3906 switch(obj->variantType)
3908 case YAFFS_OBJECT_TYPE_FILE:
3909 return yaffs_UnlinkFile(obj);
3911 case YAFFS_OBJECT_TYPE_DIRECTORY:
3912 return yaffs_DeleteDirectory(obj);
3914 case YAFFS_OBJECT_TYPE_SYMLINK:
3915 return yaffs_DeleteSymLink(obj);
3917 case YAFFS_OBJECT_TYPE_HARDLINK:
3918 case YAFFS_OBJECT_TYPE_UNKNOWN:
3925 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3929 obj = yaffs_FindObjectByName(dir,name);
3931 if(obj && obj->unlinkAllowed)
3933 return yaffs_UnlinkWorker(obj);
3940 //////////////// Initialisation Scanning /////////////////
3944 // For now we use the SmartMedia check.
3945 // We look at the blockStatus byte in the first two chunks
3946 // These must be 0xFF to pass as OK.
3947 // todo: this function needs to be modifyable foir different NAND types
3948 // and different chunk sizes. Suggest make this into a per-device configurable
3950 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3954 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&spare,1);
3956 if(yaffs_CountBits(spare.blockStatus) < 7)
3961 if(spare.blockStatus != 0xFF)
3966 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
3969 if(yaffs_CountBits(spare.blockStatus) < 7)
3974 if(spare.blockStatus != 0xFF)
3984 static int yaffs_Scan(yaffs_Device *dev)
3992 yaffs_BlockState state;
3993 yaffs_Object *hardList = NULL;
3995 yaffs_BlockInfo *bi;
3998 yaffs_ObjectHeader *oh;
4000 yaffs_Object *parent;
4002 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
4005 // Scan all the blocks...
4007 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
4010 bi = yaffs_GetBlockInfo(dev,blk);
4011 yaffs_ClearChunkBits(dev,blk);
4013 bi->softDeletions = 0;
4014 state = YAFFS_BLOCK_STATE_SCANNING;
4017 if(yaffs_IsBlockBad(dev,blk))
4019 state = YAFFS_BLOCK_STATE_DEAD;
4020 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
4023 // Read each chunk in the block.
4025 for(c = 0; c < dev->nChunksPerBlock &&
4026 state == YAFFS_BLOCK_STATE_SCANNING; c++)
4028 // Read the spare area and decide what to do
4029 chunk = blk * dev->nChunksPerBlock + c;
4031 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
4034 // This block looks ok, now what's in this chunk?
4035 yaffs_GetTagsFromSpare(dev,&spare,&tags);
4037 if(yaffs_CountBits(spare.pageStatus) < 6)
4041 dev->nFreeChunks ++;
4042 //T((" %d %d deleted\n",blk,c));
4044 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
4046 // An unassigned chunk in the block
4047 // This means that either the block is empty or
4048 // this is the one being allocated from
4052 // the block is unused
4053 state = YAFFS_BLOCK_STATE_EMPTY;
4054 dev->nErasedBlocks++;
4058 // this is the block being allocated from
4059 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4060 state = YAFFS_BLOCK_STATE_ALLOCATING;
4061 dev->allocationBlock = blk;
4062 dev->allocationPage = c;
4065 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4067 else if(tags.chunkId > 0)
4071 yaffs_SetChunkBit(dev,blk,c);
4074 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4075 // PutChunkIntoFIle checks for a clash (two data chunks with
4076 // the same chunkId).
4077 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4078 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
4079 if(in->variant.fileVariant.scannedFileSize <endpos)
4081 in->variant.fileVariant.scannedFileSize = endpos;
4082 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4083 in->variant.fileVariant.fileSize =
4084 in->variant.fileVariant.scannedFileSize;
4088 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4092 // chunkId == 0, so it is an ObjectHeader.
4093 // Thus, we read in the object header and make the object
4094 yaffs_SetChunkBit(dev,blk,c);
4097 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
4099 oh = (yaffs_ObjectHeader *)chunkData;
4101 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4105 // We have already filled this one. We have a duplicate and need to resolve it.
4107 unsigned existingSerial = in->serial;
4108 unsigned newSerial = tags.serialNumber;
4110 if(((existingSerial+1) & 3) == newSerial)
4112 // Use new one - destroy the exisiting one
4113 yaffs_DeleteChunk(dev,in->chunkId,1);
4118 // Use existing - destroy this one.
4119 yaffs_DeleteChunk(dev,chunk,1);
4124 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4125 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4127 // We only load some info, don't fiddle with directory structure
4129 in->variantType = oh->type;
4131 in->st_mode = oh->st_mode;
4132 #ifdef CONFIG_YAFFS_WINCE
4133 in->win_atime[0] = oh->win_atime[0];
4134 in->win_ctime[0] = oh->win_ctime[0];
4135 in->win_mtime[0] = oh->win_mtime[0];
4136 in->win_atime[1] = oh->win_atime[1];
4137 in->win_ctime[1] = oh->win_ctime[1];
4138 in->win_mtime[1] = oh->win_mtime[1];
4140 in->st_uid = oh->st_uid;
4141 in->st_gid = oh->st_gid;
4142 in->st_atime = oh->st_atime;
4143 in->st_mtime = oh->st_mtime;
4144 in->st_ctime = oh->st_ctime;
4145 in->st_rdev = oh->st_rdev;
4147 in->chunkId = chunk;
4152 // we need to load this info
4155 in->variantType = oh->type;
4157 in->st_mode = oh->st_mode;
4158 #ifdef CONFIG_YAFFS_WINCE
4159 in->win_atime[0] = oh->win_atime[0];
4160 in->win_ctime[0] = oh->win_ctime[0];
4161 in->win_mtime[0] = oh->win_mtime[0];
4162 in->win_atime[1] = oh->win_atime[1];
4163 in->win_ctime[1] = oh->win_ctime[1];
4164 in->win_mtime[1] = oh->win_mtime[1];
4166 in->st_uid = oh->st_uid;
4167 in->st_gid = oh->st_gid;
4168 in->st_atime = oh->st_atime;
4169 in->st_mtime = oh->st_mtime;
4170 in->st_ctime = oh->st_ctime;
4171 in->st_rdev = oh->st_rdev;
4173 in->chunkId = chunk;
4175 yaffs_SetObjectName(in,oh->name);
4178 // directory stuff...
4179 // hook up to parent
4181 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4182 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4184 // Set up as a directory
4185 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4186 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4188 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4190 // Hoosterman, another problem....
4191 // We're trying to use a non-directory as a directory
4193 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan" TENDSTR)));
4197 yaffs_AddObjectToDirectory(parent,in);
4198 if(parent == dev->unlinkedDir)
4200 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4201 dev->nDeletedFiles++;
4204 // Note re hardlinks.
4205 // Since we might scan a hardlink before its equivalent object is scanned
4206 // we put them all in a list.
4207 // After scanning is complete, we should have all the objects, so we run through this
4208 // list and fix up all the chains.
4210 switch(in->variantType)
4212 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4214 case YAFFS_OBJECT_TYPE_FILE:
4215 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
4216 in->variant.fileVariant.fileSize = oh->fileSize;
4219 case YAFFS_OBJECT_TYPE_HARDLINK:
4220 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4221 in->hardLinks.next = (struct list_head *)hardList;
4224 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4226 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4228 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4229 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4232 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4237 if(state == YAFFS_BLOCK_STATE_SCANNING)
4239 // If we got this far while scanning, then the block is fully allocated.
4240 state = YAFFS_BLOCK_STATE_FULL;
4243 bi->blockState = state;
4245 // Now let's see if it was dirty
4246 if( bi->pagesInUse == 0 &&
4247 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4249 yaffs_BlockBecameDirty(dev,blk);
4254 // Fix up the hard link chains.
4255 // We should now have scanned all the objects, now it's time to add these
4260 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4262 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4266 // Add the hardlink pointers
4267 hl->variant.hardLinkVariant.equivalentObject=in;
4268 list_add(&hl->hardLinks,&in->hardLinks);
4272 //Todo Need to report/handle this better.
4273 // Got a problem... hardlink to a non-existant object
4274 hl->variant.hardLinkVariant.equivalentObject=NULL;
4275 INIT_LIST_HEAD(&hl->hardLinks);
4282 struct list_head *i;
4283 struct list_head *n;
4286 // Soft delete all the unlinked files
4287 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
4291 l = list_entry(i, yaffs_Object,siblings);
4294 yaffs_SoftDeleteFile(l);
4305 ////////////////////////// Directory Functions /////////////////////////
4308 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
4311 if(obj->siblings.prev == NULL)
4314 INIT_LIST_HEAD(&obj->siblings);
4317 else if(!list_empty(&obj->siblings))
4319 // If it is holed up somewhere else, un hook it
4320 list_del_init(&obj->siblings);
4323 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
4324 obj->parent = directory;
4326 if(directory == obj->myDev->unlinkedDir)
4329 obj->myDev->nUnlinkedFiles++;
4330 obj->renameAllowed = 0;
4334 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4336 list_del_init(&obj->siblings);
4340 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
4344 struct list_head *i;
4345 char buffer[YAFFS_MAX_NAME_LENGTH+1];
4349 sum = yaffs_CalcNameSum(name);
4351 list_for_each(i,&directory->variant.directoryVariant.children)
4355 l = list_entry(i, yaffs_Object,siblings);
4357 // Special case for lost-n-found
4358 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4360 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
4365 else if(yaffs_SumCompare(l->sum, sum))
4368 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
4369 if(yaffs_strcmp(name,buffer) == 0)
4382 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
4384 struct list_head *i;
4388 list_for_each(i,&theDir->variant.directoryVariant.children)
4392 l = list_entry(i, yaffs_Object,siblings);
4405 // GetEquivalentObject dereferences any hard links to get to the
4408 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4410 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4412 // We want the object id of the equivalent object, not this one
4413 obj = obj->variant.hardLinkVariant.equivalentObject;
4419 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
4421 memset(name,0,buffSize);
4423 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4425 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
4427 else if(obj->chunkId <= 0)
4431 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
4432 strncpy(name,locName,buffSize - 1);
4435 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4436 else if(obj->shortName[0])
4438 strcpy(name,obj->shortName);
4443 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4444 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4446 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4448 if(obj->chunkId >= 0)
4450 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
4452 strncpy(name,oh->name,buffSize - 1);
4455 return strlen(name);
4458 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4461 // Dereference any hard linking
4462 obj = yaffs_GetEquivalentObject(obj);
4464 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4466 return obj->variant.fileVariant.fileSize;
4468 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4470 return strlen(obj->variant.symLinkVariant.alias);
4474 // Only a directory should drop through to here
4475 return YAFFS_BYTES_PER_CHUNK;
4479 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4482 struct list_head *i;
4486 count++; // the object itself
4488 list_for_each(i,&obj->hardLinks)
4490 count++; // add the hard links;
4497 int yaffs_GetObjectInode(yaffs_Object *obj)
4499 obj = yaffs_GetEquivalentObject(obj);
4501 return obj->objectId;
4504 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4506 obj = yaffs_GetEquivalentObject(obj);
4508 switch(obj->variantType)
4510 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
4511 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
4512 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
4513 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
4514 case YAFFS_OBJECT_TYPE_SPECIAL:
4515 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
4516 if(S_ISCHR(obj->st_mode)) return DT_CHR;
4517 if(S_ISBLK(obj->st_mode)) return DT_BLK;
4518 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
4519 default: return DT_REG; break;
4523 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4525 obj = yaffs_GetEquivalentObject(obj);
4526 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4528 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4532 return yaffs_CloneString("");
4536 #ifndef CONFIG_YAFFS_WINCE
4538 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4540 unsigned int valid = attr->ia_valid;
4542 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4543 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4544 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4546 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
4547 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
4548 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
4550 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4552 yaffs_UpdateObjectHeader(obj,NULL,1);
4557 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4559 unsigned int valid = 0;
4561 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
4562 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
4563 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
4565 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
4566 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
4567 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
4569 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4571 attr->ia_valid = valid;
4579 int yaffs_DumpObject(yaffs_Object *obj)
4581 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4583 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4585 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4587 // if(obj->chunkId >= 0)
4589 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4592 yaffs_GetObjectName(obj,name,256);
4594 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),
4595 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
4596 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4599 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4600 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
4601 obj->sum, obj->chunkId));
4602 switch(obj->variantType)
4604 case YAFFS_OBJECT_TYPE_FILE:
4605 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4607 case YAFFS_OBJECT_TYPE_DIRECTORY:
4608 YPRINTF((" DIRECTORY\n"));
4610 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4611 case YAFFS_OBJECT_TYPE_SYMLINK:
4612 case YAFFS_OBJECT_TYPE_UNKNOWN:
4621 ///////////////////////// Initialisation code ///////////////////////////
4625 int yaffs_GutsInitialise(yaffs_Device *dev)
4632 if( dev->nBytesPerChunk != YAFFS_BYTES_PER_CHUNK ||
4634 dev->nChunksPerBlock < 2 ||
4635 dev->nReservedBlocks < 2 ||
4636 dev->startBlock <= 0 ||
4637 dev->endBlock <= 0 ||
4638 dev->endBlock <= (dev->startBlock + dev->nReservedBlocks)
4641 //these parameters must be set before stating yaffs
4642 // Other parameters startBlock,
4648 if(!yaffs_CheckStructures())
4650 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
4656 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
4662 if(dev->startBlock <= 0 ||
4663 (dev->endBlock - dev->startBlock) < 10)
4665 T(YAFFS_TRACE_ALWAYS,(TSTR("startBlock %d or endBlock %d invalid\n" TENDSTR),
4666 dev->startBlock, dev->endBlock));
4670 nBlocks = dev->endBlock - dev->startBlock + 1;
4674 // OK now calculate a few things for the device
4675 // Calculate chunkGroupBits.
4676 // We need to find the next power of 2 > than endBlock
4678 x = dev->nChunksPerBlock * (dev->endBlock+1);
4680 for(bits = extraBits = 0; x > 1; bits++)
4682 if(x & 1) extraBits++;
4686 if(extraBits > 0) bits++;
4689 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4690 // chunk range we're using is greater than 16 we need
4691 // to figure out chunk shift and chunkGroupSize
4694 dev->chunkGroupBits = 0;
4698 dev->chunkGroupBits = bits - 16;
4700 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4704 // More device initialisation
4705 dev->garbageCollections = 0;
4706 dev->passiveGarbageCollections = 0;
4707 dev->currentDirtyChecker = 0;
4708 dev->bufferedBlock = -1;
4709 dev->doingBufferedBlockRewrite = 0;
4710 dev->nDeletedFiles = 0;
4711 dev->nBackgroundDeletions=0;
4712 dev->nUnlinkedFiles = 0;
4715 dev->tagsEccFixed=0;
4716 dev->tagsEccUnfixed=0;
4718 dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
4723 yaffs_InitialiseBlocks(dev,nBlocks);
4725 yaffs_InitialiseTnodes(dev);
4727 yaffs_InitialiseObjects(dev);
4729 if(dev->nShortOpCaches > 0)
4733 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
4735 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
4738 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
4740 for(i=0; i < dev->nShortOpCaches; i++)
4742 dev->srCache[i].object = NULL;
4743 dev->srCache[i].lastUse = 0;
4744 dev->srCache[i].dirty = 0;
4752 // Initialise the unlinked, root and lost and found directories
4753 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4755 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4757 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4758 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4759 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4762 // Now scan the flash.
4766 dev->nPageReads = 0;
4767 dev->nPageWrites = 0;
4768 dev->nBlockErasures = 0;
4770 dev->nRetriedWrites = 0;
4771 dev->nRetiredBlocks = 0;
4778 void yaffs_Deinitialise(yaffs_Device *dev)
4783 yaffs_DeinitialiseBlocks(dev);
4784 yaffs_DeinitialiseTnodes(dev);
4785 yaffs_DeinitialiseObjects(dev);
4786 YFREE(dev->localBuffer);
4793 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4795 int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
4797 struct list_head *i;
4801 // To the free chunks add the chunks that are in the deleted unlinked files.
4802 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4804 l = list_entry(i, yaffs_Object,siblings);
4808 nFree += l->nDataChunks;
4813 // printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
4815 if(nFree < 0) nFree = 0;
4823 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4829 yaffs_BlockInfo *blk;
4831 struct list_head *i;
4834 for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
4836 blk = yaffs_GetBlockInfo(dev,b);
4838 switch(blk->blockState)
4840 case YAFFS_BLOCK_STATE_EMPTY:
4841 case YAFFS_BLOCK_STATE_ALLOCATING:
4842 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
4850 // To the free chunks add the chunks that are in the deleted unlinked files.
4851 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4855 l = list_entry(i, yaffs_Object,siblings);
4859 pending += l->nDataChunks;
4866 //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
4868 if(nFree != dev->nFreeChunks)
4870 // printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
4875 if(nFree < 0) nFree = 0;
4883 /////////////////// YAFFS test code //////////////////////////////////
4885 #define yaffs_CheckStruct(structure,syze, name) \
4886 if(sizeof(structure) != syze) \
4888 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
4889 return YAFFS_FAIL; \
4893 static int yaffs_CheckStructures(void)
4895 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4896 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4897 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4898 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
4899 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4901 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4908 void yaffs_GutsTest(yaffs_Device *dev)
4911 if(yaffs_CheckStructures() != YAFFS_OK)
4913 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
4917 yaffs_TnodeTest(dev);
4918 yaffs_ObjectTest(dev);