3 * YAFFS: Yet another FFS. A NAND-flash specific file system.
5 * Copyright (C) 2002 Aleph One Ltd.
6 * for Toby Churchill Ltd and Brightstar Engineering
8 * Created by Charles Manning <charles@aleph1.co.uk>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2 as
12 * published by the Free Software Foundation.
17 const char *yaffs_guts_c_version="$Id: yaffs_guts.c,v 1.4 2004-12-17 04:39:04 charles Exp $";
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
24 #include "yaffs_tagscompat.h"
26 #ifdef CONFIG_YAFFS_WINCE
27 void yfsd_LockYAFFS(BOOL fsLockOnly);
28 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
31 #define YAFFS_PASSIVE_GC_CHUNKS 2
34 // Use Steven Hill's ECC struff instead
35 // External functions for ECC on data
36 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
37 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
38 #define yaffs_ECCCalculate(data,ecc) nand_calculate_ecc(data,ecc)
39 #define yaffs_ECCCorrect(data,read_ecc,calc_ecc) nand_correct_ecc(data,read_ecc,calc_ecc)
41 #include "yaffs_ecc.h"
44 // countBits is a quick way of counting the number of bits in a byte.
45 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
47 static const char yaffs_countBitsTable[256] =
49 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
50 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
51 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
52 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
53 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
54 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
55 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
56 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
57 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
58 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
59 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
60 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
61 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
62 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
63 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
64 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
67 static int yaffs_CountBits(__u8 x)
70 retVal = yaffs_countBitsTable[x];
76 // Stuff using yea olde tags
77 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
78 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
80 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
81 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
88 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *buffer, yaffs_ExtendedTags *tags);
89 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *data, yaffs_ExtendedTags *tags);
90 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo);
91 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device *dev,int blockNo, yaffs_BlockState *state,unsigned *sequenceNumber);
93 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_ExtendedTags *tags, int useReserve);
94 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
95 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
97 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
98 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
99 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const YCHAR *name, int force,int isShrink);
100 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
101 static int yaffs_CheckStructures(void);
102 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
103 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
105 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
107 static __u8 *yaffs_GetTempBuffer(yaffs_Device *dev,int lineNo);
108 static void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo);
111 static int yaffs_ValidateTags(yaffs_ExtendedTags *tags);
113 // Robustification (if it ever comes about...)
114 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
115 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
116 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
117 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_ExtendedTags *tags);
118 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_ExtendedTags *tags);
120 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
122 static int yaffs_UnlinkWorker(yaffs_Object *obj);
123 static void yaffs_DestroyObject(yaffs_Object *obj);
126 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1,int dataSize);
129 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId, int chunkInObject);
132 loff_t yaffs_GetFileSize(yaffs_Object *obj);
135 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
137 #ifdef YAFFS_PARANOID
138 static int yaffs_CheckFileSanity(yaffs_Object *in);
140 #define yaffs_CheckFileSanity(in)
143 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
144 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
146 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *buffer, yaffs_ExtendedTags *tags)
148 if(dev->readChunkWithTagsFromNAND)
149 return dev->readChunkWithTagsFromNAND(dev,chunkInNAND,buffer,tags);
151 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,tags);
154 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_ExtendedTags *tags)
158 tags->sequenceNumber = dev->sequenceNumber;
160 if(!yaffs_ValidateTags(tags))
162 T(YAFFS_TRACE_ERROR,(TSTR("Writing uninitialised tags" TENDSTR)));
165 T(YAFFS_TRACE_WRITE,(TSTR("Writing chunk %d tags %d %d"TENDSTR),chunkInNAND,tags->objectId,tags->chunkId));
169 T(YAFFS_TRACE_ERROR,(TSTR("Writing with no tags" TENDSTR)));
173 if(dev->writeChunkWithTagsToNAND)
174 return dev->writeChunkWithTagsToNAND(dev,chunkInNAND,buffer,tags);
176 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,chunkInNAND,buffer,tags);
179 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo)
181 if(dev->markNANDBlockBad)
182 return dev->markNANDBlockBad(dev,blockNo);
184 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev,blockNo);
186 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device *dev,int blockNo, yaffs_BlockState *state, unsigned *sequenceNumber)
188 if(dev->queryNANDBlock)
189 return dev->queryNANDBlock(dev,blockNo,state,sequenceNumber);
191 return yaffs_TagsCompatabilityQueryNANDBlock(dev,blockNo,state,sequenceNumber);
194 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
198 dev->nBlockErasures++;
199 result = dev->eraseBlockInNAND(dev,blockInNAND);
201 if(!result)result = dev->eraseBlockInNAND(dev,blockInNAND); // If at first we don't succeed, try again *once*.
205 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
207 return dev->initialiseNAND(dev);
213 // Temporary buffer manipulations
215 static __u8 *yaffs_GetTempBuffer(yaffs_Device *dev,int lineNo)
218 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
220 if(dev->tempBuffer[i].line == 0)
222 dev->tempBuffer[i].line = lineNo;
223 if((i+1) > dev->maxTemp)
225 dev->maxTemp = i + 1;
226 for(j = 0; j <= i; j++)
227 dev->tempBuffer[j].maxLine = dev->tempBuffer[j].line;
230 return dev->tempBuffer[i].buffer;
234 T(YAFFS_TRACE_BUFFERS,(TSTR("Out of temp buffers at line %d, other held by lines:"),lineNo));
235 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
237 T(YAFFS_TRACE_BUFFERS,(TSTR(" %d "),dev->tempBuffer[i].line));
239 T(YAFFS_TRACE_BUFFERS,(TSTR(" "TENDSTR)));
241 dev->unmanagedTempAllocations++;
242 // Get an unmanaged one
243 return YMALLOC(dev->nBytesPerChunk);
248 static void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo)
251 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
253 if(dev->tempBuffer[i].buffer == buffer)
255 dev->tempBuffer[i].line = 0;
262 // assume it is an unmanaged one.
263 T(YAFFS_TRACE_BUFFERS,(TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),lineNo));
265 dev->unmanagedTempDeallocations++;
271 // Chunk bitmap manipulations
273 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
275 if(blk < dev->startBlock || blk > dev->endBlock)
277 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
280 return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->startBlock));
283 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
285 __u8 *blkBits = yaffs_BlockBits(dev,blk);
287 memset(blkBits,0,dev->chunkBitmapStride);
290 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev,int blk,int chunk)
292 __u8 *blkBits = yaffs_BlockBits(dev,blk);
294 blkBits[chunk/8] &= ~ (1<<(chunk & 7));
297 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
299 __u8 *blkBits = yaffs_BlockBits(dev,blk);
301 blkBits[chunk/8] |= (1<<(chunk & 7));
304 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
306 __u8 *blkBits = yaffs_BlockBits(dev,blk);
307 return (blkBits[chunk/8] & (1<<(chunk & 7))) ? 1 :0;
310 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
312 __u8 *blkBits = yaffs_BlockBits(dev,blk);
314 for(i = 0; i < dev->chunkBitmapStride; i++)
316 if(*blkBits) return 1;
323 // Function to manipulate block info
324 static Y_INLINE yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
326 if(blk < dev->startBlock || blk > dev->endBlock)
328 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),blk));
331 return &dev->blockInfo[blk - dev->startBlock];
336 static Y_INLINE int yaffs_HashFunction(int n)
338 return (n % YAFFS_NOBJECT_BUCKETS);
342 yaffs_Object *yaffs_Root(yaffs_Device *dev)
347 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
349 return dev->lostNFoundDir;
353 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
355 if(chunkInNAND < dev->startBlock * dev->nChunksPerBlock)
357 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
362 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
367 static int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
371 int doErrorCorrection)
374 yaffs_Spare localSpare;
383 // If we don't have a real spare, then we use a local one.
384 // Need this for the calculation of the ecc
391 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
392 if(data && doErrorCorrection)
395 //Todo handle any errors
396 int eccResult1,eccResult2;
399 yaffs_ECCCalculate(data,calcEcc);
400 eccResult1 = yaffs_ECCCorrect (data,spare->ecc1, calcEcc);
401 yaffs_ECCCalculate(&data[256],calcEcc);
402 eccResult2 = yaffs_ECCCorrect(&data[256],spare->ecc2, calcEcc);
406 T(YAFFS_TRACE_ERROR, (TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
409 else if(eccResult1<0)
411 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
417 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
420 else if(eccResult2<0)
422 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
426 if(eccResult1 || eccResult2)
428 // Hoosterman, we had a data problem on this page
429 yaffs_HandleReadDataError(dev,chunkInNAND);
435 // Must allocate enough memory for spare+2*sizeof(int) for ecc results from device.
436 struct yaffs_NANDSpare nspare;
437 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
438 memcpy (spare, &nspare, sizeof(yaffs_Spare));
439 if(data && doErrorCorrection)
443 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
445 else if(nspare.eccres1<0)
447 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
452 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
454 else if(nspare.eccres2<0)
456 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
459 if(nspare.eccres1 || nspare.eccres2)
461 // Hoosterman, we had a data problem on this page
462 yaffs_HandleReadDataError(dev,chunkInNAND);
474 int yaffs_CheckFF(__u8 *buffer,int nBytes)
476 //Horrible, slow implementation
479 if(*buffer != 0xFF) return 0;
485 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
488 int retval = YAFFS_OK;
489 __u8 *data = yaffs_GetTempBuffer(dev,__LINE__);
490 yaffs_ExtendedTags tags;
492 dev->readChunkWithTagsFromNAND(dev,chunkInNAND,data,&tags);
494 if(!yaffs_CheckFF(data,dev->nBytesPerChunk) || tags.chunkUsed)
496 T(YAFFS_TRACE_NANDACCESS,(TSTR("Chunk %d not erased" TENDSTR),chunkInNAND));
500 yaffs_ReleaseTempBuffer(dev,data,__LINE__);
509 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_ExtendedTags *tags,int useReserve)
519 chunk = yaffs_AllocateChunk(dev,useReserve);
524 // First check this chunk is erased...
525 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
526 writeOk = yaffs_CheckChunkErased(dev,chunk);
530 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
534 writeOk = yaffs_WriteChunkWithTagsToNAND(dev,chunk,data,tags);
540 // Copy the data into the robustification buffer.
541 // NB We do this at the end to prevent duplicates in the case of a write error.
543 yaffs_HandleWriteChunkOk(dev,chunk,data,tags);
547 yaffs_HandleWriteChunkError(dev,chunk);
551 } while(chunk >= 0 && ! writeOk);
555 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
556 dev->nRetriedWrites+= (attempts - 1);
567 // Functions for robustisizing
571 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
574 yaffs_MarkBlockBad(dev,blockInNAND);
576 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
578 dev->nRetiredBlocks++;
583 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
585 dev->doingBufferedBlockRewrite = 1;
587 // Remove erased chunks
588 // Rewrite existing chunks to a new block
589 // Set current write block to the new block
591 dev->doingBufferedBlockRewrite = 0;
597 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
599 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
601 // Mark the block for retirement
602 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
603 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
607 // Just do a garbage collection on the affected block then retire the block
612 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
616 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_ExtendedTags *tags)
620 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_ExtendedTags *tags)
624 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
626 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
628 // Mark the block for retirement
629 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
631 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
637 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1,int dataSize)
641 if( memcmp(d0,d1,dataSize) != 0 ||
642 s0->tagByte0 != s1->tagByte0 ||
643 s0->tagByte1 != s1->tagByte1 ||
644 s0->tagByte2 != s1->tagByte2 ||
645 s0->tagByte3 != s1->tagByte3 ||
646 s0->tagByte4 != s1->tagByte4 ||
647 s0->tagByte5 != s1->tagByte5 ||
648 s0->tagByte6 != s1->tagByte6 ||
649 s0->tagByte7 != s1->tagByte7 ||
650 s0->ecc1[0] != s1->ecc1[0] ||
651 s0->ecc1[1] != s1->ecc1[1] ||
652 s0->ecc1[2] != s1->ecc1[2] ||
653 s0->ecc2[0] != s1->ecc2[0] ||
654 s0->ecc2[1] != s1->ecc2[1] ||
655 s0->ecc2[2] != s1->ecc2[2] )
665 ///////////////////////// Object management //////////////////
666 // List of spare objects
667 // The list is hooked together using the first pointer
670 // static yaffs_Object *yaffs_freeObjects = NULL;
672 // static int yaffs_nFreeObjects;
674 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
676 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
679 static __u16 yaffs_CalcNameSum(const YCHAR *name)
684 YUCHAR *bname = (YUCHAR *)name;
687 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
690 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
691 sum += yaffs_toupper(*bname) * i;
702 void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
704 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
705 if(name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
707 yaffs_strcpy(obj->shortName,name);
711 obj->shortName[0]=_Y('\0');
714 obj->sum = yaffs_CalcNameSum(name);
718 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
720 yaffs_ECCCalculate(data , spare->ecc1);
721 yaffs_ECCCalculate(&data[256] , spare->ecc2);
726 ///////////////////////// TNODES ///////////////////////
728 // List of spare tnodes
729 // The list is hooked together using the first pointer
732 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
734 // static int yaffs_nFreeTnodes;
736 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
740 // yaffs_CreateTnodes creates a bunch more tnodes and
741 // adds them to the tnode free list.
742 // Don't use this function directly
744 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
747 yaffs_Tnode *newTnodes;
748 yaffs_TnodeList *tnl;
750 if(nTnodes < 1) return YAFFS_OK;
754 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
758 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
762 // Hook them into the free list
763 for(i = 0; i < nTnodes - 1; i++)
765 newTnodes[i].internal[0] = &newTnodes[i+1];
766 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
767 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = 1;
771 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
772 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
773 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = 1;
775 dev->freeTnodes = newTnodes;
776 dev->nFreeTnodes+= nTnodes;
777 dev->nTnodesCreated += nTnodes;
779 // Now add this bunch of tnodes to a list for freeing up.
780 // NB If we can't add this to the management list it isn't fatal
781 // but it just means we can't free this bunch of tnodes later.
782 tnl = YMALLOC(sizeof(yaffs_TnodeList));
785 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
790 tnl->tnodes = newTnodes;
791 tnl->next = dev->allocatedTnodeList;
792 dev->allocatedTnodeList = tnl;
796 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
803 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
804 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
806 yaffs_Tnode *tn = NULL;
808 // If there are none left make more
811 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
816 tn = dev->freeTnodes;
817 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
818 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 1)
820 // Hoosterman, this thing looks like it isn't in the list
821 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 1" TENDSTR)));
824 dev->freeTnodes = dev->freeTnodes->internal[0];
827 memset(tn,0,sizeof(yaffs_Tnode));
835 // FreeTnode frees up a tnode and puts it back on the free list
836 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
840 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
841 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 0)
843 // Hoosterman, this thing looks like it is already in the list
844 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 2" TENDSTR)));
846 tn->internal[YAFFS_NTNODES_INTERNAL] = 1;
848 tn->internal[0] = dev->freeTnodes;
849 dev->freeTnodes = tn;
855 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
857 // Free the list of allocated tnodes
858 yaffs_TnodeList *tmp;
860 while(dev->allocatedTnodeList)
862 tmp = dev->allocatedTnodeList->next;
864 YFREE(dev->allocatedTnodeList->tnodes);
865 YFREE(dev->allocatedTnodeList);
866 dev->allocatedTnodeList = tmp;
870 dev->freeTnodes = NULL;
871 dev->nFreeTnodes = 0;
874 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
876 dev->allocatedTnodeList = NULL;
877 dev->freeTnodes = NULL;
878 dev->nFreeTnodes = 0;
879 dev->nTnodesCreated = 0;
884 void yaffs_TnodeTest(yaffs_Device *dev)
889 yaffs_Tnode *tn[1000];
891 YINFO("Testing TNodes");
893 for(j = 0; j < 50; j++)
895 for(i = 0; i < 1000; i++)
897 tn[i] = yaffs_GetTnode(dev);
900 YALERT("Getting tnode failed");
903 for(i = 0; i < 1000; i+=3)
905 yaffs_FreeTnode(dev,tn[i]);
914 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
916 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
917 // The look up tree is represented by the top tnode and the number of topLevel
918 // in the tree. 0 means only the level 0 tnode is in the tree.
921 // FindLevel0Tnode finds the level 0 tnode, if one exists.
922 // Used when reading.....
923 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
926 yaffs_Tnode *tn = fStruct->top;
928 int requiredTallness;
929 int level = fStruct->topLevel;
931 // Check sane level and chunk Id
932 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
935 // sprintf(str,"Bad level %d",level);
940 if(chunkId > YAFFS_MAX_CHUNK_ID)
943 // sprintf(str,"Bad chunkId %d",chunkId);
948 // First check we're tall enough (ie enough topLevel)
950 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
951 requiredTallness = 0;
954 i >>= YAFFS_TNODES_INTERNAL_BITS;
959 if(requiredTallness > fStruct->topLevel)
961 // Not tall enough, so we can't find it, return NULL.
966 // Traverse down to level 0
967 while (level > 0 && tn)
969 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
970 YAFFS_TNODES_INTERNAL_MASK];
978 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
979 // This happens in two steps:
980 // 1. If the tree isn't tall enough, then make it taller.
981 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
983 // Used when modifying the tree.
985 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
990 int requiredTallness;
997 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
999 // Check sane level and page Id
1000 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1003 // sprintf(str,"Bad level %d",fStruct->topLevel);
1008 if(chunkId > YAFFS_MAX_CHUNK_ID)
1011 // sprintf(str,"Bad chunkId %d",chunkId);
1016 // First check we're tall enough (ie enough topLevel)
1018 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
1019 requiredTallness = 0;
1022 x >>= YAFFS_TNODES_INTERNAL_BITS;
1026 //T((TSTR(" required=%d"),requiredTallness));
1029 if(requiredTallness > fStruct->topLevel)
1031 // Not tall enough,gotta make the tree taller
1032 for(i = fStruct->topLevel; i < requiredTallness; i++)
1034 //T((TSTR(" add new top")));
1036 tn = yaffs_GetTnode(dev);
1040 tn->internal[0] = fStruct->top;
1045 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
1049 fStruct->topLevel = requiredTallness;
1053 // Traverse down to level 0, adding anything we need
1055 l = fStruct->topLevel;
1059 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
1060 YAFFS_TNODES_INTERNAL_MASK;
1062 //T((TSTR(" [%d:%d]"),l,i));
1064 if(!tn->internal[x])
1066 //T((TSTR(" added")));
1068 tn->internal[x] = yaffs_GetTnode(dev);
1071 tn = tn->internal[x];
1082 int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk, yaffs_ExtendedTags *tags, int objectId, int chunkInInode)
1087 for(j = 0; theChunk && j < dev->chunkGroupSize; j++)
1089 if(yaffs_CheckChunkBit(dev,theChunk / dev->nChunksPerBlock,theChunk % dev->nChunksPerBlock))
1091 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL,tags);
1092 if(yaffs_TagsMatch(tags,objectId,chunkInInode))
1104 // DeleteWorker scans backwards through the tnode tree and deletes all the
1105 // chunks and tnodes in the file
1106 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1108 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1113 yaffs_ExtendedTags tags;
1115 yaffs_Device *dev = in->myDev;
1125 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1129 if(limit && (*limit) < 0)
1135 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1136 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1140 yaffs_FreeTnode(dev,tn->internal[i]);
1141 tn->internal[i] = NULL;
1146 return (allDone) ? 1 : 0;
1152 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1157 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1159 theChunk = tn->level0[i] << dev->chunkGroupBits;
1161 foundChunk = yaffs_FindChunkInGroup(dev,theChunk,&tags,in->objectId,chunkInInode);
1165 yaffs_DeleteChunk(dev,foundChunk,1,__LINE__);
1182 return (i < 0) ? 1 : 0;
1194 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1197 yaffs_BlockInfo *theBlock;
1199 T(YAFFS_TRACE_DELETION,(TSTR("soft delete chunk %d" TENDSTR),chunk));
1201 theBlock = yaffs_GetBlockInfo(dev, chunk/dev->nChunksPerBlock);
1204 theBlock->softDeletions++;
1208 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1209 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1211 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1213 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1218 yaffs_Device *dev = in->myDev;
1226 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1230 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1231 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1234 yaffs_FreeTnode(dev,tn->internal[i]);
1235 tn->internal[i] = NULL;
1239 //Hoosterman... how could this happen.
1243 return (allDone) ? 1 : 0;
1248 for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1252 // Note this does not find the real chunk, only the chunk group.
1253 // We make an assumption that a chunk group is niot larger than a block.
1254 theChunk = (tn->level0[i] << dev->chunkGroupBits);
1256 yaffs_SoftDeleteChunk(dev,theChunk);
1273 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1276 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1279 if(obj->nDataChunks <= 0)
1281 // Empty file with no duplicate object headers, just delete it immediately
1282 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1283 obj->variant.fileVariant.top = NULL;
1284 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1285 yaffs_DoGenericObjectDeletion(obj);
1289 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1290 obj->softDeleted = 1;
1299 // Pruning removes any part of the file structure tree that is beyond the
1300 // bounds of the file (ie that does not point to chunks).
1302 // A file should only get pruned when its size is reduced.
1304 // Before pruning, the chunks must be pulled from the tree and the
1305 // level 0 tnode entries must be zeroed out.
1306 // Could also use this for file deletion, but that's probably better handled
1307 // by a special case.
1309 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1311 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1320 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1322 if(tn->internal[i] && level > 0)
1324 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1333 if(hasData == 0 && del0)
1335 // Free and return NULL
1337 yaffs_FreeTnode(dev,tn);
1347 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1354 if(fStruct->topLevel > 0)
1356 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1358 // Now we have a tree with all the non-zero branches NULL but the height
1359 // is the same as it was.
1360 // Let's see if we can trim internal tnodes to shorten the tree.
1361 // We can do this if only the 0th element in the tnode is in use
1362 // (ie all the non-zero are NULL)
1364 while(fStruct->topLevel && !done)
1369 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1379 fStruct->top = tn->internal[0];
1380 fStruct->topLevel--;
1381 yaffs_FreeTnode(dev,tn);
1397 /////////////////////// End of File Structure functions. /////////////////
1399 // yaffs_CreateFreeObjects creates a bunch more objects and
1400 // adds them to the object free list.
1401 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1404 yaffs_Object *newObjects;
1405 yaffs_ObjectList *list;
1407 if(nObjects < 1) return YAFFS_OK;
1409 // make these things
1411 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1415 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1419 // Hook them into the free list
1420 for(i = 0; i < nObjects - 1; i++)
1422 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1425 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1426 dev->freeObjects = newObjects;
1427 dev->nFreeObjects+= nObjects;
1428 dev->nObjectsCreated+= nObjects;
1430 // Now add this bunch of Objects to a list for freeing up.
1432 list = YMALLOC(sizeof(yaffs_ObjectList));
1435 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1439 list->objects = newObjects;
1440 list->next = dev->allocatedObjectList;
1441 dev->allocatedObjectList = list;
1450 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1451 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1453 yaffs_Object *tn = NULL;
1455 // If there are none left make more
1456 if(!dev->freeObjects)
1458 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1461 if(dev->freeObjects)
1463 tn = dev->freeObjects;
1464 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1465 dev->nFreeObjects--;
1467 // Now sweeten it up...
1469 memset(tn,0,sizeof(yaffs_Object));
1472 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1473 INIT_LIST_HEAD(&(tn->hardLinks));
1474 INIT_LIST_HEAD(&(tn->hashLink));
1475 INIT_LIST_HEAD(&tn->siblings);
1477 // Add it to the lost and found directory.
1478 // NB Can't put root or lostNFound in lostNFound so
1479 // check if lostNFound exists first
1480 if(dev->lostNFoundDir)
1482 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1490 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1493 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1496 obj->fake = 1; // it is fake so it has no NAND presence...
1497 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1498 obj->unlinkAllowed= 0; // ... or unlink it
1501 obj->st_mode = mode;
1503 obj->chunkId = 0; // Not a valid chunk.
1511 static void yaffs_UnhashObject(yaffs_Object *tn)
1514 yaffs_Device *dev = tn->myDev;
1517 // If it is still linked into the bucket list, free from the list
1518 if(!list_empty(&tn->hashLink))
1520 list_del_init(&tn->hashLink);
1521 bucket = yaffs_HashFunction(tn->objectId);
1522 dev->objectBucket[bucket].count--;
1528 // FreeObject frees up a Object and puts it back on the free list
1529 static void yaffs_FreeObject(yaffs_Object *tn)
1532 yaffs_Device *dev = tn->myDev;
1537 // We're still hooked up to a cached inode.
1538 // Don't delete now, but mark for later deletion
1539 tn->deferedFree = 1;
1544 yaffs_UnhashObject(tn);
1546 // Link into the free list.
1547 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1548 dev->freeObjects = tn;
1549 dev->nFreeObjects++;
1556 void yaffs_HandleDeferedFree(yaffs_Object *obj)
1558 if(obj->deferedFree)
1560 yaffs_FreeObject(obj);
1568 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1570 // Free the list of allocated Objects
1572 yaffs_ObjectList *tmp;
1574 while( dev->allocatedObjectList)
1576 tmp = dev->allocatedObjectList->next;
1577 YFREE(dev->allocatedObjectList->objects);
1578 YFREE(dev->allocatedObjectList);
1580 dev->allocatedObjectList = tmp;
1583 dev->freeObjects = NULL;
1584 dev->nFreeObjects = 0;
1587 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1591 dev->allocatedObjectList = NULL;
1592 dev->freeObjects = NULL;
1593 dev->nFreeObjects = 0;
1595 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1597 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1598 dev->objectBucket[i].count = 0;
1608 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1613 int lowest = 999999;
1616 // First let's see if we can find one that's empty.
1618 for(i = 0; i < 10 && lowest > 0; i++)
1621 x %= YAFFS_NOBJECT_BUCKETS;
1622 if(dev->objectBucket[x].count < lowest)
1624 lowest = dev->objectBucket[x].count;
1630 // If we didn't find an empty list, then try
1631 // looking a bit further for a short one
1633 for(i = 0; i < 10 && lowest > 3; i++)
1636 x %= YAFFS_NOBJECT_BUCKETS;
1637 if(dev->objectBucket[x].count < lowest)
1639 lowest = dev->objectBucket[x].count;
1648 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1650 int bucket = yaffs_FindNiceObjectBucket(dev);
1652 // Now find an object value that has not already been taken
1653 // by scanning the list.
1656 struct list_head *i;
1658 __u32 n = (__u32)bucket;
1660 //yaffs_CheckObjectHashSanity();
1665 n += YAFFS_NOBJECT_BUCKETS;
1666 if(1 ||dev->objectBucket[bucket].count > 0)
1668 list_for_each(i,&dev->objectBucket[bucket].list)
1670 // If there is already one in the list
1671 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1679 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1684 void yaffs_HashObject(yaffs_Object *in)
1686 int bucket = yaffs_HashFunction(in->objectId);
1687 yaffs_Device *dev = in->myDev;
1689 if(!list_empty(&in->hashLink))
1695 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1696 dev->objectBucket[bucket].count++;
1700 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1702 int bucket = yaffs_HashFunction(number);
1703 struct list_head *i;
1706 list_for_each(i,&dev->objectBucket[bucket].list)
1708 // Look if it is in the list
1711 in = list_entry(i, yaffs_Object,hashLink);
1712 if(in->objectId == number)
1724 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1727 yaffs_Object *theObject;
1731 number = yaffs_CreateNewObjectNumber(dev);
1734 theObject = yaffs_AllocateEmptyObject(dev);
1738 theObject->fake = 0;
1739 theObject->renameAllowed = 1;
1740 theObject->unlinkAllowed = 1;
1741 theObject->objectId = number;
1742 yaffs_HashObject(theObject);
1743 theObject->variantType = type;
1744 #ifdef CONFIG_YAFFS_WINCE
1745 yfsd_WinFileTimeNow(theObject->win_atime);
1746 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1747 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1751 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = Y_CURRENT_TIME;
1755 case YAFFS_OBJECT_TYPE_FILE:
1756 theObject->variant.fileVariant.fileSize = 0;
1757 theObject->variant.fileVariant.scannedFileSize = 0;
1758 theObject->variant.fileVariant.topLevel = 0;
1759 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1761 case YAFFS_OBJECT_TYPE_DIRECTORY:
1762 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1764 case YAFFS_OBJECT_TYPE_SYMLINK:
1765 // No action required
1767 case YAFFS_OBJECT_TYPE_HARDLINK:
1768 // No action required
1770 case YAFFS_OBJECT_TYPE_SPECIAL:
1771 // No action required
1773 case YAFFS_OBJECT_TYPE_UNKNOWN:
1774 // todo this should not happen
1782 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1784 yaffs_Object *theObject = NULL;
1788 theObject = yaffs_FindObjectByNumber(dev,number);
1793 theObject = yaffs_CreateNewObject(dev,number,type);
1800 YCHAR *yaffs_CloneString(const YCHAR *str)
1802 YCHAR *newStr = NULL;
1806 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1807 yaffs_strcpy(newStr,str);
1815 // Mknod (create) a new object.
1816 // equivalentObject only has meaning for a hard link;
1817 // aliasString only has meaning for a sumlink.
1818 // rdev only has meaning for devices (a subset of special objects)
1819 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1820 yaffs_Object *parent,
1825 yaffs_Object *equivalentObject,
1826 const YCHAR *aliasString,
1831 yaffs_Device *dev = parent->myDev;
1833 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1834 if(yaffs_FindObjectByName(parent,name))
1839 in = yaffs_CreateNewObject(dev,-1,type);
1845 in->variantType = type;
1849 #ifdef CONFIG_YAFFS_WINCE
1850 yfsd_WinFileTimeNow(in->win_atime);
1851 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1852 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1855 in->st_atime = in->st_mtime = in->st_ctime = Y_CURRENT_TIME;
1861 in->nDataChunks = 0;
1863 yaffs_SetObjectName(in,name);
1866 yaffs_AddObjectToDirectory(parent,in);
1868 in->myDev = parent->myDev;
1873 case YAFFS_OBJECT_TYPE_SYMLINK:
1874 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1876 case YAFFS_OBJECT_TYPE_HARDLINK:
1877 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1878 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1879 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1881 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1882 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1883 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1884 case YAFFS_OBJECT_TYPE_UNKNOWN:
1888 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1889 yaffs_UpdateObjectHeader(in,name,0,0) < 0)
1891 // Could not create the object header, fail the creation
1892 yaffs_DestroyObject(in);
1901 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid)
1903 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1906 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid)
1908 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1911 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1913 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1916 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid,const YCHAR *alias)
1918 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1921 // NB yaffs_Link returns the object id of the equivalent object.
1922 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name, yaffs_Object *equivalentObject)
1924 // Get the real object in case we were fed a hard link as an equivalent object
1925 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1927 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1929 return equivalentObject;
1939 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const YCHAR *newName,int force)
1946 newDir = obj->parent; // use the old directory
1949 // TODO: Do we need this different handling for YAFFS2 and YAFFS1??
1950 if(obj->myDev->isYaffs2)
1952 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1956 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1959 deleteOp = (newDir == obj->myDev->deletedDir);
1961 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1962 // duplicate names are allowed.
1963 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1967 !yaffs_FindObjectByName(newDir,newName)) &&
1968 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1970 yaffs_SetObjectName(obj,newName);
1973 yaffs_AddObjectToDirectory(newDir,obj);
1975 if(unlinkOp) obj->unlinked = 1;
1977 // If it is a dletion then we mark it as a shrink for gc purposes.
1978 if(yaffs_UpdateObjectHeader(obj,newName,0,deleteOp) >= 0)
1989 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName, yaffs_Object *newDir, const YCHAR *newName)
1994 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1995 // Special case for case insemsitive systems (eg. WinCE).
1996 // While look-up is case insensitive, the name isn't.
1997 // THerefore we might want to change x.txt to X.txt
1998 if(oldDir == newDir && yaffs_strcmp(oldName,newName) == 0)
2004 obj = yaffs_FindObjectByName(oldDir,oldName);
2005 if(obj && obj->renameAllowed)
2007 return yaffs_ChangeObjectName(obj,newDir,newName,force);
2014 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
2016 // Scan the buckets and check that the lists
2017 // have as many members as the count says there are
2020 struct list_head *j;
2023 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
2027 list_for_each(j,&dev->objectBucket[bucket].list)
2032 if(countEm != dev->objectBucket[bucket].count)
2034 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
2043 void yaffs_ObjectTest(yaffs_Device *dev)
2045 yaffs_Object *in[1000];
2047 yaffs_Object *inold[1000];
2051 memset(in,0,1000*sizeof(yaffs_Object *));
2052 memset(inold,0,1000*sizeof(yaffs_Object *));
2054 yaffs_CheckObjectHashSanity(dev);
2056 for(j = 0; j < 10; j++)
2060 for(i = 0; i < 1000; i++)
2062 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
2065 YINFO("No more inodes");
2069 inNo[i] = in[i]->objectId;
2073 for(i = 0; i < 1000; i++)
2075 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
2077 //T(("Differnce in look up test\n"));
2081 // T(("Look up ok\n"));
2085 yaffs_CheckObjectHashSanity(dev);
2087 for(i = 0; i < 1000; i+=3)
2089 yaffs_FreeObject(in[i]);
2094 yaffs_CheckObjectHashSanity(dev);
2101 /////////////////////////// Block Management and Page Allocation ///////////////////
2104 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
2106 dev->allocationBlock = -1; // force it to get a new one
2107 //Todo we're assuming the malloc will pass.
2108 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2109 // Set up dynamic blockinfo stuff.
2110 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
2111 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2112 if(dev->blockInfo && dev->chunkBits)
2114 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
2115 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
2123 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2125 YFREE(dev->blockInfo);
2126 dev->blockInfo = NULL;
2127 YFREE(dev->chunkBits);
2128 dev->chunkBits = NULL;
2132 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev, yaffs_BlockInfo *bi)
2138 if(!dev->isYaffs2) return 1; // disqualification only applies to yaffs2.
2140 if(!bi->hasShrinkHeader) return 1; // can gc
2143 // Find the oldest dirty sequence number if we don't know it and save it
2144 // so we don't have to keep recomputing it.
2145 if(!dev->oldestDirtySequence)
2147 seq = dev->sequenceNumber;
2149 for(i = dev->startBlock; i <= dev->endBlock; i++)
2151 b = yaffs_GetBlockInfo(dev,i);
2152 if(b->blockState == YAFFS_BLOCK_STATE_FULL &&
2153 (b->pagesInUse - b->softDeletions )< dev->nChunksPerBlock &&
2154 b->sequenceNumber < seq)
2156 seq = b->sequenceNumber;
2159 dev->oldestDirtySequence = seq;
2163 // Can't do gc of this block if there are any blocks older than this one that have
2165 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2172 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
2173 // for garbage collection.
2178 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,int aggressive)
2181 int b = dev->currentDirtyChecker;
2187 yaffs_BlockInfo *bi;
2188 static int nonAggressiveSkip = 0;
2190 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2192 // else (we're doing a leasurely gc), then we only bother to do this if the
2193 // block has only a few pages in use.
2196 nonAggressiveSkip--;
2198 if(!aggressive &&(nonAggressiveSkip > 0))
2203 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2206 iterations = dev->endBlock - dev->startBlock + 1;
2210 iterations = dev->endBlock - dev->startBlock + 1;
2211 iterations = iterations / 16;
2212 if(iterations > 200)
2218 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2221 if ( b < dev->startBlock || b > dev->endBlock)
2223 b = dev->startBlock;
2226 if(b < dev->startBlock || b > dev->endBlock)
2228 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2232 bi = yaffs_GetBlockInfo(dev,b);
2234 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2235 (bi->pagesInUse - bi->softDeletions )< pagesInUse &&
2236 yaffs_BlockNotDisqualifiedFromGC(dev,bi))
2239 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2243 dev->currentDirtyChecker = b;
2247 T(YAFFS_TRACE_GC,(TSTR("GC Selected block %d with %d free" TENDSTR),dirtiest,dev->nChunksPerBlock - pagesInUse));
2250 dev->oldestDirtySequence = 0; // clear this
2254 nonAggressiveSkip = 4;
2261 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2263 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2267 // If the block is still healthy erase it and mark as clean.
2268 // If the block has had a data failure, then retire it.
2269 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2271 if(!bi->needsRetiring)
2273 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2276 dev->nErasureFailures++;
2277 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2281 if(erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE))
2284 for(i = 0; i < dev->nChunksPerBlock; i++)
2286 if(!yaffs_CheckChunkErased(dev,blockNo * dev->nChunksPerBlock + i))
2288 T(YAFFS_TRACE_ERROR,(TSTR(">>Block %d erasure supposedly OK, but chunk %d not erased" TENDSTR),blockNo,i));
2296 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2297 dev->nErasedBlocks++;
2299 bi->softDeletions = 0;
2300 bi->hasShrinkHeader=0;
2301 yaffs_ClearChunkBits(dev,blockNo);
2303 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2307 yaffs_RetireBlock(dev,blockNo);
2308 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2312 static void yaffs_DumpBlockStats(yaffs_Device *dev)
2315 yaffs_BlockInfo *bi;
2317 for(i= dev->startBlock; i <=dev->endBlock; i++)
2319 bi = yaffs_GetBlockInfo(dev,i);
2320 T(YAFFS_TRACE_ALLOCATE,(TSTR("%3d state %d shrink %d inuse %d/%d seq %d pages"),i,
2321 bi->blockState,bi->hasShrinkHeader,bi->pagesInUse,bi->softDeletions,bi->sequenceNumber));
2323 for(j = 0; j < dev->nChunksPerBlock; j++)
2325 if(yaffs_CheckChunkBit(dev,i,j))
2327 T(YAFFS_TRACE_ALLOCATE,(TSTR(" %d"),j));
2331 T(YAFFS_TRACE_ALLOCATE,(TSTR(" " TENDSTR)));
2337 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2341 yaffs_BlockInfo *bi;
2346 if(j < 0 || j > 100)
2349 yaffs_DumpBlockStats(dev);
2354 if(dev->nErasedBlocks < 1)
2356 // Hoosterman we've got a problem.
2357 // Can't get space to gc
2358 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2363 // Find an empty block.
2365 for(i = dev->startBlock; i <= dev->endBlock; i++)
2367 dev->allocationBlockFinder++;
2368 if(dev->allocationBlockFinder < dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2370 dev->allocationBlockFinder = dev->startBlock;
2373 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2375 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2377 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2378 dev->sequenceNumber++;
2379 bi->sequenceNumber = dev->sequenceNumber;
2380 dev->nErasedBlocks--;
2381 T(YAFFS_TRACE_ALLOCATE,(TSTR("Allocated block %d, seq %d" TENDSTR),dev->allocationBlockFinder,dev->sequenceNumber));
2382 return dev->allocationBlockFinder;
2385 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no more eraased blocks, but there should have been one" TENDSTR)));
2393 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2396 yaffs_BlockInfo *bi;
2398 if(dev->allocationBlock < 0)
2400 // Get next block to allocate off
2401 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2402 dev->allocationPage = 0;
2405 if(!useReserve && dev->nErasedBlocks </*=*/ dev->nReservedBlocks)
2407 // Not enough space to allocate unless we're allowed to use the reserve.
2411 if(dev->nErasedBlocks < dev->nReservedBlocks && dev->allocationPage == 0)
2413 T(YAFFS_TRACE_ALLOCATE,(TSTR("Allocating reserve" TENDSTR)));
2417 // Next page please....
2418 if(dev->allocationBlock >= 0)
2420 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2422 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2423 dev->allocationPage;
2425 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2427 dev->allocationPage++;
2431 // If the block is full set the state to full
2432 if(dev->allocationPage >= dev->nChunksPerBlock)
2434 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2435 dev->allocationBlock = -1;
2442 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2448 // To determine if we have enough space we just look at the
2449 // number of erased blocks.
2450 // The cache is allowed to use reserved blocks.
2452 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2454 return (dev->nErasedBlocks >= dev->nReservedBlocks);
2458 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2462 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2464 if(dev->allocationBlock> 0)
2466 n += (dev->nChunksPerBlock - dev->allocationPage);
2473 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2479 int retVal = YAFFS_OK;
2483 int chunksBefore = yaffs_GetErasedChunks(dev);
2486 yaffs_ExtendedTags tags;
2488 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2490 yaffs_Object *object;
2492 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2494 T(YAFFS_TRACE_TRACING,(TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR),block,bi->pagesInUse,bi->hasShrinkHeader));
2495 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2497 bi->hasShrinkHeader = 0; // clear the flag so that the block can erase
2500 if(!yaffs_StillSomeChunkBits(dev,block))
2502 T(YAFFS_TRACE_TRACING,(TSTR("Collecting block %d that has no chunks in use" TENDSTR),block));
2503 yaffs_BlockBecameDirty(dev,block);
2508 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
2510 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2511 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2512 chunkInBlock++, oldChunk++ )
2514 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2517 // This page is in use and might need to be copied off
2521 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2523 yaffs_InitialiseTags(&tags);
2525 yaffs_ReadChunkWithTagsFromNAND(dev,oldChunk,buffer, &tags);
2527 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2529 T(YAFFS_TRACE_GC_DETAIL,(TSTR("Collecting page %d, %d %d %d " TENDSTR),chunkInBlock,tags.objectId,tags.chunkId,tags.byteCount));
2533 T(YAFFS_TRACE_ERROR,(TSTR("page %d in gc has no object " TENDSTR),oldChunk));
2536 if(object && object->deleted && tags.chunkId != 0)
2538 // Data chunk in a deleted file, throw it away
2539 // It's a deleted data chunk,
2540 // No need to copy this, just forget about it and fix up the
2543 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2544 object->nDataChunks--;
2546 if(object->nDataChunks <= 0)
2548 // remeber to clean up the object
2549 dev->gcCleanupList[cleanups] = tags.objectId;
2554 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2556 // Deleted object header with no data chunks.
2557 // Can be discarded and the file deleted.
2558 object->chunkId = 0;
2559 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2560 object->variant.fileVariant.top = NULL;
2561 yaffs_DoGenericObjectDeletion(object);
2566 // It's either a data chunk in a live file or
2567 // an ObjectHeader, so we're interested in it.
2568 // NB Need to keep the ObjectHeaders of deleted files
2569 // until the whole file has been deleted off
2570 tags.serialNumber++;
2574 newChunk = yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags,1);
2578 retVal = YAFFS_FAIL;
2583 // Ok, now fix up the Tnodes etc.
2585 if(tags.chunkId == 0)
2588 object->chunkId = newChunk;
2589 object->serial = tags.serialNumber;
2593 // It's a data chunk
2594 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2599 yaffs_DeleteChunk(dev,oldChunk,markNAND,__LINE__);
2604 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
2607 // Do any required cleanups
2608 for(i = 0; i < cleanups; i++)
2610 // Time to delete the file too
2611 object = yaffs_FindObjectByNumber(dev,dev->gcCleanupList[i]);
2614 yaffs_FreeTnode(dev,object->variant.fileVariant.top);
2615 object->variant.fileVariant.top = NULL;
2616 T(YAFFS_TRACE_GC,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2617 yaffs_DoGenericObjectDeletion(object);
2624 if(chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev)))
2626 T(YAFFS_TRACE_GC,(TSTR("gc did not increase free chunks before %d after %d" TENDSTR),chunksBefore,chunksAfter));
2633 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2635 // find a file to delete
2636 struct list_head *i;
2640 //Scan the unlinked files looking for one to delete
2641 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2645 l = list_entry(i, yaffs_Object,siblings);
2656 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2658 // This does background deletion on unlinked files.. only deleted ones.
2659 // If we don't have a file we're working on then find one
2660 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2662 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2665 // OK, we're working on a file...
2666 if(dev->unlinkedDeletion)
2668 yaffs_Object *obj = dev->unlinkedDeletion;
2670 int limit; // Number of chunks to delete in a file.
2671 // NB this can be exceeded, but not by much.
2675 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2677 if(obj->nDataChunks == 0)
2679 // Done all the deleting of data chunks.
2680 // Now dump the header and clean up
2681 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2682 obj->variant.fileVariant.top = NULL;
2683 yaffs_DoGenericObjectDeletion(obj);
2684 dev->nDeletedFiles--;
2685 dev->nUnlinkedFiles--;
2686 dev->nBackgroundDeletions++;
2687 dev->unlinkedDeletion = NULL;
2695 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
2696 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2701 //yaffs_DoUnlinkedFileDeletion(dev);
2703 if(dev->nErasedBlocks <= (dev->nReservedBlocks + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2710 block = yaffs_FindBlockForGarbageCollection(dev,aggressive);
2714 dev->garbageCollections++;
2715 return yaffs_GarbageCollectBlock(dev,block);
2727 // New garbage collector
2728 // If we're very low on erased blocks then we do aggressive garbage collection
2729 // otherwise we do "leasurely" garbage collection.
2730 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2731 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2733 // The idea is to help clear out space in a more spread-out manner.
2734 // Dunno if it really does anything useful.
2736 int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2740 int gcOk = YAFFS_OK;
2743 //yaffs_DoUnlinkedFileDeletion(dev);
2745 // This loop should pass the first time.
2746 // We'll only see looping here if the erase of the collected block fails.
2750 if(dev->nErasedBlocks <= (dev->nReservedBlocks + 2))
2752 // We need a block soon...
2757 // We're in no hurry
2761 block = yaffs_FindBlockForGarbageCollection(dev,aggressive);
2765 dev->garbageCollections++;
2768 dev->passiveGarbageCollections++;
2771 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2773 gcOk = yaffs_GarbageCollectBlock(dev,block);
2776 if(dev->nErasedBlocks <= (dev->nReservedBlocks + 1))
2778 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d" TENDSTR),dev->nErasedBlocks,maxTries,block));
2780 } while((dev->nErasedBlocks <= (dev->nReservedBlocks + 1)) && (block > 0) && (maxTries < 5));
2782 return aggressive ? gcOk: YAFFS_OK;
2786 //////////////////////////// TAGS ///////////////////////////////////////
2789 void yaffs_InitialiseTags(yaffs_ExtendedTags *tags)
2791 memset(tags,0,sizeof(yaffs_ExtendedTags));
2792 tags->validMarker0 = 0xAAAAAAAA;
2793 tags->validMarker1 = 0x55555555;
2796 static int yaffs_ValidateTags(yaffs_ExtendedTags *tags)
2798 return (tags->validMarker0 == 0xAAAAAAAA && tags->validMarker1 == 0x55555555);
2805 void yaffs_CalcTagsECC(yaffs_Tags *tags)
2809 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
2816 for(i = 0; i < 8; i++)
2818 for(j = 1; j &0xff; j<<=1)
2833 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
2835 unsigned ecc = tags->ecc;
2837 yaffs_CalcTagsECC(tags);
2841 if(ecc && ecc <= 64)
2843 // TODO: Handle the failure better. Retire?
2844 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
2848 b[ecc / 8] ^= (1 << (ecc & 7));
2850 // Now recvalc the ecc
2851 yaffs_CalcTagsECC(tags);
2853 return 1; // recovered error
2857 // Wierd ecc failure value
2858 // TODO Need to do somethiong here
2859 return -1; //unrecovered error
2865 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2867 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2869 yaffs_CalcTagsECC(tagsPtr);
2871 sparePtr->tagByte0 = tu->asBytes[0];
2872 sparePtr->tagByte1 = tu->asBytes[1];
2873 sparePtr->tagByte2 = tu->asBytes[2];
2874 sparePtr->tagByte3 = tu->asBytes[3];
2875 sparePtr->tagByte4 = tu->asBytes[4];
2876 sparePtr->tagByte5 = tu->asBytes[5];
2877 sparePtr->tagByte6 = tu->asBytes[6];
2878 sparePtr->tagByte7 = tu->asBytes[7];
2881 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2883 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2886 tu->asBytes[0]= sparePtr->tagByte0;
2887 tu->asBytes[1]= sparePtr->tagByte1;
2888 tu->asBytes[2]= sparePtr->tagByte2;
2889 tu->asBytes[3]= sparePtr->tagByte3;
2890 tu->asBytes[4]= sparePtr->tagByte4;
2891 tu->asBytes[5]= sparePtr->tagByte5;
2892 tu->asBytes[6]= sparePtr->tagByte6;
2893 tu->asBytes[7]= sparePtr->tagByte7;
2895 result = yaffs_CheckECCOnTags(tagsPtr);
2898 dev->tagsEccFixed++;
2902 dev->tagsEccUnfixed++;
2906 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2908 memset(spare,0xFF,sizeof(yaffs_Spare));
2914 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_ExtendedTags *tags, int useReserve)
2916 // NB There must be tags, data is optional
2917 // If there is data, then an ECC is calculated on it.
2926 //yaffs_SpareInitialise(&spare);
2928 //if(!dev->useNANDECC && buffer)
2930 // yaffs_CalcECC(buffer,&spare);
2933 //yaffs_LoadTagsIntoSpare(&spare,tags);
2935 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2940 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId, int chunkInObject)
2942 return ( tags->chunkId == chunkInObject &&
2943 tags->objectId == objectId &&
2944 !tags->chunkDeleted) ? 1 : 0;
2950 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_ExtendedTags *tags)
2952 //Get the Tnode, then get the level 0 offset chunk offset
2955 yaffs_ExtendedTags localTags;
2958 yaffs_Device *dev = in->myDev;
2963 // Passed a NULL, so use our own tags space
2967 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2971 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2973 retVal = yaffs_FindChunkInGroup(dev,theChunk,tags,in->objectId,chunkInInode);
2978 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_ExtendedTags *tags)
2980 //Get the Tnode, then get the level 0 offset chunk offset
2983 yaffs_ExtendedTags localTags;
2985 yaffs_Device *dev = in->myDev;
2990 // Passed a NULL, so use our own tags space
2994 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2999 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
3001 retVal = yaffs_FindChunkInGroup(dev,theChunk,tags,in->objectId,chunkInInode);
3003 // Delete the entry in the filestructure (if found)
3006 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
3011 //T(("No level 0 found for %d\n", chunkInInode));
3016 //T(("Could not find %d to delete\n",chunkInInode));
3022 #ifdef YAFFS_PARANOID
3024 static int yaffs_CheckFileSanity(yaffs_Object *in)
3032 yaffs_Tags localTags;
3033 yaffs_Tags *tags = &localTags;
3038 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3040 //T(("Object not a file\n"));
3044 objId = in->objectId;
3045 fSize = in->variant.fileVariant.fileSize;
3046 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
3048 for(chunk = 1; chunk <= nChunks; chunk++)
3050 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
3055 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
3057 if(yaffs_CheckChunkBits(dev,theChunk/dev->nChunksPerBlock,theChunk%dev->nChunksPerBlock))
3061 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
3062 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
3070 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
3071 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
3080 //T(("No level 0 found for %d\n", chunk));
3084 return failed ? YAFFS_FAIL : YAFFS_OK;
3089 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
3092 yaffs_Device *dev = in->myDev;
3094 yaffs_ExtendedTags existingTags;
3095 yaffs_ExtendedTags newTags;
3096 unsigned existingSerial, newSerial;
3098 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
3104 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
3108 // If we're scanning then we need to test for duplicates
3109 // NB This does not need to be efficient since it should only ever
3110 // happen when the power fails during a write, then only one
3111 // chunk should ever be affected.
3114 if(existingChunk != 0)
3116 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
3117 // thus we have to do a FindChunkInFile to get the real chunk id.
3119 // We have a duplicate now we need to decide which one to use
3120 // To do this we get both sets of tags and compare serial numbers.
3121 yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND, NULL,&newTags);
3125 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
3127 if(existingChunk <=0)
3129 //Hoosterman - how did this happen?
3131 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
3136 // NB The deleted flags should be false, otherwise the chunks will
3137 // not be loaded during a scan
3139 newSerial = newTags.serialNumber;
3140 existingSerial = existingTags.serialNumber;
3142 if( in->myDev->isYaffs2 ||
3143 existingChunk <= 0 ||
3144 ((existingSerial+1) & 3) == newSerial)
3147 // Delete the old one and drop through to update the tnode
3148 yaffs_DeleteChunk(dev,existingChunk,1,__LINE__);
3153 // Delete the new one and return early so that the tnode isn't changed
3154 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
3161 if(existingChunk == 0)
3166 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
3173 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
3175 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
3177 if(chunkInNAND >= 0)
3179 return yaffs_ReadChunkWithTagsFromNAND(in->myDev,chunkInNAND,buffer,NULL);
3183 T(YAFFS_TRACE_NANDACCESS,(TSTR("Chunk %d not found zero instead" TENDSTR),chunkInNAND));
3185 memset(buffer,0,in->myDev->nBytesPerChunk); // get sane data if you read a hole
3192 void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND,int lyn)
3196 yaffs_ExtendedTags tags;
3197 yaffs_BlockInfo *bi;
3199 if(chunkId <= 0) return;
3202 block = chunkId / dev->nChunksPerBlock;
3203 page = chunkId % dev->nChunksPerBlock;
3205 bi = yaffs_GetBlockInfo(dev,block);
3207 T(YAFFS_TRACE_DELETION,(TSTR("line %d delete of chunk %d" TENDSTR),lyn,chunkId));
3210 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
3213 // yaffs_SpareInitialise(&spare);
3215 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
3217 //read data before write, to ensure correct ecc
3218 //if we're using MTD verification under Linux
3219 yaffs_ReadChunkFromNAND(dev,chunkId,NULL,&spare,0);
3222 yaffs_InitialiseTags(&tags);
3224 tags.chunkDeleted = 1;
3227 yaffs_WriteChunkWithTagsToNAND(dev,chunkId,NULL,&tags);
3228 yaffs_HandleUpdateChunk(dev,chunkId,&tags);
3232 dev->nUnmarkedDeletions++;
3236 // Pull out of the management area.
3237 // If the whole block became dirty, this will kick off an erasure.
3238 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3239 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3240 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3241 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)
3245 yaffs_ClearChunkBit(dev,block,page);
3248 if(bi->pagesInUse == 0 &&
3249 !bi->hasShrinkHeader &&
3250 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3251 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING)
3253 yaffs_BlockBecameDirty(dev,block);
3259 // T(("Bad news deleting chunk %d\n",chunkId));
3267 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
3269 // Find old chunk Need to do this to get serial number
3270 // Write new one and patch into tree.
3271 // Invalidate old tags.
3274 yaffs_ExtendedTags prevTags;
3277 yaffs_ExtendedTags newTags;
3279 yaffs_Device *dev = in->myDev;
3281 yaffs_CheckGarbageCollection(dev);
3283 // Get the previous chunk at this location in the file if it exists
3284 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
3287 yaffs_InitialiseTags(&newTags);
3289 newTags.chunkId = chunkInInode;
3290 newTags.objectId = in->objectId;
3291 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3292 newTags.byteCount = nBytes;
3294 // yaffs_CalcTagsECC(&newTags);
3296 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
3300 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
3303 if(prevChunkId >= 0)
3305 yaffs_DeleteChunk(dev,prevChunkId,1,__LINE__);
3309 yaffs_CheckFileSanity(in);
3320 // UpdateObjectHeader updates the header on NAND for an object.
3321 // If name is not NULL, then that new name is used.
3323 int yaffs_UpdateObjectHeader(yaffs_Object *in,const YCHAR *name, int force,int isShrink)
3326 yaffs_BlockInfo *bi;
3328 yaffs_Device *dev = in->myDev;
3334 yaffs_ExtendedTags newTags;
3336 __u8 *buffer = NULL;
3337 YCHAR oldName[YAFFS_MAX_NAME_LENGTH+1];
3339 // __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
3341 yaffs_ObjectHeader *oh = NULL;
3342 // yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
3345 if(!in->fake || force)
3348 yaffs_CheckGarbageCollection(dev);
3350 buffer = yaffs_GetTempBuffer(in->myDev,__LINE__);
3351 oh = (yaffs_ObjectHeader *)buffer;
3353 prevChunkId = in->chunkId;
3355 if(prevChunkId >= 0)
3357 yaffs_ReadChunkWithTagsFromNAND(dev,prevChunkId,buffer,NULL);
3358 memcpy(oldName,oh->name,sizeof(oh->name));
3361 memset(buffer,0xFF,dev->nBytesPerChunk);
3364 oh->type = in->variantType;
3366 oh->st_mode = in->st_mode;
3368 #ifdef CONFIG_YAFFS_WINCE
3369 oh->win_atime[0] = in->win_atime[0];
3370 oh->win_ctime[0] = in->win_ctime[0];
3371 oh->win_mtime[0] = in->win_mtime[0];
3372 oh->win_atime[1] = in->win_atime[1];
3373 oh->win_ctime[1] = in->win_ctime[1];
3374 oh->win_mtime[1] = in->win_mtime[1];
3376 oh->st_uid = in->st_uid;
3377 oh->st_gid = in->st_gid;
3378 oh->st_atime = in->st_atime;
3379 oh->st_mtime = in->st_mtime;
3380 oh->st_ctime = in->st_ctime;
3381 oh->st_rdev = in->st_rdev;
3385 oh->parentObjectId = in->parent->objectId;
3389 oh->parentObjectId = 0;
3392 //oh->sum = in->sum;
3395 memset(oh->name,0,sizeof(oh->name));
3396 yaffs_strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3398 else if(prevChunkId)
3400 memcpy(oh->name, oldName,sizeof(oh->name));
3404 memset(oh->name,0,sizeof(oh->name));
3407 oh->isShrink = isShrink;
3409 switch(in->variantType)
3411 case YAFFS_OBJECT_TYPE_UNKNOWN:
3412 // Should not happen
3414 case YAFFS_OBJECT_TYPE_FILE:
3415 oh->fileSize = in->variant.fileVariant.fileSize;
3417 case YAFFS_OBJECT_TYPE_HARDLINK:
3418 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3420 case YAFFS_OBJECT_TYPE_SPECIAL:
3423 case YAFFS_OBJECT_TYPE_DIRECTORY:
3426 case YAFFS_OBJECT_TYPE_SYMLINK:
3427 yaffs_strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3428 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3433 yaffs_InitialiseTags(&newTags);
3435 newTags.chunkId = 0;
3436 newTags.objectId = in->objectId;
3437 newTags.serialNumber = in->serial;
3440 // Create new chunk in NAND
3441 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3446 in->chunkId = newChunkId;
3448 if(prevChunkId >= 0)
3450 yaffs_DeleteChunk(dev,prevChunkId,1,__LINE__);
3455 // If this was a shrink, then mark the block that the chunk lives on
3458 bi = yaffs_GetBlockInfo(in->myDev,newChunkId / in->myDev->nChunksPerBlock);