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 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
16 const char *yaffs_guts_c_version="$Id: yaffs_guts.c,v 1.2 2004-11-16 02:36:15 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
23 #include "yaffs_tagscompat.h"
25 #ifdef CONFIG_YAFFS_WINCE
26 void yfsd_LockYAFFS(BOOL fsLockOnly);
27 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
30 #define YAFFS_PASSIVE_GC_CHUNKS 2
33 // Use Steven Hill's ECC struff instead
34 // External functions for ECC on data
35 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
36 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
37 #define yaffs_ECCCalculate(data,ecc) nand_calculate_ecc(data,ecc)
38 #define yaffs_ECCCorrect(data,read_ecc,calc_ecc) nand_correct_ecc(data,read_ecc,calc_ecc)
40 #include "yaffs_ecc.h"
43 // countBits is a quick way of counting the number of bits in a byte.
44 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
46 static const char yaffs_countBitsTable[256] =
48 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
49 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
50 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
51 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
52 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
53 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
54 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
55 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
56 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
57 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
58 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
59 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
60 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
61 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
62 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
63 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
66 static int yaffs_CountBits(__u8 x)
69 retVal = yaffs_countBitsTable[x];
75 // Stuff using yea olde tags
76 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
77 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
79 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
80 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
87 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *buffer, yaffs_ExtendedTags *tags);
88 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *data, yaffs_ExtendedTags *tags);
89 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo);
90 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device *dev,int blockNo, yaffs_BlockState *state,unsigned *sequenceNumber);
92 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_ExtendedTags *tags, int useReserve);
93 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
94 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
96 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
97 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
98 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const YCHAR *name, int force,int isShrink);
99 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
100 static int yaffs_CheckStructures(void);
101 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
102 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
104 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
106 static __u8 *yaffs_GetTempBuffer(yaffs_Device *dev,int lineNo);
107 static void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo);
110 static int yaffs_ValidateTags(yaffs_ExtendedTags *tags);
112 // Robustification (if it ever comes about...)
113 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
114 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
115 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
116 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_ExtendedTags *tags);
117 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_ExtendedTags *tags);
119 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
121 static int yaffs_UnlinkWorker(yaffs_Object *obj);
122 static void yaffs_DestroyObject(yaffs_Object *obj);
125 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1,int dataSize);
128 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId, int chunkInObject);
131 loff_t yaffs_GetFileSize(yaffs_Object *obj);
134 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
136 #ifdef YAFFS_PARANOID
137 static int yaffs_CheckFileSanity(yaffs_Object *in);
139 #define yaffs_CheckFileSanity(in)
142 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
143 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
145 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *buffer, yaffs_ExtendedTags *tags)
147 if(dev->readChunkWithTagsFromNAND)
148 return dev->readChunkWithTagsFromNAND(dev,chunkInNAND,buffer,tags);
150 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,tags);
153 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_ExtendedTags *tags)
157 tags->sequenceNumber = dev->sequenceNumber;
159 if(!yaffs_ValidateTags(tags))
161 T(YAFFS_TRACE_ERROR,(TSTR("Writing uninitialised tags" TENDSTR)));
164 T(YAFFS_TRACE_WRITE,(TSTR("Writing chunk %d tags %d %d"TENDSTR),chunkInNAND,tags->objectId,tags->chunkId));
168 T(YAFFS_TRACE_ERROR,(TSTR("Writing with no tags" TENDSTR)));
172 if(dev->writeChunkWithTagsToNAND)
173 return dev->writeChunkWithTagsToNAND(dev,chunkInNAND,buffer,tags);
175 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,chunkInNAND,buffer,tags);
178 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo)
180 if(dev->markNANDBlockBad)
181 return dev->markNANDBlockBad(dev,blockNo);
183 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev,blockNo);
185 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device *dev,int blockNo, yaffs_BlockState *state, unsigned *sequenceNumber)
187 if(dev->queryNANDBlock)
188 return dev->queryNANDBlock(dev,blockNo,state,sequenceNumber);
190 return yaffs_TagsCompatabilityQueryNANDBlock(dev,blockNo,state,sequenceNumber);
193 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
197 dev->nBlockErasures++;
198 result = dev->eraseBlockInNAND(dev,blockInNAND);
200 if(!result)result = dev->eraseBlockInNAND(dev,blockInNAND); // If at first we don't succeed, try again *once*.
204 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
206 return dev->initialiseNAND(dev);
212 // Temporary buffer manipulations
214 static __u8 *yaffs_GetTempBuffer(yaffs_Device *dev,int lineNo)
217 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
219 if(dev->tempBuffer[i].line == 0)
221 dev->tempBuffer[i].line = lineNo;
222 if((i+1) > dev->maxTemp)
224 dev->maxTemp = i + 1;
225 for(j = 0; j <= i; j++)
226 dev->tempBuffer[j].maxLine = dev->tempBuffer[j].line;
229 return dev->tempBuffer[i].buffer;
233 T(YAFFS_TRACE_BUFFERS,(TSTR("Out of temp buffers at line %d, other held by lines:"),lineNo));
234 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
236 T(YAFFS_TRACE_BUFFERS,(TSTR(" %d "),dev->tempBuffer[i].line));
238 T(YAFFS_TRACE_BUFFERS,(TSTR(" "TENDSTR)));
240 dev->unmanagedTempAllocations++;
241 // Get an unmanaged one
242 return YMALLOC(dev->nBytesPerChunk);
247 static void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo)
250 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
252 if(dev->tempBuffer[i].buffer == buffer)
254 dev->tempBuffer[i].line = 0;
261 // assume it is an unmanaged one.
262 T(YAFFS_TRACE_BUFFERS,(TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),lineNo));
264 dev->unmanagedTempDeallocations++;
270 // Chunk bitmap manipulations
272 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
274 if(blk < dev->startBlock || blk > dev->endBlock)
276 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
279 return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->startBlock));
282 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
284 __u8 *blkBits = yaffs_BlockBits(dev,blk);
286 memset(blkBits,0,dev->chunkBitmapStride);
289 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev,int blk,int chunk)
291 __u8 *blkBits = yaffs_BlockBits(dev,blk);
293 blkBits[chunk/8] &= ~ (1<<(chunk & 7));
296 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
298 __u8 *blkBits = yaffs_BlockBits(dev,blk);
300 blkBits[chunk/8] |= (1<<(chunk & 7));
303 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
305 __u8 *blkBits = yaffs_BlockBits(dev,blk);
306 return (blkBits[chunk/8] & (1<<(chunk & 7))) ? 1 :0;
309 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
311 __u8 *blkBits = yaffs_BlockBits(dev,blk);
313 for(i = 0; i < dev->chunkBitmapStride; i++)
315 if(*blkBits) return 1;
322 // Function to manipulate block info
323 static Y_INLINE yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
325 if(blk < dev->startBlock || blk > dev->endBlock)
327 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),blk));
330 return &dev->blockInfo[blk - dev->startBlock];
335 static Y_INLINE int yaffs_HashFunction(int n)
337 return (n % YAFFS_NOBJECT_BUCKETS);
341 yaffs_Object *yaffs_Root(yaffs_Device *dev)
346 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
348 return dev->lostNFoundDir;
352 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
354 if(chunkInNAND < dev->startBlock * dev->nChunksPerBlock)
356 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
361 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
366 static int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
370 int doErrorCorrection)
373 yaffs_Spare localSpare;
382 // If we don't have a real spare, then we use a local one.
383 // Need this for the calculation of the ecc
390 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
391 if(data && doErrorCorrection)
394 //Todo handle any errors
395 int eccResult1,eccResult2;
398 yaffs_ECCCalculate(data,calcEcc);
399 eccResult1 = yaffs_ECCCorrect (data,spare->ecc1, calcEcc);
400 yaffs_ECCCalculate(&data[256],calcEcc);
401 eccResult2 = yaffs_ECCCorrect(&data[256],spare->ecc2, calcEcc);
405 T(YAFFS_TRACE_ERROR, (TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
408 else if(eccResult1<0)
410 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
416 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
419 else if(eccResult2<0)
421 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
425 if(eccResult1 || eccResult2)
427 // Hoosterman, we had a data problem on this page
428 yaffs_HandleReadDataError(dev,chunkInNAND);
434 // Must allocate enough memory for spare+2*sizeof(int) for ecc results from device.
435 struct yaffs_NANDSpare nspare;
436 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
437 memcpy (spare, &nspare, sizeof(yaffs_Spare));
438 if(data && doErrorCorrection)
442 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
444 else if(nspare.eccres1<0)
446 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
451 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
453 else if(nspare.eccres2<0)
455 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
458 if(nspare.eccres1 || nspare.eccres2)
460 // Hoosterman, we had a data problem on this page
461 yaffs_HandleReadDataError(dev,chunkInNAND);
473 int yaffs_CheckFF(__u8 *buffer,int nBytes)
475 //Horrible, slow implementation
478 if(*buffer != 0xFF) return 0;
483 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
486 int retval = YAFFS_OK;
487 __u8 *data = yaffs_GetTempBuffer(dev,__LINE__);
488 yaffs_ExtendedTags tags;
490 dev->readChunkWithTagsFromNAND(dev,chunkInNAND,data,&tags);
492 if(!yaffs_CheckFF(data,dev->nBytesPerChunk) || tags.chunkUsed)
494 T(YAFFS_TRACE_NANDACCESS,(TSTR("Chunk %d not erased" TENDSTR),chunkInNAND));
498 yaffs_ReleaseTempBuffer(dev,data,__LINE__);
507 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_ExtendedTags *tags,int useReserve)
517 chunk = yaffs_AllocateChunk(dev,useReserve);
522 // First check this chunk is erased...
523 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
524 writeOk = yaffs_CheckChunkErased(dev,chunk);
528 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
532 writeOk = yaffs_WriteChunkWithTagsToNAND(dev,chunk,data,tags);
538 // Copy the data into the robustification buffer.
539 // NB We do this at the end to prevent duplicates in the case of a write error.
541 yaffs_HandleWriteChunkOk(dev,chunk,data,tags);
545 yaffs_HandleWriteChunkError(dev,chunk);
549 } while(chunk >= 0 && ! writeOk);
553 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
554 dev->nRetriedWrites+= (attempts - 1);
565 // Functions for robustisizing
569 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
572 yaffs_MarkBlockBad(dev,blockInNAND);
574 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
576 dev->nRetiredBlocks++;
581 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
583 dev->doingBufferedBlockRewrite = 1;
585 // Remove erased chunks
586 // Rewrite existing chunks to a new block
587 // Set current write block to the new block
589 dev->doingBufferedBlockRewrite = 0;
595 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
597 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
599 // Mark the block for retirement
600 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
601 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
605 // Just do a garbage collection on the affected block then retire the block
610 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
614 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_ExtendedTags *tags)
618 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_ExtendedTags *tags)
622 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
624 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
626 // Mark the block for retirement
627 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
629 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
635 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1,int dataSize)
639 if( memcmp(d0,d1,dataSize) != 0 ||
640 s0->tagByte0 != s1->tagByte0 ||
641 s0->tagByte1 != s1->tagByte1 ||
642 s0->tagByte2 != s1->tagByte2 ||
643 s0->tagByte3 != s1->tagByte3 ||
644 s0->tagByte4 != s1->tagByte4 ||
645 s0->tagByte5 != s1->tagByte5 ||
646 s0->tagByte6 != s1->tagByte6 ||
647 s0->tagByte7 != s1->tagByte7 ||
648 s0->ecc1[0] != s1->ecc1[0] ||
649 s0->ecc1[1] != s1->ecc1[1] ||
650 s0->ecc1[2] != s1->ecc1[2] ||
651 s0->ecc2[0] != s1->ecc2[0] ||
652 s0->ecc2[1] != s1->ecc2[1] ||
653 s0->ecc2[2] != s1->ecc2[2] )
663 ///////////////////////// Object management //////////////////
664 // List of spare objects
665 // The list is hooked together using the first pointer
668 // static yaffs_Object *yaffs_freeObjects = NULL;
670 // static int yaffs_nFreeObjects;
672 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
674 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
677 static __u16 yaffs_CalcNameSum(const YCHAR *name)
682 YUCHAR *bname = (YUCHAR *)name;
685 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
688 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
689 sum += yaffs_toupper(*bname) * i;
700 void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
702 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
703 if(name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
705 yaffs_strcpy(obj->shortName,name);
709 obj->shortName[0]=_Y('\0');
712 obj->sum = yaffs_CalcNameSum(name);
716 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
718 yaffs_ECCCalculate(data , spare->ecc1);
719 yaffs_ECCCalculate(&data[256] , spare->ecc2);
724 ///////////////////////// TNODES ///////////////////////
726 // List of spare tnodes
727 // The list is hooked together using the first pointer
730 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
732 // static int yaffs_nFreeTnodes;
734 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
738 // yaffs_CreateTnodes creates a bunch more tnodes and
739 // adds them to the tnode free list.
740 // Don't use this function directly
742 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
745 yaffs_Tnode *newTnodes;
746 yaffs_TnodeList *tnl;
748 if(nTnodes < 1) return YAFFS_OK;
752 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
756 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
760 // Hook them into the free list
761 for(i = 0; i < nTnodes - 1; i++)
763 newTnodes[i].internal[0] = &newTnodes[i+1];
764 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
765 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = 1;
769 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
770 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
771 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = 1;
773 dev->freeTnodes = newTnodes;
774 dev->nFreeTnodes+= nTnodes;
775 dev->nTnodesCreated += nTnodes;
777 // Now add this bunch of tnodes to a list for freeing up.
778 // NB If we can't add this to the management list it isn't fatal
779 // but it just means we can't free this bunch of tnodes later.
780 tnl = YMALLOC(sizeof(yaffs_TnodeList));
783 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
788 tnl->tnodes = newTnodes;
789 tnl->next = dev->allocatedTnodeList;
790 dev->allocatedTnodeList = tnl;
794 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
801 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
802 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
804 yaffs_Tnode *tn = NULL;
806 // If there are none left make more
809 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
814 tn = dev->freeTnodes;
815 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
816 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 1)
818 // Hoosterman, this thing looks like it isn't in the list
819 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 1" TENDSTR)));
822 dev->freeTnodes = dev->freeTnodes->internal[0];
825 memset(tn,0,sizeof(yaffs_Tnode));
833 // FreeTnode frees up a tnode and puts it back on the free list
834 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
838 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
839 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 0)
841 // Hoosterman, this thing looks like it is already in the list
842 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 2" TENDSTR)));
844 tn->internal[YAFFS_NTNODES_INTERNAL] = 1;
846 tn->internal[0] = dev->freeTnodes;
847 dev->freeTnodes = tn;
853 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
855 // Free the list of allocated tnodes
856 yaffs_TnodeList *tmp;
858 while(dev->allocatedTnodeList)
860 tmp = dev->allocatedTnodeList->next;
862 YFREE(dev->allocatedTnodeList->tnodes);
863 YFREE(dev->allocatedTnodeList);
864 dev->allocatedTnodeList = tmp;
868 dev->freeTnodes = NULL;
869 dev->nFreeTnodes = 0;
872 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
874 dev->allocatedTnodeList = NULL;
875 dev->freeTnodes = NULL;
876 dev->nFreeTnodes = 0;
877 dev->nTnodesCreated = 0;
882 void yaffs_TnodeTest(yaffs_Device *dev)
887 yaffs_Tnode *tn[1000];
889 YINFO("Testing TNodes");
891 for(j = 0; j < 50; j++)
893 for(i = 0; i < 1000; i++)
895 tn[i] = yaffs_GetTnode(dev);
898 YALERT("Getting tnode failed");
901 for(i = 0; i < 1000; i+=3)
903 yaffs_FreeTnode(dev,tn[i]);
912 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
914 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
915 // The look up tree is represented by the top tnode and the number of topLevel
916 // in the tree. 0 means only the level 0 tnode is in the tree.
919 // FindLevel0Tnode finds the level 0 tnode, if one exists.
920 // Used when reading.....
921 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
924 yaffs_Tnode *tn = fStruct->top;
926 int requiredTallness;
927 int level = fStruct->topLevel;
929 // Check sane level and chunk Id
930 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
933 // sprintf(str,"Bad level %d",level);
938 if(chunkId > YAFFS_MAX_CHUNK_ID)
941 // sprintf(str,"Bad chunkId %d",chunkId);
946 // First check we're tall enough (ie enough topLevel)
948 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
949 requiredTallness = 0;
952 i >>= YAFFS_TNODES_INTERNAL_BITS;
957 if(requiredTallness > fStruct->topLevel)
959 // Not tall enough, so we can't find it, return NULL.
964 // Traverse down to level 0
965 while (level > 0 && tn)
967 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
968 YAFFS_TNODES_INTERNAL_MASK];
976 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
977 // This happens in two steps:
978 // 1. If the tree isn't tall enough, then make it taller.
979 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
981 // Used when modifying the tree.
983 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
988 int requiredTallness;
995 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
997 // Check sane level and page Id
998 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1001 // sprintf(str,"Bad level %d",fStruct->topLevel);
1006 if(chunkId > YAFFS_MAX_CHUNK_ID)
1009 // sprintf(str,"Bad chunkId %d",chunkId);
1014 // First check we're tall enough (ie enough topLevel)
1016 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
1017 requiredTallness = 0;
1020 x >>= YAFFS_TNODES_INTERNAL_BITS;
1024 //T((TSTR(" required=%d"),requiredTallness));
1027 if(requiredTallness > fStruct->topLevel)
1029 // Not tall enough,gotta make the tree taller
1030 for(i = fStruct->topLevel; i < requiredTallness; i++)
1032 //T((TSTR(" add new top")));
1034 tn = yaffs_GetTnode(dev);
1038 tn->internal[0] = fStruct->top;
1043 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
1047 fStruct->topLevel = requiredTallness;
1051 // Traverse down to level 0, adding anything we need
1053 l = fStruct->topLevel;
1057 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
1058 YAFFS_TNODES_INTERNAL_MASK;
1060 //T((TSTR(" [%d:%d]"),l,i));
1062 if(!tn->internal[x])
1064 //T((TSTR(" added")));
1066 tn->internal[x] = yaffs_GetTnode(dev);
1069 tn = tn->internal[x];
1080 int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk, yaffs_ExtendedTags *tags, int objectId, int chunkInInode)
1085 for(j = 0; theChunk && j < dev->chunkGroupSize; j++)
1087 if(yaffs_CheckChunkBit(dev,theChunk / dev->nChunksPerBlock,theChunk % dev->nChunksPerBlock))
1089 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL,tags);
1090 if(yaffs_TagsMatch(tags,objectId,chunkInInode))
1102 // DeleteWorker scans backwards through the tnode tree and deletes all the
1103 // chunks and tnodes in the file
1104 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1106 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1111 yaffs_ExtendedTags tags;
1113 yaffs_Device *dev = in->myDev;
1123 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1127 if(limit && (*limit) < 0)
1133 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1134 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1138 yaffs_FreeTnode(dev,tn->internal[i]);
1139 tn->internal[i] = NULL;
1144 return (allDone) ? 1 : 0;
1150 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1155 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1157 theChunk = tn->level0[i] << dev->chunkGroupBits;
1159 foundChunk = yaffs_FindChunkInGroup(dev,theChunk,&tags,in->objectId,chunkInInode);
1163 yaffs_DeleteChunk(dev,foundChunk,1,__LINE__);
1180 return (i < 0) ? 1 : 0;
1192 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1195 yaffs_BlockInfo *theBlock;
1197 T(YAFFS_TRACE_DELETION,(TSTR("soft delete chunk %d" TENDSTR),chunk));
1199 theBlock = yaffs_GetBlockInfo(dev, chunk/dev->nChunksPerBlock);
1202 theBlock->softDeletions++;
1206 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1207 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1209 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1211 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1216 yaffs_Device *dev = in->myDev;
1224 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1228 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1229 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1232 yaffs_FreeTnode(dev,tn->internal[i]);
1233 tn->internal[i] = NULL;
1237 //Hoosterman... how could this happen.
1241 return (allDone) ? 1 : 0;
1246 for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1250 // Note this does not find the real chunk, only the chunk group.
1251 // We make an assumption that a chunk group is niot larger than a block.
1252 theChunk = (tn->level0[i] << dev->chunkGroupBits);
1254 yaffs_SoftDeleteChunk(dev,theChunk);
1271 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1274 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1277 if(obj->nDataChunks <= 0)
1279 // Empty file with no duplicate object headers, just delete it immediately
1280 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1281 obj->variant.fileVariant.top = NULL;
1282 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1283 yaffs_DoGenericObjectDeletion(obj);
1287 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1288 obj->softDeleted = 1;
1297 // Pruning removes any part of the file structure tree that is beyond the
1298 // bounds of the file (ie that does not point to chunks).
1300 // A file should only get pruned when its size is reduced.
1302 // Before pruning, the chunks must be pulled from the tree and the
1303 // level 0 tnode entries must be zeroed out.
1304 // Could also use this for file deletion, but that's probably better handled
1305 // by a special case.
1307 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1309 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1318 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1320 if(tn->internal[i] && level > 0)
1322 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1331 if(hasData == 0 && del0)
1333 // Free and return NULL
1335 yaffs_FreeTnode(dev,tn);
1345 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1352 if(fStruct->topLevel > 0)
1354 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1356 // Now we have a tree with all the non-zero branches NULL but the height
1357 // is the same as it was.
1358 // Let's see if we can trim internal tnodes to shorten the tree.
1359 // We can do this if only the 0th element in the tnode is in use
1360 // (ie all the non-zero are NULL)
1362 while(fStruct->topLevel && !done)
1367 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1377 fStruct->top = tn->internal[0];
1378 fStruct->topLevel--;
1379 yaffs_FreeTnode(dev,tn);
1395 /////////////////////// End of File Structure functions. /////////////////
1397 // yaffs_CreateFreeObjects creates a bunch more objects and
1398 // adds them to the object free list.
1399 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1402 yaffs_Object *newObjects;
1403 yaffs_ObjectList *list;
1405 if(nObjects < 1) return YAFFS_OK;
1407 // make these things
1409 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1413 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1417 // Hook them into the free list
1418 for(i = 0; i < nObjects - 1; i++)
1420 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1423 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1424 dev->freeObjects = newObjects;
1425 dev->nFreeObjects+= nObjects;
1426 dev->nObjectsCreated+= nObjects;
1428 // Now add this bunch of Objects to a list for freeing up.
1430 list = YMALLOC(sizeof(yaffs_ObjectList));
1433 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1437 list->objects = newObjects;
1438 list->next = dev->allocatedObjectList;
1439 dev->allocatedObjectList = list;
1448 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1449 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1451 yaffs_Object *tn = NULL;
1453 // If there are none left make more
1454 if(!dev->freeObjects)
1456 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1459 if(dev->freeObjects)
1461 tn = dev->freeObjects;
1462 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1463 dev->nFreeObjects--;
1465 // Now sweeten it up...
1467 memset(tn,0,sizeof(yaffs_Object));
1470 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1471 INIT_LIST_HEAD(&(tn->hardLinks));
1472 INIT_LIST_HEAD(&(tn->hashLink));
1473 INIT_LIST_HEAD(&tn->siblings);
1475 // Add it to the lost and found directory.
1476 // NB Can't put root or lostNFound in lostNFound so
1477 // check if lostNFound exists first
1478 if(dev->lostNFoundDir)
1480 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1488 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1491 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1494 obj->fake = 1; // it is fake so it has no NAND presence...
1495 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1496 obj->unlinkAllowed= 0; // ... or unlink it
1499 obj->st_mode = mode;
1501 obj->chunkId = 0; // Not a valid chunk.
1509 static void yaffs_UnhashObject(yaffs_Object *tn)
1512 yaffs_Device *dev = tn->myDev;
1515 // If it is still linked into the bucket list, free from the list
1516 if(!list_empty(&tn->hashLink))
1518 list_del_init(&tn->hashLink);
1519 bucket = yaffs_HashFunction(tn->objectId);
1520 dev->objectBucket[bucket].count--;
1526 // FreeObject frees up a Object and puts it back on the free list
1527 static void yaffs_FreeObject(yaffs_Object *tn)
1530 yaffs_Device *dev = tn->myDev;
1535 // We're still hooked up to a cached inode.
1536 // Don't delete now, but mark for later deletion
1537 tn->deferedFree = 1;
1542 yaffs_UnhashObject(tn);
1544 // Link into the free list.
1545 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1546 dev->freeObjects = tn;
1547 dev->nFreeObjects++;
1554 void yaffs_HandleDeferedFree(yaffs_Object *obj)
1556 if(obj->deferedFree)
1558 yaffs_FreeObject(obj);
1566 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1568 // Free the list of allocated Objects
1570 yaffs_ObjectList *tmp;
1572 while( dev->allocatedObjectList)
1574 tmp = dev->allocatedObjectList->next;
1575 YFREE(dev->allocatedObjectList->objects);
1576 YFREE(dev->allocatedObjectList);
1578 dev->allocatedObjectList = tmp;
1581 dev->freeObjects = NULL;
1582 dev->nFreeObjects = 0;
1585 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1589 dev->allocatedObjectList = NULL;
1590 dev->freeObjects = NULL;
1591 dev->nFreeObjects = 0;
1593 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1595 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1596 dev->objectBucket[i].count = 0;
1606 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1611 int lowest = 999999;
1614 // First let's see if we can find one that's empty.
1616 for(i = 0; i < 10 && lowest > 0; i++)
1619 x %= YAFFS_NOBJECT_BUCKETS;
1620 if(dev->objectBucket[x].count < lowest)
1622 lowest = dev->objectBucket[x].count;
1628 // If we didn't find an empty list, then try
1629 // looking a bit further for a short one
1631 for(i = 0; i < 10 && lowest > 3; i++)
1634 x %= YAFFS_NOBJECT_BUCKETS;
1635 if(dev->objectBucket[x].count < lowest)
1637 lowest = dev->objectBucket[x].count;
1646 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1648 int bucket = yaffs_FindNiceObjectBucket(dev);
1650 // Now find an object value that has not already been taken
1651 // by scanning the list.
1654 struct list_head *i;
1656 __u32 n = (__u32)bucket;
1658 //yaffs_CheckObjectHashSanity();
1663 n += YAFFS_NOBJECT_BUCKETS;
1664 if(1 ||dev->objectBucket[bucket].count > 0)
1666 list_for_each(i,&dev->objectBucket[bucket].list)
1668 // If there is already one in the list
1669 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1677 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1682 void yaffs_HashObject(yaffs_Object *in)
1684 int bucket = yaffs_HashFunction(in->objectId);
1685 yaffs_Device *dev = in->myDev;
1687 if(!list_empty(&in->hashLink))
1693 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1694 dev->objectBucket[bucket].count++;
1698 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1700 int bucket = yaffs_HashFunction(number);
1701 struct list_head *i;
1704 list_for_each(i,&dev->objectBucket[bucket].list)
1706 // Look if it is in the list
1709 in = list_entry(i, yaffs_Object,hashLink);
1710 if(in->objectId == number)
1722 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1725 yaffs_Object *theObject;
1729 number = yaffs_CreateNewObjectNumber(dev);
1732 theObject = yaffs_AllocateEmptyObject(dev);
1736 theObject->fake = 0;
1737 theObject->renameAllowed = 1;
1738 theObject->unlinkAllowed = 1;
1739 theObject->objectId = number;
1740 yaffs_HashObject(theObject);
1741 theObject->variantType = type;
1742 #ifdef CONFIG_YAFFS_WINCE
1743 yfsd_WinFileTimeNow(theObject->win_atime);
1744 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1745 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1749 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = Y_CURRENT_TIME;
1753 case YAFFS_OBJECT_TYPE_FILE:
1754 theObject->variant.fileVariant.fileSize = 0;
1755 theObject->variant.fileVariant.scannedFileSize = 0;
1756 theObject->variant.fileVariant.topLevel = 0;
1757 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1759 case YAFFS_OBJECT_TYPE_DIRECTORY:
1760 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1762 case YAFFS_OBJECT_TYPE_SYMLINK:
1763 // No action required
1765 case YAFFS_OBJECT_TYPE_HARDLINK:
1766 // No action required
1768 case YAFFS_OBJECT_TYPE_SPECIAL:
1769 // No action required
1771 case YAFFS_OBJECT_TYPE_UNKNOWN:
1772 // todo this should not happen
1780 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1782 yaffs_Object *theObject = NULL;
1786 theObject = yaffs_FindObjectByNumber(dev,number);
1791 theObject = yaffs_CreateNewObject(dev,number,type);
1798 YCHAR *yaffs_CloneString(const YCHAR *str)
1800 YCHAR *newStr = NULL;
1804 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1805 yaffs_strcpy(newStr,str);
1813 // Mknod (create) a new object.
1814 // equivalentObject only has meaning for a hard link;
1815 // aliasString only has meaning for a sumlink.
1816 // rdev only has meaning for devices (a subset of special objects)
1817 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1818 yaffs_Object *parent,
1823 yaffs_Object *equivalentObject,
1824 const YCHAR *aliasString,
1829 yaffs_Device *dev = parent->myDev;
1831 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1832 if(yaffs_FindObjectByName(parent,name))
1837 in = yaffs_CreateNewObject(dev,-1,type);
1843 in->variantType = type;
1847 #ifdef CONFIG_YAFFS_WINCE
1848 yfsd_WinFileTimeNow(in->win_atime);
1849 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1850 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1853 in->st_atime = in->st_mtime = in->st_ctime = Y_CURRENT_TIME;
1859 in->nDataChunks = 0;
1861 yaffs_SetObjectName(in,name);
1864 yaffs_AddObjectToDirectory(parent,in);
1866 in->myDev = parent->myDev;
1871 case YAFFS_OBJECT_TYPE_SYMLINK:
1872 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1874 case YAFFS_OBJECT_TYPE_HARDLINK:
1875 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1876 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1877 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1879 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1880 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1881 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1882 case YAFFS_OBJECT_TYPE_UNKNOWN:
1886 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1887 yaffs_UpdateObjectHeader(in,name,0,0) < 0)
1889 // Could not create the object header, fail the creation
1890 yaffs_DestroyObject(in);
1899 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid)
1901 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1904 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid)
1906 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1909 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1911 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1914 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid,const YCHAR *alias)
1916 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1919 // NB yaffs_Link returns the object id of the equivalent object.
1920 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name, yaffs_Object *equivalentObject)
1922 // Get the real object in case we were fed a hard link as an equivalent object
1923 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1925 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1927 return equivalentObject;
1937 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const YCHAR *newName,int force)
1944 newDir = obj->parent; // use the old directory
1947 // TODO: Do we need this different handling for YAFFS2 and YAFFS1??
1948 if(obj->myDev->isYaffs2)
1950 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1954 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1957 deleteOp = (newDir == obj->myDev->deletedDir);
1959 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1960 // duplicate names are allowed.
1961 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1965 !yaffs_FindObjectByName(newDir,newName)) &&
1966 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1968 yaffs_SetObjectName(obj,newName);
1971 yaffs_AddObjectToDirectory(newDir,obj);
1973 if(unlinkOp) obj->unlinked = 1;
1975 // If it is a dletion then we mark it as a shrink for gc purposes.
1976 if(yaffs_UpdateObjectHeader(obj,newName,0,deleteOp) >= 0)
1987 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName, yaffs_Object *newDir, const YCHAR *newName)
1992 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1993 // Special case for case insemsitive systems (eg. WinCE).
1994 // While look-up is case insensitive, the name isn't.
1995 // THerefore we might want to change x.txt to X.txt
1996 if(oldDir == newDir && yaffs_strcmp(oldName,newName) == 0)
2002 obj = yaffs_FindObjectByName(oldDir,oldName);
2003 if(obj && obj->renameAllowed)
2005 return yaffs_ChangeObjectName(obj,newDir,newName,force);
2012 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
2014 // Scan the buckets and check that the lists
2015 // have as many members as the count says there are
2018 struct list_head *j;
2021 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
2025 list_for_each(j,&dev->objectBucket[bucket].list)
2030 if(countEm != dev->objectBucket[bucket].count)
2032 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
2041 void yaffs_ObjectTest(yaffs_Device *dev)
2043 yaffs_Object *in[1000];
2045 yaffs_Object *inold[1000];
2049 memset(in,0,1000*sizeof(yaffs_Object *));
2050 memset(inold,0,1000*sizeof(yaffs_Object *));
2052 yaffs_CheckObjectHashSanity(dev);
2054 for(j = 0; j < 10; j++)
2058 for(i = 0; i < 1000; i++)
2060 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
2063 YINFO("No more inodes");
2067 inNo[i] = in[i]->objectId;
2071 for(i = 0; i < 1000; i++)
2073 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
2075 //T(("Differnce in look up test\n"));
2079 // T(("Look up ok\n"));
2083 yaffs_CheckObjectHashSanity(dev);
2085 for(i = 0; i < 1000; i+=3)
2087 yaffs_FreeObject(in[i]);
2092 yaffs_CheckObjectHashSanity(dev);
2099 /////////////////////////// Block Management and Page Allocation ///////////////////
2102 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
2104 dev->allocationBlock = -1; // force it to get a new one
2105 //Todo we're assuming the malloc will pass.
2106 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2107 // Set up dynamic blockinfo stuff.
2108 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
2109 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2110 if(dev->blockInfo && dev->chunkBits)
2112 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
2113 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
2121 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2123 YFREE(dev->blockInfo);
2124 dev->blockInfo = NULL;
2125 YFREE(dev->chunkBits);
2126 dev->chunkBits = NULL;
2130 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev, yaffs_BlockInfo *bi)
2136 if(!dev->isYaffs2) return 1; // disqualification only applies to yaffs2.
2138 if(!bi->hasShrinkHeader) return 1; // can gc
2141 // Find the oldest dirty sequence number if we don't know it and save it
2142 // so we don't have to keep recomputing it.
2143 if(!dev->oldestDirtySequence)
2145 seq = dev->sequenceNumber;
2147 for(i = dev->startBlock; i <= dev->endBlock; i++)
2149 b = yaffs_GetBlockInfo(dev,i);
2150 if(b->blockState == YAFFS_BLOCK_STATE_FULL &&
2151 (b->pagesInUse - b->softDeletions )< dev->nChunksPerBlock &&
2152 b->sequenceNumber < seq)
2154 seq = b->sequenceNumber;
2157 dev->oldestDirtySequence = seq;
2161 // Can't do gc of this block if there are any blocks older than this one that have
2163 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2170 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
2171 // for garbage collection.
2176 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,int aggressive)
2179 int b = dev->currentDirtyChecker;
2185 yaffs_BlockInfo *bi;
2186 static int nonAggressiveSkip = 0;
2188 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2190 // else (we're doing a leasurely gc), then we only bother to do this if the
2191 // block has only a few pages in use.
2194 nonAggressiveSkip--;
2196 if(!aggressive &&(nonAggressiveSkip > 0))
2201 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2204 iterations = dev->endBlock - dev->startBlock + 1;
2208 iterations = dev->endBlock - dev->startBlock + 1;
2209 iterations = iterations / 16;
2210 if(iterations > 200)
2216 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2219 if ( b < dev->startBlock || b > dev->endBlock)
2221 b = dev->startBlock;
2224 if(b < dev->startBlock || b > dev->endBlock)
2226 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2230 bi = yaffs_GetBlockInfo(dev,b);
2232 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2233 (bi->pagesInUse - bi->softDeletions )< pagesInUse &&
2234 yaffs_BlockNotDisqualifiedFromGC(dev,bi))
2237 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2241 dev->currentDirtyChecker = b;
2245 T(YAFFS_TRACE_GC,(TSTR("GC Selected block %d with %d free" TENDSTR),dirtiest,dev->nChunksPerBlock - pagesInUse));
2248 dev->oldestDirtySequence = 0; // clear this
2252 nonAggressiveSkip = 4;
2259 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2261 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2265 // If the block is still healthy erase it and mark as clean.
2266 // If the block has had a data failure, then retire it.
2267 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2269 if(!bi->needsRetiring)
2271 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2274 dev->nErasureFailures++;
2275 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2279 if(erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE))
2282 for(i = 0; i < dev->nChunksPerBlock; i++)
2284 if(!yaffs_CheckChunkErased(dev,blockNo * dev->nChunksPerBlock + i))
2286 T(YAFFS_TRACE_ERROR,(TSTR(">>Block %d erasure supposedly OK, but chunk %d not erased" TENDSTR),blockNo,i));
2294 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2295 dev->nErasedBlocks++;
2297 bi->softDeletions = 0;
2298 bi->hasShrinkHeader=0;
2299 yaffs_ClearChunkBits(dev,blockNo);
2301 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2305 yaffs_RetireBlock(dev,blockNo);
2306 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2310 static void yaffs_DumpBlockStats(yaffs_Device *dev)
2313 yaffs_BlockInfo *bi;
2315 for(i= dev->startBlock; i <=dev->endBlock; i++)
2317 bi = yaffs_GetBlockInfo(dev,i);
2318 T(YAFFS_TRACE_ALLOCATE,(TSTR("%3d state %d shrink %d inuse %d/%d seq %d pages"),i,
2319 bi->blockState,bi->hasShrinkHeader,bi->pagesInUse,bi->softDeletions,bi->sequenceNumber));
2321 for(j = 0; j < dev->nChunksPerBlock; j++)
2323 if(yaffs_CheckChunkBit(dev,i,j))
2325 T(YAFFS_TRACE_ALLOCATE,(TSTR(" %d"),j));
2329 T(YAFFS_TRACE_ALLOCATE,(TSTR(" " TENDSTR)));
2335 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2339 yaffs_BlockInfo *bi;
2344 if(j < 0 || j > 100)
2347 yaffs_DumpBlockStats(dev);
2352 if(dev->nErasedBlocks < 1)
2354 // Hoosterman we've got a problem.
2355 // Can't get space to gc
2356 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2361 // Find an empty block.
2363 for(i = dev->startBlock; i <= dev->endBlock; i++)
2365 dev->allocationBlockFinder++;
2366 if(dev->allocationBlockFinder < dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2368 dev->allocationBlockFinder = dev->startBlock;
2371 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2373 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2375 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2376 dev->sequenceNumber++;
2377 bi->sequenceNumber = dev->sequenceNumber;
2378 dev->nErasedBlocks--;
2379 T(YAFFS_TRACE_ALLOCATE,(TSTR("Allocated block %d, seq %d" TENDSTR),dev->allocationBlockFinder,dev->sequenceNumber));
2380 return dev->allocationBlockFinder;
2383 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no more eraased blocks, but there should have been one" TENDSTR)));
2391 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2394 yaffs_BlockInfo *bi;
2396 if(dev->allocationBlock < 0)
2398 // Get next block to allocate off
2399 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2400 dev->allocationPage = 0;
2403 if(!useReserve && dev->nErasedBlocks </*=*/ dev->nReservedBlocks)
2405 // Not enough space to allocate unless we're allowed to use the reserve.
2409 if(dev->nErasedBlocks < dev->nReservedBlocks && dev->allocationPage == 0)
2411 T(YAFFS_TRACE_ALLOCATE,(TSTR("Allocating reserve" TENDSTR)));
2415 // Next page please....
2416 if(dev->allocationBlock >= 0)
2418 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2420 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2421 dev->allocationPage;
2423 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2425 dev->allocationPage++;
2429 // If the block is full set the state to full
2430 if(dev->allocationPage >= dev->nChunksPerBlock)
2432 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2433 dev->allocationBlock = -1;
2440 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2446 // To determine if we have enough space we just look at the
2447 // number of erased blocks.
2448 // The cache is allowed to use reserved blocks.
2450 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2452 return (dev->nErasedBlocks >= dev->nReservedBlocks);
2456 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2460 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2462 if(dev->allocationBlock> 0)
2464 n += (dev->nChunksPerBlock - dev->allocationPage);
2471 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2477 int retVal = YAFFS_OK;
2481 int chunksBefore = yaffs_GetErasedChunks(dev);
2484 yaffs_ExtendedTags tags;
2486 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2488 yaffs_Object *object;
2490 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2492 T(YAFFS_TRACE_TRACING,(TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR),block,bi->pagesInUse,bi->hasShrinkHeader));
2493 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2495 bi->hasShrinkHeader = 0; // clear the flag so that the block can erase
2498 if(!yaffs_StillSomeChunkBits(dev,block))
2500 T(YAFFS_TRACE_TRACING,(TSTR("Collecting block %d that has no chunks in use" TENDSTR),block));
2501 yaffs_BlockBecameDirty(dev,block);
2506 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
2508 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2509 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2510 chunkInBlock++, oldChunk++ )
2512 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2515 // This page is in use and might need to be copied off
2519 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2521 yaffs_InitialiseTags(&tags);
2523 yaffs_ReadChunkWithTagsFromNAND(dev,oldChunk,buffer, &tags);
2525 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2527 T(YAFFS_TRACE_GC_DETAIL,(TSTR("Collecting page %d, %d %d %d " TENDSTR),chunkInBlock,tags.objectId,tags.chunkId,tags.byteCount));
2531 T(YAFFS_TRACE_ERROR,(TSTR("page %d in gc has no object " TENDSTR),oldChunk));
2534 if(object && object->deleted && tags.chunkId != 0)
2536 // Data chunk in a deleted file, throw it away
2537 // It's a deleted data chunk,
2538 // No need to copy this, just forget about it and fix up the
2541 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2542 object->nDataChunks--;
2544 if(object->nDataChunks <= 0)
2546 // remeber to clean up the object
2547 dev->gcCleanupList[cleanups] = tags.objectId;
2552 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2554 // Deleted object header with no data chunks.
2555 // Can be discarded and the file deleted.
2556 object->chunkId = 0;
2557 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2558 object->variant.fileVariant.top = NULL;
2559 yaffs_DoGenericObjectDeletion(object);
2564 // It's either a data chunk in a live file or
2565 // an ObjectHeader, so we're interested in it.
2566 // NB Need to keep the ObjectHeaders of deleted files
2567 // until the whole file has been deleted off
2568 tags.serialNumber++;
2572 newChunk = yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags,1);
2576 retVal = YAFFS_FAIL;
2581 // Ok, now fix up the Tnodes etc.
2583 if(tags.chunkId == 0)
2586 object->chunkId = newChunk;
2587 object->serial = tags.serialNumber;
2591 // It's a data chunk
2592 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2597 yaffs_DeleteChunk(dev,oldChunk,markNAND,__LINE__);
2602 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
2605 // Do any required cleanups
2606 for(i = 0; i < cleanups; i++)
2608 // Time to delete the file too
2609 object = yaffs_FindObjectByNumber(dev,dev->gcCleanupList[i]);
2612 yaffs_FreeTnode(dev,object->variant.fileVariant.top);
2613 object->variant.fileVariant.top = NULL;
2614 T(YAFFS_TRACE_GC,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2615 yaffs_DoGenericObjectDeletion(object);
2622 if(chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev)))
2624 T(YAFFS_TRACE_GC,(TSTR("gc did not increase free chunks before %d after %d" TENDSTR),chunksBefore,chunksAfter));
2631 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2633 // find a file to delete
2634 struct list_head *i;
2638 //Scan the unlinked files looking for one to delete
2639 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2643 l = list_entry(i, yaffs_Object,siblings);
2654 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2656 // This does background deletion on unlinked files.. only deleted ones.
2657 // If we don't have a file we're working on then find one
2658 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2660 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2663 // OK, we're working on a file...
2664 if(dev->unlinkedDeletion)
2666 yaffs_Object *obj = dev->unlinkedDeletion;
2668 int limit; // Number of chunks to delete in a file.
2669 // NB this can be exceeded, but not by much.
2673 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2675 if(obj->nDataChunks == 0)
2677 // Done all the deleting of data chunks.
2678 // Now dump the header and clean up
2679 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2680 obj->variant.fileVariant.top = NULL;
2681 yaffs_DoGenericObjectDeletion(obj);
2682 dev->nDeletedFiles--;
2683 dev->nUnlinkedFiles--;
2684 dev->nBackgroundDeletions++;
2685 dev->unlinkedDeletion = NULL;
2693 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
2694 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2699 //yaffs_DoUnlinkedFileDeletion(dev);
2701 if(dev->nErasedBlocks <= (dev->nReservedBlocks + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2708 block = yaffs_FindBlockForGarbageCollection(dev,aggressive);
2712 dev->garbageCollections++;
2713 return yaffs_GarbageCollectBlock(dev,block);
2725 // New garbage collector
2726 // If we're very low on erased blocks then we do aggressive garbage collection
2727 // otherwise we do "leasurely" garbage collection.
2728 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2729 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2731 // The idea is to help clear out space in a more spread-out manner.
2732 // Dunno if it really does anything useful.
2734 int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2738 int gcOk = YAFFS_OK;
2741 //yaffs_DoUnlinkedFileDeletion(dev);
2743 // This loop should pass the first time.
2744 // We'll only see looping here if the erase of the collected block fails.
2748 if(dev->nErasedBlocks <= (dev->nReservedBlocks + 2))
2750 // We need a block soon...
2755 // We're in no hurry
2759 block = yaffs_FindBlockForGarbageCollection(dev,aggressive);
2763 dev->garbageCollections++;
2766 dev->passiveGarbageCollections++;
2769 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2771 gcOk = yaffs_GarbageCollectBlock(dev,block);
2774 if(dev->nErasedBlocks <= (dev->nReservedBlocks + 1))
2776 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d" TENDSTR),dev->nErasedBlocks,maxTries,block));
2778 } while((dev->nErasedBlocks <= (dev->nReservedBlocks + 1)) && (block > 0) && (maxTries < 5));
2780 return aggressive ? gcOk: YAFFS_OK;
2784 //////////////////////////// TAGS ///////////////////////////////////////
2787 void yaffs_InitialiseTags(yaffs_ExtendedTags *tags)
2789 memset(tags,0,sizeof(yaffs_ExtendedTags));
2790 tags->validMarker0 = 0xAAAAAAAA;
2791 tags->validMarker1 = 0x55555555;
2794 static int yaffs_ValidateTags(yaffs_ExtendedTags *tags)
2796 return (tags->validMarker0 == 0xAAAAAAAA && tags->validMarker1 == 0x55555555);
2803 void yaffs_CalcTagsECC(yaffs_Tags *tags)
2807 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
2814 for(i = 0; i < 8; i++)
2816 for(j = 1; j &0xff; j<<=1)
2831 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
2833 unsigned ecc = tags->ecc;
2835 yaffs_CalcTagsECC(tags);
2839 if(ecc && ecc <= 64)
2841 // TODO: Handle the failure better. Retire?
2842 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
2846 b[ecc / 8] ^= (1 << (ecc & 7));
2848 // Now recvalc the ecc
2849 yaffs_CalcTagsECC(tags);
2851 return 1; // recovered error
2855 // Wierd ecc failure value
2856 // TODO Need to do somethiong here
2857 return -1; //unrecovered error
2863 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2865 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2867 yaffs_CalcTagsECC(tagsPtr);
2869 sparePtr->tagByte0 = tu->asBytes[0];
2870 sparePtr->tagByte1 = tu->asBytes[1];
2871 sparePtr->tagByte2 = tu->asBytes[2];
2872 sparePtr->tagByte3 = tu->asBytes[3];
2873 sparePtr->tagByte4 = tu->asBytes[4];
2874 sparePtr->tagByte5 = tu->asBytes[5];
2875 sparePtr->tagByte6 = tu->asBytes[6];
2876 sparePtr->tagByte7 = tu->asBytes[7];
2879 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2881 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2884 tu->asBytes[0]= sparePtr->tagByte0;
2885 tu->asBytes[1]= sparePtr->tagByte1;
2886 tu->asBytes[2]= sparePtr->tagByte2;
2887 tu->asBytes[3]= sparePtr->tagByte3;
2888 tu->asBytes[4]= sparePtr->tagByte4;
2889 tu->asBytes[5]= sparePtr->tagByte5;
2890 tu->asBytes[6]= sparePtr->tagByte6;
2891 tu->asBytes[7]= sparePtr->tagByte7;
2893 result = yaffs_CheckECCOnTags(tagsPtr);
2896 dev->tagsEccFixed++;
2900 dev->tagsEccUnfixed++;
2904 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2906 memset(spare,0xFF,sizeof(yaffs_Spare));
2912 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_ExtendedTags *tags, int useReserve)
2914 // NB There must be tags, data is optional
2915 // If there is data, then an ECC is calculated on it.
2924 //yaffs_SpareInitialise(&spare);
2926 //if(!dev->useNANDECC && buffer)
2928 // yaffs_CalcECC(buffer,&spare);
2931 //yaffs_LoadTagsIntoSpare(&spare,tags);
2933 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2938 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId, int chunkInObject)
2940 return ( tags->chunkId == chunkInObject &&
2941 tags->objectId == objectId &&
2942 !tags->chunkDeleted) ? 1 : 0;
2948 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_ExtendedTags *tags)
2950 //Get the Tnode, then get the level 0 offset chunk offset
2953 yaffs_ExtendedTags localTags;
2956 yaffs_Device *dev = in->myDev;
2961 // Passed a NULL, so use our own tags space
2965 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2969 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2971 retVal = yaffs_FindChunkInGroup(dev,theChunk,tags,in->objectId,chunkInInode);
2976 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_ExtendedTags *tags)
2978 //Get the Tnode, then get the level 0 offset chunk offset
2981 yaffs_ExtendedTags localTags;
2983 yaffs_Device *dev = in->myDev;
2988 // Passed a NULL, so use our own tags space
2992 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2997 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2999 retVal = yaffs_FindChunkInGroup(dev,theChunk,tags,in->objectId,chunkInInode);
3001 // Delete the entry in the filestructure (if found)
3004 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
3009 //T(("No level 0 found for %d\n", chunkInInode));
3014 //T(("Could not find %d to delete\n",chunkInInode));
3020 #ifdef YAFFS_PARANOID
3022 static int yaffs_CheckFileSanity(yaffs_Object *in)
3030 yaffs_Tags localTags;
3031 yaffs_Tags *tags = &localTags;
3036 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3038 //T(("Object not a file\n"));
3042 objId = in->objectId;
3043 fSize = in->variant.fileVariant.fileSize;
3044 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
3046 for(chunk = 1; chunk <= nChunks; chunk++)
3048 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
3053 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
3055 if(yaffs_CheckChunkBits(dev,theChunk/dev->nChunksPerBlock,theChunk%dev->nChunksPerBlock))
3059 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
3060 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
3068 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
3069 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
3078 //T(("No level 0 found for %d\n", chunk));
3082 return failed ? YAFFS_FAIL : YAFFS_OK;
3087 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
3090 yaffs_Device *dev = in->myDev;
3092 yaffs_ExtendedTags existingTags;
3093 yaffs_ExtendedTags newTags;
3094 unsigned existingSerial, newSerial;
3096 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
3102 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
3106 // If we're scanning then we need to test for duplicates
3107 // NB This does not need to be efficient since it should only ever
3108 // happen when the power fails during a write, then only one
3109 // chunk should ever be affected.
3112 if(existingChunk != 0)
3114 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
3115 // thus we have to do a FindChunkInFile to get the real chunk id.
3117 // We have a duplicate now we need to decide which one to use
3118 // To do this we get both sets of tags and compare serial numbers.
3119 yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND, NULL,&newTags);
3123 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
3125 if(existingChunk <=0)
3127 //Hoosterman - how did this happen?
3129 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
3134 // NB The deleted flags should be false, otherwise the chunks will
3135 // not be loaded during a scan
3137 newSerial = newTags.serialNumber;
3138 existingSerial = existingTags.serialNumber;
3140 if( in->myDev->isYaffs2 ||
3141 existingChunk <= 0 ||
3142 ((existingSerial+1) & 3) == newSerial)
3145 // Delete the old one and drop through to update the tnode
3146 yaffs_DeleteChunk(dev,existingChunk,1,__LINE__);
3151 // Delete the new one and return early so that the tnode isn't changed
3152 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
3159 if(existingChunk == 0)
3164 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
3171 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
3173 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
3175 if(chunkInNAND >= 0)
3177 return yaffs_ReadChunkWithTagsFromNAND(in->myDev,chunkInNAND,buffer,NULL);
3181 T(YAFFS_TRACE_NANDACCESS,(TSTR("Chunk %d not found zero instead" TENDSTR),chunkInNAND));
3183 memset(buffer,0,in->myDev->nBytesPerChunk); // get sane data if you read a hole
3190 void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND,int lyn)
3194 yaffs_ExtendedTags tags;
3195 yaffs_BlockInfo *bi;
3197 if(chunkId <= 0) return;
3200 block = chunkId / dev->nChunksPerBlock;
3201 page = chunkId % dev->nChunksPerBlock;
3203 bi = yaffs_GetBlockInfo(dev,block);
3205 T(YAFFS_TRACE_DELETION,(TSTR("line %d delete of chunk %d" TENDSTR),lyn,chunkId));
3208 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
3211 // yaffs_SpareInitialise(&spare);
3213 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
3215 //read data before write, to ensure correct ecc
3216 //if we're using MTD verification under Linux
3217 yaffs_ReadChunkFromNAND(dev,chunkId,NULL,&spare,0);
3220 yaffs_InitialiseTags(&tags);
3222 tags.chunkDeleted = 1;
3225 yaffs_WriteChunkWithTagsToNAND(dev,chunkId,NULL,&tags);
3226 yaffs_HandleUpdateChunk(dev,chunkId,&tags);
3230 dev->nUnmarkedDeletions++;
3234 // Pull out of the management area.
3235 // If the whole block became dirty, this will kick off an erasure.
3236 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3237 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3238 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3239 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)
3243 yaffs_ClearChunkBit(dev,block,page);
3246 if(bi->pagesInUse == 0 &&
3247 !bi->hasShrinkHeader &&
3248 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3249 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING)
3251 yaffs_BlockBecameDirty(dev,block);
3257 // T(("Bad news deleting chunk %d\n",chunkId));
3265 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
3267 // Find old chunk Need to do this to get serial number
3268 // Write new one and patch into tree.
3269 // Invalidate old tags.
3272 yaffs_ExtendedTags prevTags;
3275 yaffs_ExtendedTags newTags;
3277 yaffs_Device *dev = in->myDev;
3279 yaffs_CheckGarbageCollection(dev);
3281 // Get the previous chunk at this location in the file if it exists
3282 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
3285 yaffs_InitialiseTags(&newTags);
3287 newTags.chunkId = chunkInInode;
3288 newTags.objectId = in->objectId;
3289 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3290 newTags.byteCount = nBytes;
3292 // yaffs_CalcTagsECC(&newTags);
3294 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
3298 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
3301 if(prevChunkId >= 0)
3303 yaffs_DeleteChunk(dev,prevChunkId,1,__LINE__);
3307 yaffs_CheckFileSanity(in);
3318 // UpdateObjectHeader updates the header on NAND for an object.
3319 // If name is not NULL, then that new name is used.
3321 int yaffs_UpdateObjectHeader(yaffs_Object *in,const YCHAR *name, int force,int isShrink)
3324 yaffs_BlockInfo *bi;
3326 yaffs_Device *dev = in->myDev;
3332 yaffs_ExtendedTags newTags;
3334 __u8 *buffer = NULL;
3335 YCHAR oldName[YAFFS_MAX_NAME_LENGTH+1];
3337 // __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
3339 yaffs_ObjectHeader *oh = NULL;
3340 // yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
3343 if(!in->fake || force)
3346 yaffs_CheckGarbageCollection(dev);
3348 buffer = yaffs_GetTempBuffer(in->myDev,__LINE__);
3349 oh = (yaffs_ObjectHeader *)buffer;
3351 prevChunkId = in->chunkId;
3353 if(prevChunkId >= 0)
3355 yaffs_ReadChunkWithTagsFromNAND(dev,prevChunkId,buffer,NULL);
3356 memcpy(oldName,oh->name,sizeof(oh->name));
3359 memset(buffer,0xFF,dev->nBytesPerChunk);
3362 oh->type = in->variantType;
3364 oh->st_mode = in->st_mode;
3366 #ifdef CONFIG_YAFFS_WINCE
3367 oh->win_atime[0] = in->win_atime[0];
3368 oh->win_ctime[0] = in->win_ctime[0];
3369 oh->win_mtime[0] = in->win_mtime[0];
3370 oh->win_atime[1] = in->win_atime[1];
3371 oh->win_ctime[1] = in->win_ctime[1];
3372 oh->win_mtime[1] = in->win_mtime[1];
3374 oh->st_uid = in->st_uid;
3375 oh->st_gid = in->st_gid;
3376 oh->st_atime = in->st_atime;
3377 oh->st_mtime = in->st_mtime;
3378 oh->st_ctime = in->st_ctime;
3379 oh->st_rdev = in->st_rdev;
3383 oh->parentObjectId = in->parent->objectId;
3387 oh->parentObjectId = 0;
3390 //oh->sum = in->sum;
3393 memset(oh->name,0,sizeof(oh->name));
3394 yaffs_strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3396 else if(prevChunkId)
3398 memcpy(oh->name, oldName,sizeof(oh->name));
3402 memset(oh->name,0,sizeof(oh->name));
3405 oh->isShrink = isShrink;
3407 switch(in->variantType)
3409 case YAFFS_OBJECT_TYPE_UNKNOWN:
3410 // Should not happen
3412 case YAFFS_OBJECT_TYPE_FILE:
3413 oh->fileSize = in->variant.fileVariant.fileSize;
3415 case YAFFS_OBJECT_TYPE_HARDLINK:
3416 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3418 case YAFFS_OBJECT_TYPE_SPECIAL:
3421 case YAFFS_OBJECT_TYPE_DIRECTORY:
3424 case YAFFS_OBJECT_TYPE_SYMLINK:
3425 yaffs_strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3426 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3431 yaffs_InitialiseTags(&newTags);
3433 newTags.chunkId = 0;
3434 newTags.objectId = in->objectId;
3435 newTags.serialNumber = in->serial;
3438 // Create new chunk in NAND
3439 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3444 in->chunkId = newChunkId;
3446 if(prevChunkId >= 0)
3448 yaffs_DeleteChunk(dev,prevChunkId,1,__LINE__);
3453 // If this was a shrink, then mark the block that the chunk lives on
3456 bi = yaffs_GetBlockInfo(in->myDev,newChunkId / in->myDev->nChunksPerBlock);
3457 bi->hasShrinkHeader = 1;
3462 retVal = newChunkId;
3467 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
3473 /////////////////////// Short Operations Cache ////////////////////////////////
3474 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3475 // reads might be short sequential reads, and a lot of writes may be short
3476 // sequential writes. eg. scanning/writing a jpeg file.
3477 // In these cases, a short read/write cache can provide a huge perfomance benefit
3478 // with dumb-as-a-rock code.
3479 // There are a limited number (~10) of cache chunks per device so that we don't
3480 // need a very intelligent search.
3486 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3488 yaffs_Device *dev = obj->myDev;
3491 yaffs_ChunkCache *cache;
3494 int nCaches = obj->myDev->nShortOpCaches;
3501 // Find the dirty cache for this object with the lowest chunk id.
3502 for(i = 0; i < nCaches; i++)
3504 if(dev->srCache[i].object == obj &&
3505 dev->srCache[i].dirty)
3507 if(!cache || dev->srCache[i].chunkId < lowest)
3509 cache = &dev->srCache[i];
3510 lowest = cache->chunkId;
3515 if(cache && !cache->locked)
3517 //Write it out and free it up
3520 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3522 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3524 nBytes= YAFFS_BYTES_PER_CHUNK;
3527 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3533 cache->object = NULL;
3536 } while(cache && chunkWritten > 0);
3540 //Hoosterman, disk full while writing cache out.
3541 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3549 // Grab us a chunk for use.
3550 // First look for an empty one.
3551 // Then look for the least recently used non-dirty one.
3552 // Then look for the least recently used dirty one...., flush and look again.
3553 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3559 if(dev->nShortOpCaches > 0)
3561 for(i = 0; i < dev->nShortOpCaches; i++)
3563 if(!dev->srCache[i].object)
3565 //T(("Grabbing empty %d\n",i));
3567 //printf("Grabbing empty %d\n",i);
3569 return &dev->srCache[i];
3576 usage = 0; // just to stop the compiler grizzling
3578 for(i = 0; i < dev->nShortOpCaches; i++)
3580 if(!dev->srCache[i].dirty &&
3581 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3584 usage = dev->srCache[i].lastUse;
3589 //T(("Grabbing non-empty %d\n",theOne));
3591 //if(theOne >= 0) printf("Grabbed non-empty cache %d\n",theOne);
3593 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3603 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3605 yaffs_ChunkCache *cache;
3606 yaffs_Object *theObj;
3611 if(dev->nShortOpCaches > 0)
3613 // Try find a non-dirty one...
3615 cache = yaffs_GrabChunkCacheWorker(dev);
3619 // They were all dirty, find the last recently used object and flush
3620 // its cache, then find again.
3621 // NB what's here is not very accurate, we actually flush the object
3622 // the last recently used page.
3629 for(i = 0; i < dev->nShortOpCaches; i++)
3631 if( dev->srCache[i].object &&
3632 !dev->srCache[i].locked &&
3633 (dev->srCache[i].lastUse < usage || !cache))
3635 usage = dev->srCache[i].lastUse;
3636 theObj = dev->srCache[i].object;
3637 cache = &dev->srCache[i];
3642 if(!cache || cache->dirty)
3646 yaffs_FlushFilesChunkCache(theObj);
3649 cache = yaffs_GrabChunkCacheWorker(dev);
3653 //printf(" pushout %d\n",pushout);
3666 // Find a cached chunk
3667 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3669 yaffs_Device *dev = obj->myDev;
3671 if(dev->nShortOpCaches > 0)
3673 for(i = 0; i < dev->nShortOpCaches; i++)
3675 if(dev->srCache[i].object == obj &&
3676 dev->srCache[i].chunkId == chunkId)
3680 return &dev->srCache[i];
3687 // Mark the chunk for the least recently used algorithym
3688 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3691 if(dev->nShortOpCaches > 0)
3693 if( dev->srLastUse < 0 ||
3694 dev->srLastUse > 100000000)
3696 // Reset the cache usages
3698 for(i = 1; i < dev->nShortOpCaches; i++)
3700 dev->srCache[i].lastUse = 0;
3707 cache->lastUse = dev->srLastUse;
3716 // Invalidate a single cache page.
3717 // Do this when a whole page gets written,
3718 // ie the short cache for this page is no longer valid.
3719 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3721 if(object->myDev->nShortOpCaches > 0)
3723 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3727 cache->object = NULL;
3733 // Invalidate all the cache pages associated with this object
3734 // Do this whenever ther file is deleted or resized.
3735 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3738 yaffs_Device *dev = in->myDev;
3740 if(dev->nShortOpCaches > 0)
3742 // Now invalidate it.
3743 for(i = 0; i < dev->nShortOpCaches; i++)
3745 if(dev->srCache[i].object == in)
3747 dev->srCache[i].object = NULL;
3757 ///////////////////////// File read/write ///////////////////////////////
3758 // Read and write have very similar structures.
3759 // In general the read/write has three parts to it
3760 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3761 // * Some complete chunks
3762 // * An incomplete chunk to end off with
3764 // Curve-balls: the first chunk might also be the last chunk.
3766 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3775 yaffs_ChunkCache *cache;
3783 chunk = offset / dev->nBytesPerChunk + 1; // The first chunk is 1
3784 start = offset % dev->nBytesPerChunk;
3786 // OK now check for the curveball where the start and end are in
3788 if( (start + n) < dev->nBytesPerChunk)
3794 nToCopy = dev->nBytesPerChunk - start;
3797 cache = yaffs_FindChunkCache(in,chunk);
3799 // If the chunk is already in the cache or it is less than a whole chunk
3800 // then use the cache (if there is caching)
3801 // else bypass the cache.
3802 if( cache || nToCopy != dev->nBytesPerChunk)
3804 if(dev->nShortOpCaches > 0)
3807 // If we can't find the data in the cache, then load it up.
3811 cache = yaffs_GrabChunkCache(in->myDev);
3813 cache->chunkId = chunk;
3816 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3820 yaffs_UseChunkCache(dev,cache,0);
3824 #ifdef CONFIG_YAFFS_WINCE
3825 yfsd_UnlockYAFFS(TRUE);
3827 memcpy(buffer,&cache->data[start],nToCopy);
3829 #ifdef CONFIG_YAFFS_WINCE
3830 yfsd_LockYAFFS(TRUE);
3836 // Read into the local buffer then copy...
3838 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3839 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3840 #ifdef CONFIG_YAFFS_WINCE
3841 yfsd_UnlockYAFFS(TRUE);
3843 memcpy(buffer,&localBuffer[start],nToCopy);
3845 #ifdef CONFIG_YAFFS_WINCE
3846 yfsd_LockYAFFS(TRUE);
3848 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
3854 #ifdef CONFIG_YAFFS_WINCE
3855 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3857 // Under WinCE can't do direct transfer. Need to use a local buffer.
3858 // This is because we otherwise screw up WinCE's memory mapper
3859 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3861 #ifdef CONFIG_YAFFS_WINCE
3862 yfsd_UnlockYAFFS(TRUE);
3864 memcpy(buffer,localBuffer,dev->nBytesPerChunk);
3866 #ifdef CONFIG_YAFFS_WINCE
3867 yfsd_LockYAFFS(TRUE);
3868 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
3872 // A full chunk. Read directly into the supplied buffer.
3873 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3889 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3898 int startOfWrite = offset;
3899 int chunkWritten = 0;
3907 while(n > 0 && chunkWritten >= 0)
3909 chunk = offset / dev->nBytesPerChunk + 1;
3910 start = offset % dev->nBytesPerChunk;
3913 // OK now check for the curveball where the start and end are in
3916 if( (start + n) < dev->nBytesPerChunk)
3920 // Now folks, to calculate how many bytes to write back....
3921 // If we're overwriting and not writing to then end of file then
3922 // we need to write back as much as was there before.
3924 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * dev->nBytesPerChunk);
3926 if(nBytesRead > dev->nBytesPerChunk)
3928 nBytesRead = dev->nBytesPerChunk;
3931 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3936 nToCopy = dev->nBytesPerChunk - start;
3937 nToWriteBack = dev->nBytesPerChunk;
3940 if(nToCopy != dev->nBytesPerChunk)
3942 // An incomplete start or end chunk (or maybe both start and end chunk)
3943 if(dev->nShortOpCaches > 0)
3945 yaffs_ChunkCache *cache;
3946 // If we can't find the data in the cache, then load it up.
3947 cache = yaffs_FindChunkCache(in,chunk);
3948 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3950 cache = yaffs_GrabChunkCache(in->myDev);
3952 cache->chunkId = chunk;
3955 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3960 yaffs_UseChunkCache(dev,cache,1);
3962 #ifdef CONFIG_YAFFS_WINCE
3963 yfsd_UnlockYAFFS(TRUE);
3966 memcpy(&cache->data[start],buffer,nToCopy);
3968 #ifdef CONFIG_YAFFS_WINCE
3969 yfsd_LockYAFFS(TRUE);
3972 cache->nBytes = nToWriteBack;
3976 chunkWritten = -1; // fail the write
3981 // An incomplete start or end chunk (or maybe both start and end chunk)
3982 // Read into the local buffer then copy, then copy over and write back.
3984 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3986 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3988 #ifdef CONFIG_YAFFS_WINCE
3989 yfsd_UnlockYAFFS(TRUE);
3992 memcpy(&localBuffer[start],buffer,nToCopy);
3994 #ifdef CONFIG_YAFFS_WINCE
3995 yfsd_LockYAFFS(TRUE);
3997 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,nToWriteBack,0);
3999 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
4001 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
4008 #ifdef CONFIG_YAFFS_WINCE
4009 // Under WinCE can't do direct transfer. Need to use a local buffer.
4010 // This is because we otherwise screw up WinCE's memory mapper
4011 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
4012 #ifdef CONFIG_YAFFS_WINCE
4013 yfsd_UnlockYAFFS(TRUE);
4015 memcpy(localBuffer,buffer,dev->nBytesPerChunk);
4016 #ifdef CONFIG_YAFFS_WINCE
4017 yfsd_LockYAFFS(TRUE);
4019 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,dev->nBytesPerChunk,0);
4020 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
4022 // A full chunk. Write directly from the supplied buffer.
4023 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,dev->nBytesPerChunk,0);
4025 // Since we've overwritten the cached data, we better invalidate it.
4026 yaffs_InvalidateChunkCache(in,chunk);
4027 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
4030 if(chunkWritten >= 0)
4040 // Update file object
4042 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
4044 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4052 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4055 yaffs_Device *dev = in->myDev;
4056 int oldFileSize = in->variant.fileVariant.fileSize;
4059 int lastDel = 1 + (oldFileSize-1)/dev->nBytesPerChunk;
4061 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1)/
4062 dev->nBytesPerChunk;
4066 // Delete backwards so that we don't end up with holes if
4067 // power is lost part-way through the operation.
4068 for(i = lastDel; i >= startDel; i--)
4070 // NB this could be optimised somewhat,
4071 // eg. could retrieve the tags and write them without
4072 // using yaffs_DeleteChunk
4074 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
4077 if(chunkId < (dev->startBlock * dev->nChunksPerBlock) ||
4078 chunkId >= ((dev->endBlock+1) * dev->nChunksPerBlock))
4080 T(YAFFS_TRACE_ALWAYS,("Found daft chunkId %d for %d\n",chunkId,i));
4085 yaffs_DeleteChunk(dev,chunkId,1,__LINE__);
4092 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
4095 int oldFileSize = in->variant.fileVariant.fileSize;
4096 int sizeOfPartialChunk;
4097 yaffs_Device *dev = in->myDev;
4099 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
4102 yaffs_FlushFilesChunkCache(in);
4103 yaffs_InvalidateWholeChunkCache(in);
4105 yaffs_CheckGarbageCollection(dev);
4107 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
4109 return yaffs_GetFileSize(in);
4112 if(newSize < oldFileSize)
4115 yaffs_PruneResizedChunks(in,newSize);
4117 if(sizeOfPartialChunk != 0)
4119 int lastChunk = 1+ newSize/dev->nBytesPerChunk;
4120 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
4122 // Got to read and rewrite the last chunk with its new size and zero pad
4123 yaffs_ReadChunkDataFromObject(in,lastChunk,localBuffer);
4125 memset(localBuffer + sizeOfPartialChunk,0, dev->nBytesPerChunk - sizeOfPartialChunk);
4127 yaffs_WriteChunkDataToObject(in,lastChunk,localBuffer,sizeOfPartialChunk,1);
4129 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
4132 in->variant.fileVariant.fileSize = newSize;
4134 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
4136 // TODO write a new object header to show we've shrunk the file
4137 // Do this only if the file is not in the deleted directory.
4138 if(in->parent->objectId != YAFFS_OBJECTID_UNLINKED)
4140 yaffs_UpdateObjectHeader(in,NULL, 0, 1);
4154 loff_t yaffs_GetFileSize(yaffs_Object *obj)
4156 obj = yaffs_GetEquivalentObject(obj);
4158 switch(obj->variantType)
4160 case YAFFS_OBJECT_TYPE_FILE:
4161 return obj->variant.fileVariant.fileSize;
4162 case YAFFS_OBJECT_TYPE_SYMLINK:
4163 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4171 // yaffs_FlushFile() updates the file's
4174 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
4179 //T(("flushing object header\n"));
4181 yaffs_FlushFilesChunkCache(in);
4184 #ifdef CONFIG_YAFFS_WINCE
4185 yfsd_WinFileTimeNow(in->win_mtime);
4188 in->st_mtime = Y_CURRENT_TIME;
4193 retVal = (yaffs_UpdateObjectHeader(in,NULL,0,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
4205 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
4208 // First off, invalidate the file's data in the cache, without flushing.
4209 yaffs_InvalidateWholeChunkCache(in);
4211 if(in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir))
4213 // Move to the unlinked directory so we have a record that it was deleted.
4214 yaffs_ChangeObjectName(in, in->myDev->deletedDir,NULL,0);
4219 yaffs_RemoveObjectFromDirectory(in);
4220 yaffs_DeleteChunk(in->myDev,in->chunkId,1,__LINE__);
4226 in->myInode->u.generic_ip = NULL;
4230 yaffs_FreeObject(in);
4235 // yaffs_DeleteFile deletes the whole file data
4236 // and the inode associated with the file.
4237 // It does not delete the links associated with the file.
4238 static int yaffs_UnlinkFile(yaffs_Object *in)
4241 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
4243 // Delete the file data & tnodes
4245 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
4248 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
4250 return yaffs_DoGenericObjectDeletion(in);
4253 int immediateDeletion=0;
4258 //in->myDev->nUnlinkedFiles++;
4259 //in->renameAllowed = 0;
4263 immediateDeletion = 1;
4269 immediateDeletion = 1;
4273 if(immediateDeletion)
4275 retVal = yaffs_ChangeObjectName(in, in->myDev->deletedDir,NULL,0);
4276 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
4278 in->myDev->nDeletedFiles++;
4279 yaffs_SoftDeleteFile(in);
4283 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
4293 int yaffs_DeleteFile(yaffs_Object *in)
4295 int retVal = YAFFS_OK;
4297 if(in->nDataChunks > 0)
4299 // Use soft deletion
4302 retVal = yaffs_UnlinkFile(in);
4304 if(retVal == YAFFS_OK &&
4309 in->myDev->nDeletedFiles++;
4310 yaffs_SoftDeleteFile(in);
4312 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4316 // The file has no data chunks so we toss it immediately
4317 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
4318 in->variant.fileVariant.top = NULL;
4319 yaffs_DoGenericObjectDeletion(in);
4325 static int yaffs_DeleteDirectory(yaffs_Object *in)
4327 //First check that the directory is empty.
4328 if(list_empty(&in->variant.directoryVariant.children))
4330 return yaffs_DoGenericObjectDeletion(in);
4337 static int yaffs_DeleteSymLink(yaffs_Object *in)
4339 YFREE(in->variant.symLinkVariant.alias);
4341 return yaffs_DoGenericObjectDeletion(in);
4344 static int yaffs_DeleteHardLink(yaffs_Object *in)
4346 // remove this hardlink from the list assocaited with the equivalent
4348 list_del(&in->hardLinks);
4349 return yaffs_DoGenericObjectDeletion(in);
4353 static void yaffs_DestroyObject(yaffs_Object *obj)
4355 switch(obj->variantType)
4357 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
4358 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
4359 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
4360 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
4361 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
4362 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
4367 static int yaffs_UnlinkWorker(yaffs_Object *obj)
4371 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4373 return yaffs_DeleteHardLink(obj);
4375 else if(!list_empty(&obj->hardLinks))
4377 // Curve ball: We're unlinking an object that has a hardlink.
4379 // This problem arises because we are not strictly following
4380 // The Linux link/inode model.
4382 // We can't really delete the object.
4383 // Instead, we do the following:
4384 // - Select a hardlink.
4385 // - Unhook it from the hard links
4386 // - Unhook it from its parent directory (so that the rename can work)
4387 // - Rename the object to the hardlink's name.
4388 // - Delete the hardlink
4393 YCHAR name[YAFFS_MAX_NAME_LENGTH+1];
4395 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
4397 list_del_init(&hl->hardLinks);
4398 list_del_init(&hl->siblings);
4400 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
4402 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
4404 if(retVal == YAFFS_OK)
4406 retVal = yaffs_DoGenericObjectDeletion(hl);
4413 switch(obj->variantType)
4415 case YAFFS_OBJECT_TYPE_FILE:
4416 return yaffs_UnlinkFile(obj);
4418 case YAFFS_OBJECT_TYPE_DIRECTORY:
4419 return yaffs_DeleteDirectory(obj);
4421 case YAFFS_OBJECT_TYPE_SYMLINK:
4422 return yaffs_DeleteSymLink(obj);
4424 case YAFFS_OBJECT_TYPE_HARDLINK:
4425 case YAFFS_OBJECT_TYPE_UNKNOWN:
4432 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
4436 obj = yaffs_FindObjectByName(dir,name);
4438 if(obj && obj->unlinkAllowed)
4440 return yaffs_UnlinkWorker(obj);
4447 //////////////// Initialisation Scanning /////////////////
4451 // For now we use the SmartMedia check.
4452 // We look at the blockStatus byte in the first two chunks
4453 // These must be 0xFF to pass as OK.
4454 // todo: this function needs to be modifyable foir different NAND types
4455 // and different chunk sizes. Suggest make this into a per-device configurable
4457 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
4459 yaffsExtendedTags *tags;
4461 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&tags,1);
4463 if(yaffs_CountBits(spare.blockStatus) < 7)
4468 if(spare.blockStatus != 0xFF)
4473 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
4476 if(yaffs_CountBits(spare.blockStatus) < 7)
4481 if(spare.blockStatus != 0xFF)
4502 static int yaffs_Scan(yaffs_Device *dev)
4504 yaffs_ExtendedTags tags;
4509 int nBlocksToScan = 0;
4514 yaffs_BlockState state;
4515 yaffs_Object *hardList = NULL;
4517 yaffs_BlockInfo *bi;
4519 yaffs_ObjectHeader *oh;
4521 yaffs_Object *parent;
4522 int nBlocks = dev->endBlock - dev->startBlock + 1;
4526 yaffs_BlockIndex *blockIndex = NULL;
4528 chunkData = yaffs_GetTempBuffer(dev,__LINE__);
4531 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4535 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4539 // Scan all the blocks to determine their state
4540 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
4542 bi = yaffs_GetBlockInfo(dev,blk);
4543 yaffs_ClearChunkBits(dev,blk);
4545 bi->softDeletions = 0;
4547 yaffs_QueryInitialBlockState(dev,blk,&state,&sequenceNumber);
4549 bi->blockState = state;
4550 bi->sequenceNumber = sequenceNumber;
4552 if(state == YAFFS_BLOCK_STATE_DEAD)
4554 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
4556 else if(state == YAFFS_BLOCK_STATE_EMPTY)
4558 dev->nErasedBlocks++;
4559 dev->nFreeChunks += dev->nChunksPerBlock;
4561 else if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
4564 // Determine the highest sequence number
4565 if( dev->isYaffs2 &&
4566 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4567 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER)
4570 blockIndex[nBlocksToScan].seq = sequenceNumber;
4571 blockIndex[nBlocksToScan].block = blk;
4575 if(sequenceNumber >= dev->sequenceNumber)
4577 dev->sequenceNumber = sequenceNumber;
4580 else if(dev->isYaffs2)
4582 // TODO: Nasty sequence number!
4583 T(YAFFS_TRACE_SCAN,(TSTR("Block scanning block %d has bad sequence number %d" TENDSTR),blk,sequenceNumber));
4590 // Dungy old bubble sort for now...
4593 yaffs_BlockIndex temp;
4597 for(i = 0; i < nBlocksToScan; i++)
4598 for(j = i+1; j < nBlocksToScan; j++)
4599 if(blockIndex[i].seq > blockIndex[j].seq)
4601 temp = blockIndex[j];
4602 blockIndex[j] = blockIndex[i];
4603 blockIndex[i] = temp;
4608 // Now scan the blocks looking at the data.
4612 endIterator = nBlocksToScan-1;
4616 startIterator = dev->startBlock;
4617 endIterator = dev->endBlock;
4620 for(blockIterator = startIterator; blockIterator <= endIterator; blockIterator++)
4625 // get the block to scan in the correct order
4626 blk = blockIndex[blockIterator].block;
4630 blk = blockIterator;
4634 bi = yaffs_GetBlockInfo(dev,blk);
4635 state = bi->blockState;
4639 for(c = 0; c < dev->nChunksPerBlock &&
4640 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++)
4642 // Read the tags and decide what to do
4643 chunk = blk * dev->nChunksPerBlock + c;
4645 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,NULL,&tags);
4647 // Let's have a good look at this chunk...
4650 if(!dev->isYaffs2 && tags.chunkDeleted)
4654 dev->nFreeChunks ++;
4655 //T((" %d %d deleted\n",blk,c));
4657 else if(!tags.chunkUsed)
4659 // An unassigned chunk in the block
4660 // This means that either the block is empty or
4661 // this is the one being allocated from
4665 // We're looking at the first chunk in the block so the block is unused
4666 state = YAFFS_BLOCK_STATE_EMPTY;
4667 dev->nErasedBlocks++;
4671 // this is the block being allocated from
4672 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4673 state = YAFFS_BLOCK_STATE_ALLOCATING;
4674 dev->allocationBlock = blk;
4675 dev->allocationPage = c;
4676 dev->allocationBlockFinder = blk; // Set it to here to encourage the allocator to
4677 // go forth from here.
4678 //Yaffs2 sanity check:
4679 // This should be the one with the highest sequence number
4680 if(dev->isYaffs2 && (dev->sequenceNumber != bi->sequenceNumber))
4682 T(YAFFS_TRACE_ALWAYS,
4683 (TSTR("yaffs: Allocation block %d was not highest sequence id: block seq = %d, dev seq = %d" TENDSTR),
4684 blk,bi->sequenceNumber,dev->sequenceNumber));
4688 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4690 else if(tags.chunkId > 0)
4694 yaffs_SetChunkBit(dev,blk,c);
4697 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4698 // PutChunkIntoFIle checks for a clash (two data chunks with
4699 // the same chunkId).
4700 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4701 endpos = (tags.chunkId - 1)* dev->nBytesPerChunk + tags.byteCount;
4702 if(in->variant.fileVariant.scannedFileSize <endpos)
4704 in->variant.fileVariant.scannedFileSize = endpos;
4705 if(!dev->useHeaderFileSize)
4707 in->variant.fileVariant.fileSize =
4708 in->variant.fileVariant.scannedFileSize;
4712 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4716 // chunkId == 0, so it is an ObjectHeader.
4717 // Thus, we read in the object header and make the object
4718 yaffs_SetChunkBit(dev,blk,c);
4721 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,chunkData,NULL);
4723 oh = (yaffs_ObjectHeader *)chunkData;
4725 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4729 // We have already filled this one. We have a duplicate and need to resolve it.
4731 unsigned existingSerial = in->serial;
4732 unsigned newSerial = tags.serialNumber;
4734 if( dev->isYaffs2 ||
4735 ((existingSerial+1) & 3) == newSerial)
4737 // Use new one - destroy the exisiting one
4738 yaffs_DeleteChunk(dev,in->chunkId,1,__LINE__);
4743 // Use existing - destroy this one.
4744 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
4749 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4750 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4752 // We only load some info, don't fiddle with directory structure
4754 in->variantType = oh->type;
4756 in->st_mode = oh->st_mode;
4757 #ifdef CONFIG_YAFFS_WINCE
4758 in->win_atime[0] = oh->win_atime[0];
4759 in->win_ctime[0] = oh->win_ctime[0];
4760 in->win_mtime[0] = oh->win_mtime[0];
4761 in->win_atime[1] = oh->win_atime[1];
4762 in->win_ctime[1] = oh->win_ctime[1];
4763 in->win_mtime[1] = oh->win_mtime[1];
4765 in->st_uid = oh->st_uid;
4766 in->st_gid = oh->st_gid;
4767 in->st_atime = oh->st_atime;
4768 in->st_mtime = oh->st_mtime;
4769 in->st_ctime = oh->st_ctime;
4770 in->st_rdev = oh->st_rdev;
4772 in->chunkId = chunk;
4777 // we need to load this info
4780 in->variantType = oh->type;
4782 in->st_mode = oh->st_mode;
4783 #ifdef CONFIG_YAFFS_WINCE
4784 in->win_atime[0] = oh->win_atime[0];
4785 in->win_ctime[0] = oh->win_ctime[0];
4786 in->win_mtime[0] = oh->win_mtime[0];
4787 in->win_atime[1] = oh->win_atime[1];
4788 in->win_ctime[1] = oh->win_ctime[1];
4789 in->win_mtime[1] = oh->win_mtime[1];
4791 in->st_uid = oh->st_uid;
4792 in->st_gid = oh->st_gid;
4793 in->st_atime = oh->st_atime;
4794 in->st_mtime = oh->st_mtime;
4795 in->st_ctime = oh->st_ctime;
4796 in->st_rdev = oh->st_rdev;
4798 in->chunkId = chunk;
4800 yaffs_SetObjectName(in,oh->name);
4803 // directory stuff...
4804 // hook up to parent
4806 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4807 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4809 // Set up as a directory
4810 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4811 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4813 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4815 // Hoosterman, another problem....
4816 // We're trying to use a non-directory as a directory
4818 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found." TENDSTR)));
4819 parent = dev->lostNFoundDir;
4822 yaffs_AddObjectToDirectory(parent,in);
4824 if(0 && (parent == dev->deletedDir ||
4825 parent == dev->unlinkedDir))
4827 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4828 dev->nDeletedFiles++;
4831 // Note re hardlinks.
4832 // Since we might scan a hardlink before its equivalent object is scanned
4833 // we put them all in a list.
4834 // After scanning is complete, we should have all the objects, so we run through this
4835 // list and fix up all the chains.
4837 switch(in->variantType)
4839 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4841 case YAFFS_OBJECT_TYPE_FILE:
4842 if(dev->isYaffs2 && oh->isShrink)
4844 // Prune back the shrunken chunks
4845 yaffs_PruneResizedChunks(in,oh->fileSize);
4846 // Mark the block as having a shrinkHeader
4847 bi->hasShrinkHeader = 1;
4850 if(dev->useHeaderFileSize)
4851 in->variant.fileVariant.fileSize = oh->fileSize;
4854 case YAFFS_OBJECT_TYPE_HARDLINK:
4855 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4856 in->hardLinks.next = (struct list_head *)hardList;
4859 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4861 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4863 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4864 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4868 if(parent == dev->deletedDir)
4870 yaffs_DestroyObject(in);
4871 bi->hasShrinkHeader = 1;
4873 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4878 if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
4880 // If we got this far while scanning, then the block is fully allocated.
4881 state = YAFFS_BLOCK_STATE_FULL;
4884 bi->blockState = state;
4886 // Now let's see if it was dirty
4887 if( bi->pagesInUse == 0 &&
4888 !bi->hasShrinkHeader &&
4889 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4891 yaffs_BlockBecameDirty(dev,blk);
4901 // Ok, we've done all the scanning.
4903 // Fix up the hard link chains.
4904 // We should now have scanned all the objects, now it's time to add these
4909 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4911 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4915 // Add the hardlink pointers
4916 hl->variant.hardLinkVariant.equivalentObject=in;
4917 list_add(&hl->hardLinks,&in->hardLinks);
4921 //Todo Need to report/handle this better.
4922 // Got a problem... hardlink to a non-existant object
4923 hl->variant.hardLinkVariant.equivalentObject=NULL;
4924 INIT_LIST_HEAD(&hl->hardLinks);
4931 struct list_head *i;
4932 struct list_head *n;
4935 // Soft delete all the unlinked files
4936 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
4940 l = list_entry(i, yaffs_Object,siblings);
4943 yaffs_DestroyObject(l);
4949 yaffs_ReleaseTempBuffer(dev,chunkData,__LINE__);
4955 ////////////////////////// Directory Functions /////////////////////////
4958 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
4961 if(obj->siblings.prev == NULL)
4964 INIT_LIST_HEAD(&obj->siblings);
4967 else if(!list_empty(&obj->siblings))
4969 // If it is holed up somewhere else, un hook it
4970 list_del_init(&obj->siblings);
4973 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
4974 obj->parent = directory;
4976 if(directory == obj->myDev->unlinkedDir || directory == obj->myDev->deletedDir)
4979 obj->myDev->nUnlinkedFiles++;
4980 obj->renameAllowed = 0;
4984 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4986 list_del_init(&obj->siblings);
4990 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const YCHAR *name)
4994 struct list_head *i;
4995 YCHAR buffer[YAFFS_MAX_NAME_LENGTH+1];
4999 sum = yaffs_CalcNameSum(name);
5001 list_for_each(i,&directory->variant.directoryVariant.children)
5005 l = list_entry(i, yaffs_Object,siblings);
5007 // Special case for lost-n-found
5008 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
5010 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
5015 else if(yaffs_SumCompare(l->sum, sum)||
5016 l->chunkId <= 0) //LostnFound cunk called Objxxx
5019 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
5020 if(yaffs_strcmp(name,buffer) == 0)
5033 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
5035 struct list_head *i;
5039 list_for_each(i,&theDir->variant.directoryVariant.children)
5043 l = list_entry(i, yaffs_Object,siblings);
5056 // GetEquivalentObject dereferences any hard links to get to the
5059 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
5061 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
5063 // We want the object id of the equivalent object, not this one
5064 obj = obj->variant.hardLinkVariant.equivalentObject;
5070 int yaffs_GetObjectName(yaffs_Object *obj,YCHAR *name,int buffSize)
5072 memset(name,0,buffSize * sizeof(YCHAR));
5074 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
5076 yaffs_strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
5078 else if(obj->chunkId <= 0)
5082 yaffs_sprintf(locName,_Y("%s%d"),YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
5083 yaffs_strncpy(name,locName,buffSize - 1);
5086 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5087 else if(obj->shortName[0])
5089 yaffs_strcpy(name,obj->shortName);
5094 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev,__LINE__);
5096 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
5098 memset(buffer,0,obj->myDev->nBytesPerChunk);
5100 if(obj->chunkId >= 0)
5102 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
5104 yaffs_strncpy(name,oh->name,buffSize - 1);
5106 yaffs_ReleaseTempBuffer(obj->myDev,buffer,__LINE__);
5109 return yaffs_strlen(name);
5112 int yaffs_GetObjectFileLength(yaffs_Object *obj)
5115 // Dereference any hard linking
5116 obj = yaffs_GetEquivalentObject(obj);
5118 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
5120 return obj->variant.fileVariant.fileSize;
5122 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5124 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5128 // Only a directory should drop through to here
5129 return obj->myDev->nBytesPerChunk;
5133 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
5136 struct list_head *i;
5140 count++; // the object itself
5142 list_for_each(i,&obj->hardLinks)
5144 count++; // add the hard links;
5151 int yaffs_GetObjectInode(yaffs_Object *obj)
5153 obj = yaffs_GetEquivalentObject(obj);
5155 return obj->objectId;
5158 unsigned yaffs_GetObjectType(yaffs_Object *obj)
5160 obj = yaffs_GetEquivalentObject(obj);
5162 switch(obj->variantType)
5164 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
5165 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
5166 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
5167 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
5168 case YAFFS_OBJECT_TYPE_SPECIAL:
5169 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
5170 if(S_ISCHR(obj->st_mode)) return DT_CHR;
5171 if(S_ISBLK(obj->st_mode)) return DT_BLK;
5172 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
5173 default: return DT_REG; break;
5177 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
5179 obj = yaffs_GetEquivalentObject(obj);
5180 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5182 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5186 return yaffs_CloneString(_Y(""));
5190 #ifndef CONFIG_YAFFS_WINCE
5192 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
5194 unsigned int valid = attr->ia_valid;
5196 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
5197 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
5198 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
5200 if(valid & ATTR_ATIME) obj->st_atime = Y_TIME_CONVERT(attr->ia_atime);
5201 if(valid & ATTR_CTIME) obj->st_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5202 if(valid & ATTR_MTIME) obj->st_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5204 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
5206 yaffs_UpdateObjectHeader(obj,NULL,1,0);
5211 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
5213 unsigned int valid = 0;
5215 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
5216 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
5217 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
5219 Y_TIME_CONVERT(attr->ia_atime)= obj->st_atime; valid |= ATTR_ATIME;
5220 Y_TIME_CONVERT(attr->ia_ctime) = obj->st_ctime; valid |= ATTR_CTIME;
5221 Y_TIME_CONVERT(attr->ia_mtime) = obj->st_mtime; valid |= ATTR_MTIME;
5223 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
5225 attr->ia_valid = valid;
5233 int yaffs_DumpObject(yaffs_Object *obj)
5235 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
5237 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
5239 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
5241 // if(obj->chunkId >= 0)
5243 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
5246 yaffs_GetObjectName(obj,name,256);
5248 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),
5249 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
5250 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5253 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
5254 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
5255 obj->sum, obj->chunkId));
5256 switch(obj->variantType)
5258 case YAFFS_OBJECT_TYPE_FILE:
5259 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
5261 case YAFFS_OBJECT_TYPE_DIRECTORY:
5262 YPRINTF((" DIRECTORY\n"));
5264 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
5265 case YAFFS_OBJECT_TYPE_SYMLINK:
5266 case YAFFS_OBJECT_TYPE_UNKNOWN:
5275 ///////////////////////// Initialisation code ///////////////////////////
5278 int yaffs_CheckDevFunctions(const yaffs_Device *dev)
5281 // Common functions, gotta have
5282 if(!dev->eraseBlockInNAND ||
5283 !dev->initialiseNAND) return 0;
5285 #ifdef CONFIG_YAFFS_YAFFS2
5287 // Can use the "with tags" style interface for yaffs1 or yaffs2
5288 if(dev->writeChunkWithTagsToNAND &&
5289 dev->readChunkWithTagsFromNAND &&
5290 !dev->writeChunkToNAND &&
5291 !dev->readChunkFromNAND &&
5292 dev->markNANDBlockBad &&
5293 dev->queryNANDBlock) return 1;
5296 // Can use the "spare" style interface for yaffs1
5297 if(!dev->isYaffs2 &&
5298 !dev->writeChunkWithTagsToNAND &&
5299 !dev->readChunkWithTagsFromNAND &&
5300 dev->writeChunkToNAND &&
5301 dev->readChunkFromNAND &&
5302 !dev->markNANDBlockBad &&
5303 !dev->queryNANDBlock) return 1;
5309 int yaffs_GutsInitialise(yaffs_Device *dev)
5316 // Check stuff that must be set
5320 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Need a device\n" TENDSTR)));
5324 // Check geometry parameters.
5326 if( (dev->isYaffs2 && dev->nBytesPerChunk <1024) ||
5327 (!dev->isYaffs2 && dev->nBytesPerChunk !=512) ||
5328 dev->nChunksPerBlock < 2 ||
5329 dev->nReservedBlocks < 2 ||
5330 dev->startBlock <= 0 ||
5331 dev->endBlock <= 0 ||
5332 dev->endBlock <= (dev->startBlock + dev->nReservedBlocks + 2) // otherwise it is too small
5335 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: nand geometry problems\n" TENDSTR)));
5340 // Got the right mix of functions?
5342 if(!yaffs_CheckDevFunctions(dev))
5345 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5350 // This is really a compilation check.
5351 if(!yaffs_CheckStructures())
5353 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5359 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
5365 // Finished with most checks. One or two more checks happen later on too.
5371 nBlocks = dev->endBlock - dev->startBlock + 1;
5375 // OK now calculate a few things for the device
5376 // Calculate chunkGroupBits.
5377 // We need to find the next power of 2 > than endBlock
5379 x = dev->nChunksPerBlock * (dev->endBlock+1);
5381 for(bits = extraBits = 0; x > 1; bits++)
5383 if(x & 1) extraBits++;
5387 if(extraBits > 0) bits++;
5390 // Level0 Tnodes are 16 bits, so if the bitwidth of the
5391 // chunk range we're using is greater than 16 we need
5392 // to figure out chunk shift and chunkGroupSize
5395 dev->chunkGroupBits = 0;
5399 dev->chunkGroupBits = bits - 16;
5402 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5404 if(dev->nChunksPerBlock < dev->chunkGroupSize)
5406 // We have a problem because the soft delete won't work if
5407 // the chunk group size > chunks per block.
5408 // This can be remedied by using larger "virtual blocks".
5409 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: chunk group too large\n" TENDSTR)));
5415 // OK, we've finished verifying the device, lets continue with initialisation
5417 // More device initialisation
5418 dev->garbageCollections = 0;
5419 dev->passiveGarbageCollections = 0;
5420 dev->currentDirtyChecker = 0;
5421 dev->bufferedBlock = -1;
5422 dev->doingBufferedBlockRewrite = 0;
5423 dev->nDeletedFiles = 0;
5424 dev->nBackgroundDeletions=0;
5425 dev->nUnlinkedFiles = 0;
5428 dev->tagsEccFixed=0;
5429 dev->tagsEccUnfixed=0;
5430 dev->nErasureFailures = 0;
5432 //dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
5433 // Initialise temporary buffers
5436 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5438 dev->tempBuffer[i].line = 0; // not in use
5439 dev->tempBuffer[i].buffer = YMALLOC(dev->nBytesPerChunk);
5446 yaffs_InitialiseBlocks(dev,nBlocks);
5448 yaffs_InitialiseTnodes(dev);
5450 yaffs_InitialiseObjects(dev);
5452 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
5454 if(dev->nShortOpCaches > 0)
5458 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
5460 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5463 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
5465 for(i=0; i < dev->nShortOpCaches; i++)
5467 dev->srCache[i].object = NULL;
5468 dev->srCache[i].lastUse = 0;
5469 dev->srCache[i].dirty = 0;
5470 dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
5478 // Initialise the unlinked, root and lost and found directories
5479 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = dev->deletedDir = NULL;
5481 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5482 dev->deletedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5484 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
5485 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5486 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
5490 dev->useHeaderFileSize = 1;
5493 // Now scan the flash.
5497 dev->nPageReads = 0;
5498 dev->nPageWrites = 0;
5499 dev->nBlockErasures = 0;
5501 dev->nRetriedWrites = 0;
5503 dev->nRetiredBlocks = 0;
5510 void yaffs_Deinitialise(yaffs_Device *dev)
5516 yaffs_DeinitialiseBlocks(dev);
5517 yaffs_DeinitialiseTnodes(dev);
5518 yaffs_DeinitialiseObjects(dev);
5519 if(dev->nShortOpCaches > 0)
5522 for(i=0; i < dev->nShortOpCaches; i++)
5524 YFREE(dev->srCache[i].data);
5527 YFREE(dev->srCache);
5530 YFREE(dev->gcCleanupList);
5532 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5534 YFREE(dev->tempBuffer[i].buffer);
5544 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
5546 int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
5548 struct list_head *i;
5552 // To the free chunks add the chunks that are in the deleted unlinked files.
5553 list_for_each(i,&dev->deletedDir->variant.directoryVariant.children)
5555 l = list_entry(i, yaffs_Object,siblings);
5559 nFree += l->nDataChunks;
5564 // printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
5566 if(nFree < 0) nFree = 0;
5574 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
5579 int nDirtyCacheChunks=0;
5581 yaffs_BlockInfo *blk;
5583 struct list_head *i;
5586 for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
5588 blk = yaffs_GetBlockInfo(dev,b);
5590 switch(blk->blockState)
5592 case YAFFS_BLOCK_STATE_EMPTY:
5593 case YAFFS_BLOCK_STATE_ALLOCATING:
5594 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
5602 // To the free chunks add the chunks that are in the deleted unlinked files.
5603 list_for_each(i,&dev->deletedDir->variant.directoryVariant.children)
5607 l = list_entry(i, yaffs_Object,siblings);
5611 pending += l->nDataChunks;
5618 //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
5620 if(nFree != dev->nFreeChunks)
5622 // printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
5627 // Now count the number of dirty chunks in the cache and subtract those
5631 for(i = 0; i < dev->nShortOpCaches; i++)
5633 if(dev->srCache[i].dirty) nDirtyCacheChunks++;
5637 nFree -= nDirtyCacheChunks;
5639 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
5641 if(nFree < 0) nFree = 0;
5649 /////////////////// YAFFS test code //////////////////////////////////
5651 #define yaffs_CheckStruct(structure,syze, name) \
5652 if(sizeof(structure) != syze) \
5654 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
5655 return YAFFS_FAIL; \
5659 static int yaffs_CheckStructures(void)
5661 // yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
5662 // yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
5663 // yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
5664 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5665 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
5667 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
5674 void yaffs_GutsTest(yaffs_Device *dev)
5677 if(yaffs_CheckStructures() != YAFFS_OK)
5679 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
5683 yaffs_TnodeTest(dev);
5684 yaffs_ObjectTest(dev);