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.6 2005-04-24 09:57:06 charles Exp $";
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
23 #include "yaffs_tagsvalidity.h"
26 #include "yaffs_tagscompat.h"
28 #ifdef CONFIG_YAFFS_WINCE
29 void yfsd_LockYAFFS(BOOL fsLockOnly);
30 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
33 #define YAFFS_PASSIVE_GC_CHUNKS 2
36 // Use Steven Hill's ECC struff instead
37 // External functions for ECC on data
38 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
39 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
40 #define yaffs_ECCCalculate(data,ecc) nand_calculate_ecc(data,ecc)
41 #define yaffs_ECCCorrect(data,read_ecc,calc_ecc) nand_correct_ecc(data,read_ecc,calc_ecc)
43 #include "yaffs_ecc.h"
47 // countBits is a quick way of counting the number of bits in a byte.
48 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
50 static const char yaffs_countBitsTable[256] =
52 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
53 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
54 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
55 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
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 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
61 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
62 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
63 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
64 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
65 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
66 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
67 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
70 static int yaffs_CountBits(__u8 x)
73 retVal = yaffs_countBitsTable[x];
81 // Stuff using yea olde tags
82 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
83 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
85 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
86 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
93 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *buffer, yaffs_ExtendedTags *tags);
94 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *data, yaffs_ExtendedTags *tags);
95 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo);
96 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device *dev,int blockNo, yaffs_BlockState *state,unsigned *sequenceNumber);
98 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_ExtendedTags *tags, int useReserve);
100 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
102 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
104 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
105 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
106 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const YCHAR *name, int force,int isShrink);
107 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
108 static int yaffs_CheckStructures(void);
109 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
110 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
112 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
114 static __u8 *yaffs_GetTempBuffer(yaffs_Device *dev,int lineNo);
115 static void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo);
118 // Robustification (if it ever comes about...)
119 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
121 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
123 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
124 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_ExtendedTags *tags);
125 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_ExtendedTags *tags);
127 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
129 static int yaffs_UnlinkWorker(yaffs_Object *obj);
130 static void yaffs_DestroyObject(yaffs_Object *obj);
133 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1,int dataSize);
136 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId, int chunkInObject);
139 loff_t yaffs_GetFileSize(yaffs_Object *obj);
142 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
144 #ifdef YAFFS_PARANOID
145 static int yaffs_CheckFileSanity(yaffs_Object *in);
147 #define yaffs_CheckFileSanity(in)
150 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
151 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
153 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *buffer, yaffs_ExtendedTags *tags)
155 if(dev->readChunkWithTagsFromNAND)
156 return dev->readChunkWithTagsFromNAND(dev,chunkInNAND,buffer,tags);
158 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,tags);
161 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_ExtendedTags *tags)
165 tags->sequenceNumber = dev->sequenceNumber;
167 if(!yaffs_ValidateTags(tags))
169 T(YAFFS_TRACE_ERROR,(TSTR("Writing uninitialised tags" TENDSTR)));
172 T(YAFFS_TRACE_WRITE,(TSTR("Writing chunk %d tags %d %d"TENDSTR),chunkInNAND,tags->objectId,tags->chunkId));
176 T(YAFFS_TRACE_ERROR,(TSTR("Writing with no tags" TENDSTR)));
180 if(dev->writeChunkWithTagsToNAND)
181 return dev->writeChunkWithTagsToNAND(dev,chunkInNAND,buffer,tags);
183 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,chunkInNAND,buffer,tags);
186 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo)
188 if(dev->markNANDBlockBad)
189 return dev->markNANDBlockBad(dev,blockNo);
191 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev,blockNo);
193 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device *dev,int blockNo, yaffs_BlockState *state, unsigned *sequenceNumber)
195 if(dev->queryNANDBlock)
196 return dev->queryNANDBlock(dev,blockNo,state,sequenceNumber);
198 return yaffs_TagsCompatabilityQueryNANDBlock(dev,blockNo,state,sequenceNumber);
201 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
205 dev->nBlockErasures++;
206 result = dev->eraseBlockInNAND(dev,blockInNAND);
208 if(!result)result = dev->eraseBlockInNAND(dev,blockInNAND); // If at first we don't succeed, try again *once*.
212 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
214 return dev->initialiseNAND(dev);
220 // Temporary buffer manipulations
222 static __u8 *yaffs_GetTempBuffer(yaffs_Device *dev,int lineNo)
225 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
227 if(dev->tempBuffer[i].line == 0)
229 dev->tempBuffer[i].line = lineNo;
230 if((i+1) > dev->maxTemp)
232 dev->maxTemp = i + 1;
233 for(j = 0; j <= i; j++)
234 dev->tempBuffer[j].maxLine = dev->tempBuffer[j].line;
237 return dev->tempBuffer[i].buffer;
241 T(YAFFS_TRACE_BUFFERS,(TSTR("Out of temp buffers at line %d, other held by lines:"),lineNo));
242 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
244 T(YAFFS_TRACE_BUFFERS,(TSTR(" %d "),dev->tempBuffer[i].line));
246 T(YAFFS_TRACE_BUFFERS,(TSTR(" "TENDSTR)));
248 dev->unmanagedTempAllocations++;
249 // Get an unmanaged one
250 return YMALLOC(dev->nBytesPerChunk);
255 static void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo)
258 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
260 if(dev->tempBuffer[i].buffer == buffer)
262 dev->tempBuffer[i].line = 0;
269 // assume it is an unmanaged one.
270 T(YAFFS_TRACE_BUFFERS,(TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),lineNo));
272 dev->unmanagedTempDeallocations++;
278 // Chunk bitmap manipulations
280 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
282 if(blk < dev->startBlock || blk > dev->endBlock)
284 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
287 return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->startBlock));
290 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
292 __u8 *blkBits = yaffs_BlockBits(dev,blk);
294 memset(blkBits,0,dev->chunkBitmapStride);
297 static Y_INLINE void yaffs_ClearChunkBit(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 void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
306 __u8 *blkBits = yaffs_BlockBits(dev,blk);
308 blkBits[chunk/8] |= (1<<(chunk & 7));
311 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
313 __u8 *blkBits = yaffs_BlockBits(dev,blk);
314 return (blkBits[chunk/8] & (1<<(chunk & 7))) ? 1 :0;
317 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
319 __u8 *blkBits = yaffs_BlockBits(dev,blk);
321 for(i = 0; i < dev->chunkBitmapStride; i++)
323 if(*blkBits) return 1;
330 // Function to manipulate block info
331 static Y_INLINE yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
333 if(blk < dev->startBlock || blk > dev->endBlock)
335 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: getBlockInfo block %d is not valid" TENDSTR),blk));
338 return &dev->blockInfo[blk - dev->startBlock];
343 static Y_INLINE int yaffs_HashFunction(int n)
345 return (n % YAFFS_NOBJECT_BUCKETS);
349 yaffs_Object *yaffs_Root(yaffs_Device *dev)
354 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
356 return dev->lostNFoundDir;
360 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
362 if(chunkInNAND < dev->startBlock * dev->nChunksPerBlock)
364 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
369 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
374 static int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
378 int doErrorCorrection)
381 yaffs_Spare localSpare;
390 // If we don't have a real spare, then we use a local one.
391 // Need this for the calculation of the ecc
398 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
399 if(data && doErrorCorrection)
402 //Todo handle any errors
403 int eccResult1,eccResult2;
406 yaffs_ECCCalculate(data,calcEcc);
407 eccResult1 = yaffs_ECCCorrect (data,spare->ecc1, calcEcc);
408 yaffs_ECCCalculate(&data[256],calcEcc);
409 eccResult2 = yaffs_ECCCorrect(&data[256],spare->ecc2, calcEcc);
413 T(YAFFS_TRACE_ERROR, (TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
416 else if(eccResult1<0)
418 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
424 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
427 else if(eccResult2<0)
429 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
433 if(eccResult1 || eccResult2)
435 // Hoosterman, we had a data problem on this page
436 yaffs_HandleReadDataError(dev,chunkInNAND);
442 // Must allocate enough memory for spare+2*sizeof(int) for ecc results from device.
443 struct yaffs_NANDSpare nspare;
444 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
445 memcpy (spare, &nspare, sizeof(yaffs_Spare));
446 if(data && doErrorCorrection)
450 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
452 else if(nspare.eccres1<0)
454 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
459 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
461 else if(nspare.eccres2<0)
463 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
466 if(nspare.eccres1 || nspare.eccres2)
468 // Hoosterman, we had a data problem on this page
469 yaffs_HandleReadDataError(dev,chunkInNAND);
481 int yaffs_CheckFF(__u8 *buffer,int nBytes)
483 //Horrible, slow implementation
486 if(*buffer != 0xFF) return 0;
492 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
495 int retval = YAFFS_OK;
496 __u8 *data = yaffs_GetTempBuffer(dev,__LINE__);
497 yaffs_ExtendedTags tags;
499 // NCB dev->readChunkWithTagsFromNAND(dev,chunkInNAND,data,&tags);
500 yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,data,&tags);
502 if(!yaffs_CheckFF(data,dev->nBytesPerChunk) || tags.chunkUsed)
504 T(YAFFS_TRACE_NANDACCESS,(TSTR("Chunk %d not erased" TENDSTR),chunkInNAND));
508 yaffs_ReleaseTempBuffer(dev,data,__LINE__);
517 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_ExtendedTags *tags,int useReserve)
527 chunk = yaffs_AllocateChunk(dev,useReserve);
532 // First check this chunk is erased...
533 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
534 writeOk = yaffs_CheckChunkErased(dev,chunk);
538 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
542 writeOk = yaffs_WriteChunkWithTagsToNAND(dev,chunk,data,tags);
548 // Copy the data into the robustification buffer.
549 // NB We do this at the end to prevent duplicates in the case of a write error.
551 yaffs_HandleWriteChunkOk(dev,chunk,data,tags);
555 yaffs_HandleWriteChunkError(dev,chunk);
559 } while(chunk >= 0 && ! writeOk);
563 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
564 dev->nRetriedWrites+= (attempts - 1);
575 // Functions for robustisizing
579 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
582 yaffs_MarkBlockBad(dev,blockInNAND);
584 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
586 dev->nRetiredBlocks++;
591 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
593 dev->doingBufferedBlockRewrite = 1;
595 // Remove erased chunks
596 // Rewrite existing chunks to a new block
597 // Set current write block to the new block
599 dev->doingBufferedBlockRewrite = 0;
605 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
607 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
609 // Mark the block for retirement
610 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
611 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
615 // Just do a garbage collection on the affected block then retire the block
620 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
626 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_ExtendedTags *tags)
630 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_ExtendedTags *tags)
634 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
636 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
638 // Mark the block for retirement
639 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
641 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
647 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1,int dataSize)
651 if( memcmp(d0,d1,dataSize) != 0 ||
652 s0->tagByte0 != s1->tagByte0 ||
653 s0->tagByte1 != s1->tagByte1 ||
654 s0->tagByte2 != s1->tagByte2 ||
655 s0->tagByte3 != s1->tagByte3 ||
656 s0->tagByte4 != s1->tagByte4 ||
657 s0->tagByte5 != s1->tagByte5 ||
658 s0->tagByte6 != s1->tagByte6 ||
659 s0->tagByte7 != s1->tagByte7 ||
660 s0->ecc1[0] != s1->ecc1[0] ||
661 s0->ecc1[1] != s1->ecc1[1] ||
662 s0->ecc1[2] != s1->ecc1[2] ||
663 s0->ecc2[0] != s1->ecc2[0] ||
664 s0->ecc2[1] != s1->ecc2[1] ||
665 s0->ecc2[2] != s1->ecc2[2] )
675 ///////////////////////// Object management //////////////////
676 // List of spare objects
677 // The list is hooked together using the first pointer
680 // static yaffs_Object *yaffs_freeObjects = NULL;
682 // static int yaffs_nFreeObjects;
684 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
686 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
689 static __u16 yaffs_CalcNameSum(const YCHAR *name)
694 YUCHAR *bname = (YUCHAR *)name;
697 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
700 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
701 sum += yaffs_toupper(*bname) * i;
712 void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
714 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
715 if(name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
717 yaffs_strcpy(obj->shortName,name);
721 obj->shortName[0]=_Y('\0');
724 obj->sum = yaffs_CalcNameSum(name);
728 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
730 yaffs_ECCCalculate(data , spare->ecc1);
731 yaffs_ECCCalculate(&data[256] , spare->ecc2);
736 ///////////////////////// TNODES ///////////////////////
738 // List of spare tnodes
739 // The list is hooked together using the first pointer
742 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
744 // static int yaffs_nFreeTnodes;
746 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
750 // yaffs_CreateTnodes creates a bunch more tnodes and
751 // adds them to the tnode free list.
752 // Don't use this function directly
754 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
757 yaffs_Tnode *newTnodes;
758 yaffs_TnodeList *tnl;
760 if(nTnodes < 1) return YAFFS_OK;
764 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
768 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
772 // Hook them into the free list
773 for(i = 0; i < nTnodes - 1; i++)
775 newTnodes[i].internal[0] = &newTnodes[i+1];
776 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
777 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = 1;
781 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
782 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
783 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = 1;
785 dev->freeTnodes = newTnodes;
786 dev->nFreeTnodes+= nTnodes;
787 dev->nTnodesCreated += nTnodes;
789 // Now add this bunch of tnodes to a list for freeing up.
790 // NB If we can't add this to the management list it isn't fatal
791 // but it just means we can't free this bunch of tnodes later.
792 tnl = YMALLOC(sizeof(yaffs_TnodeList));
795 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
800 tnl->tnodes = newTnodes;
801 tnl->next = dev->allocatedTnodeList;
802 dev->allocatedTnodeList = tnl;
806 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
813 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
814 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
816 yaffs_Tnode *tn = NULL;
818 // If there are none left make more
821 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
826 tn = dev->freeTnodes;
827 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
828 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 1)
830 // Hoosterman, this thing looks like it isn't in the list
831 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 1" TENDSTR)));
834 dev->freeTnodes = dev->freeTnodes->internal[0];
837 memset(tn,0,sizeof(yaffs_Tnode));
845 // FreeTnode frees up a tnode and puts it back on the free list
846 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
850 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
851 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 0)
853 // Hoosterman, this thing looks like it is already in the list
854 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 2" TENDSTR)));
856 tn->internal[YAFFS_NTNODES_INTERNAL] = 1;
858 tn->internal[0] = dev->freeTnodes;
859 dev->freeTnodes = tn;
865 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
867 // Free the list of allocated tnodes
868 yaffs_TnodeList *tmp;
870 while(dev->allocatedTnodeList)
872 tmp = dev->allocatedTnodeList->next;
874 YFREE(dev->allocatedTnodeList->tnodes);
875 YFREE(dev->allocatedTnodeList);
876 dev->allocatedTnodeList = tmp;
880 dev->freeTnodes = NULL;
881 dev->nFreeTnodes = 0;
884 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
886 dev->allocatedTnodeList = NULL;
887 dev->freeTnodes = NULL;
888 dev->nFreeTnodes = 0;
889 dev->nTnodesCreated = 0;
894 void yaffs_TnodeTest(yaffs_Device *dev)
899 yaffs_Tnode *tn[1000];
901 YINFO("Testing TNodes");
903 for(j = 0; j < 50; j++)
905 for(i = 0; i < 1000; i++)
907 tn[i] = yaffs_GetTnode(dev);
910 YALERT("Getting tnode failed");
913 for(i = 0; i < 1000; i+=3)
915 yaffs_FreeTnode(dev,tn[i]);
924 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
926 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
927 // The look up tree is represented by the top tnode and the number of topLevel
928 // in the tree. 0 means only the level 0 tnode is in the tree.
931 // FindLevel0Tnode finds the level 0 tnode, if one exists.
932 // Used when reading.....
933 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
936 yaffs_Tnode *tn = fStruct->top;
938 int requiredTallness;
939 int level = fStruct->topLevel;
941 // Check sane level and chunk Id
942 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
945 // sprintf(str,"Bad level %d",level);
950 if(chunkId > YAFFS_MAX_CHUNK_ID)
953 // sprintf(str,"Bad chunkId %d",chunkId);
958 // First check we're tall enough (ie enough topLevel)
960 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
961 requiredTallness = 0;
964 i >>= YAFFS_TNODES_INTERNAL_BITS;
969 if(requiredTallness > fStruct->topLevel)
971 // Not tall enough, so we can't find it, return NULL.
976 // Traverse down to level 0
977 while (level > 0 && tn)
979 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
980 YAFFS_TNODES_INTERNAL_MASK];
988 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
989 // This happens in two steps:
990 // 1. If the tree isn't tall enough, then make it taller.
991 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
993 // Used when modifying the tree.
995 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
1000 int requiredTallness;
1007 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
1009 // Check sane level and page Id
1010 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1013 // sprintf(str,"Bad level %d",fStruct->topLevel);
1018 if(chunkId > YAFFS_MAX_CHUNK_ID)
1021 // sprintf(str,"Bad chunkId %d",chunkId);
1026 // First check we're tall enough (ie enough topLevel)
1028 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
1029 requiredTallness = 0;
1032 x >>= YAFFS_TNODES_INTERNAL_BITS;
1036 //T((TSTR(" required=%d"),requiredTallness));
1039 if(requiredTallness > fStruct->topLevel)
1041 // Not tall enough,gotta make the tree taller
1042 for(i = fStruct->topLevel; i < requiredTallness; i++)
1044 //T((TSTR(" add new top")));
1046 tn = yaffs_GetTnode(dev);
1050 tn->internal[0] = fStruct->top;
1055 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
1059 fStruct->topLevel = requiredTallness;
1063 // Traverse down to level 0, adding anything we need
1065 l = fStruct->topLevel;
1069 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
1070 YAFFS_TNODES_INTERNAL_MASK;
1072 //T((TSTR(" [%d:%d]"),l,i));
1074 if(!tn->internal[x])
1076 //T((TSTR(" added")));
1078 tn->internal[x] = yaffs_GetTnode(dev);
1081 tn = tn->internal[x];
1092 int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk, yaffs_ExtendedTags *tags, int objectId, int chunkInInode)
1097 for(j = 0; theChunk && j < dev->chunkGroupSize; j++)
1099 if(yaffs_CheckChunkBit(dev,theChunk / dev->nChunksPerBlock,theChunk % dev->nChunksPerBlock))
1101 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL,tags);
1102 if(yaffs_TagsMatch(tags,objectId,chunkInInode))
1114 // DeleteWorker scans backwards through the tnode tree and deletes all the
1115 // chunks and tnodes in the file
1116 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1118 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1123 yaffs_ExtendedTags tags;
1125 yaffs_Device *dev = in->myDev;
1135 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1139 if(limit && (*limit) < 0)
1145 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1146 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1150 yaffs_FreeTnode(dev,tn->internal[i]);
1151 tn->internal[i] = NULL;
1156 return (allDone) ? 1 : 0;
1162 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1167 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1169 theChunk = tn->level0[i] << dev->chunkGroupBits;
1171 foundChunk = yaffs_FindChunkInGroup(dev,theChunk,&tags,in->objectId,chunkInInode);
1175 yaffs_DeleteChunk(dev,foundChunk,1,__LINE__);
1192 return (i < 0) ? 1 : 0;
1204 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1207 yaffs_BlockInfo *theBlock;
1209 T(YAFFS_TRACE_DELETION,(TSTR("soft delete chunk %d" TENDSTR),chunk));
1211 theBlock = yaffs_GetBlockInfo(dev, chunk/dev->nChunksPerBlock);
1214 theBlock->softDeletions++;
1218 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1219 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1221 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1223 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1228 yaffs_Device *dev = in->myDev;
1236 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1240 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1241 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1244 yaffs_FreeTnode(dev,tn->internal[i]);
1245 tn->internal[i] = NULL;
1249 //Hoosterman... how could this happen.
1253 return (allDone) ? 1 : 0;
1258 for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1262 // Note this does not find the real chunk, only the chunk group.
1263 // We make an assumption that a chunk group is niot larger than a block.
1264 theChunk = (tn->level0[i] << dev->chunkGroupBits);
1266 yaffs_SoftDeleteChunk(dev,theChunk);
1283 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1286 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1289 if(obj->nDataChunks <= 0)
1291 // Empty file with no duplicate object headers, just delete it immediately
1292 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1293 obj->variant.fileVariant.top = NULL;
1294 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1295 yaffs_DoGenericObjectDeletion(obj);
1299 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1300 obj->softDeleted = 1;
1309 // Pruning removes any part of the file structure tree that is beyond the
1310 // bounds of the file (ie that does not point to chunks).
1312 // A file should only get pruned when its size is reduced.
1314 // Before pruning, the chunks must be pulled from the tree and the
1315 // level 0 tnode entries must be zeroed out.
1316 // Could also use this for file deletion, but that's probably better handled
1317 // by a special case.
1319 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1321 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1330 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1332 if(tn->internal[i] && level > 0)
1334 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1343 if(hasData == 0 && del0)
1345 // Free and return NULL
1347 yaffs_FreeTnode(dev,tn);
1357 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1364 if(fStruct->topLevel > 0)
1366 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1368 // Now we have a tree with all the non-zero branches NULL but the height
1369 // is the same as it was.
1370 // Let's see if we can trim internal tnodes to shorten the tree.
1371 // We can do this if only the 0th element in the tnode is in use
1372 // (ie all the non-zero are NULL)
1374 while(fStruct->topLevel && !done)
1379 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1389 fStruct->top = tn->internal[0];
1390 fStruct->topLevel--;
1391 yaffs_FreeTnode(dev,tn);
1407 /////////////////////// End of File Structure functions. /////////////////
1409 // yaffs_CreateFreeObjects creates a bunch more objects and
1410 // adds them to the object free list.
1411 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1414 yaffs_Object *newObjects;
1415 yaffs_ObjectList *list;
1417 if(nObjects < 1) return YAFFS_OK;
1419 // make these things
1421 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1425 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1429 // Hook them into the free list
1430 for(i = 0; i < nObjects - 1; i++)
1432 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1435 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1436 dev->freeObjects = newObjects;
1437 dev->nFreeObjects+= nObjects;
1438 dev->nObjectsCreated+= nObjects;
1440 // Now add this bunch of Objects to a list for freeing up.
1442 list = YMALLOC(sizeof(yaffs_ObjectList));
1445 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1449 list->objects = newObjects;
1450 list->next = dev->allocatedObjectList;
1451 dev->allocatedObjectList = list;
1460 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1461 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1463 yaffs_Object *tn = NULL;
1465 // If there are none left make more
1466 if(!dev->freeObjects)
1468 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1471 if(dev->freeObjects)
1473 tn = dev->freeObjects;
1474 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1475 dev->nFreeObjects--;
1477 // Now sweeten it up...
1479 memset(tn,0,sizeof(yaffs_Object));
1482 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1483 INIT_LIST_HEAD(&(tn->hardLinks));
1484 INIT_LIST_HEAD(&(tn->hashLink));
1485 INIT_LIST_HEAD(&tn->siblings);
1487 // Add it to the lost and found directory.
1488 // NB Can't put root or lostNFound in lostNFound so
1489 // check if lostNFound exists first
1490 if(dev->lostNFoundDir)
1492 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1500 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1503 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1506 obj->fake = 1; // it is fake so it has no NAND presence...
1507 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1508 obj->unlinkAllowed= 0; // ... or unlink it
1511 obj->st_mode = mode;
1513 obj->chunkId = 0; // Not a valid chunk.
1521 static void yaffs_UnhashObject(yaffs_Object *tn)
1524 yaffs_Device *dev = tn->myDev;
1527 // If it is still linked into the bucket list, free from the list
1528 if(!list_empty(&tn->hashLink))
1530 list_del_init(&tn->hashLink);
1531 bucket = yaffs_HashFunction(tn->objectId);
1532 dev->objectBucket[bucket].count--;
1538 // FreeObject frees up a Object and puts it back on the free list
1539 static void yaffs_FreeObject(yaffs_Object *tn)
1542 yaffs_Device *dev = tn->myDev;
1547 // We're still hooked up to a cached inode.
1548 // Don't delete now, but mark for later deletion
1549 tn->deferedFree = 1;
1554 yaffs_UnhashObject(tn);
1556 // Link into the free list.
1557 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1558 dev->freeObjects = tn;
1559 dev->nFreeObjects++;
1566 void yaffs_HandleDeferedFree(yaffs_Object *obj)
1568 if(obj->deferedFree)
1570 yaffs_FreeObject(obj);
1578 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1580 // Free the list of allocated Objects
1582 yaffs_ObjectList *tmp;
1584 while( dev->allocatedObjectList)
1586 tmp = dev->allocatedObjectList->next;
1587 YFREE(dev->allocatedObjectList->objects);
1588 YFREE(dev->allocatedObjectList);
1590 dev->allocatedObjectList = tmp;
1593 dev->freeObjects = NULL;
1594 dev->nFreeObjects = 0;
1597 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1601 dev->allocatedObjectList = NULL;
1602 dev->freeObjects = NULL;
1603 dev->nFreeObjects = 0;
1605 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1607 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1608 dev->objectBucket[i].count = 0;
1618 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1623 int lowest = 999999;
1626 // First let's see if we can find one that's empty.
1628 for(i = 0; i < 10 && lowest > 0; i++)
1631 x %= YAFFS_NOBJECT_BUCKETS;
1632 if(dev->objectBucket[x].count < lowest)
1634 lowest = dev->objectBucket[x].count;
1640 // If we didn't find an empty list, then try
1641 // looking a bit further for a short one
1643 for(i = 0; i < 10 && lowest > 3; i++)
1646 x %= YAFFS_NOBJECT_BUCKETS;
1647 if(dev->objectBucket[x].count < lowest)
1649 lowest = dev->objectBucket[x].count;
1658 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1660 int bucket = yaffs_FindNiceObjectBucket(dev);
1662 // Now find an object value that has not already been taken
1663 // by scanning the list.
1666 struct list_head *i;
1668 __u32 n = (__u32)bucket;
1670 //yaffs_CheckObjectHashSanity();
1675 n += YAFFS_NOBJECT_BUCKETS;
1676 if(1 ||dev->objectBucket[bucket].count > 0)
1678 list_for_each(i,&dev->objectBucket[bucket].list)
1680 // If there is already one in the list
1681 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1689 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1694 void yaffs_HashObject(yaffs_Object *in)
1696 int bucket = yaffs_HashFunction(in->objectId);
1697 yaffs_Device *dev = in->myDev;
1699 if(!list_empty(&in->hashLink))
1705 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1706 dev->objectBucket[bucket].count++;
1710 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1712 int bucket = yaffs_HashFunction(number);
1713 struct list_head *i;
1716 list_for_each(i,&dev->objectBucket[bucket].list)
1718 // Look if it is in the list
1721 in = list_entry(i, yaffs_Object,hashLink);
1722 if(in->objectId == number)
1725 // Don't tell the VFS about this one if it is defered free
1740 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1743 yaffs_Object *theObject;
1747 number = yaffs_CreateNewObjectNumber(dev);
1750 theObject = yaffs_AllocateEmptyObject(dev);
1754 theObject->fake = 0;
1755 theObject->renameAllowed = 1;
1756 theObject->unlinkAllowed = 1;
1757 theObject->objectId = number;
1758 yaffs_HashObject(theObject);
1759 theObject->variantType = type;
1760 #ifdef CONFIG_YAFFS_WINCE
1761 yfsd_WinFileTimeNow(theObject->win_atime);
1762 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1763 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1767 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = Y_CURRENT_TIME;
1771 case YAFFS_OBJECT_TYPE_FILE:
1772 theObject->variant.fileVariant.fileSize = 0;
1773 theObject->variant.fileVariant.scannedFileSize = 0;
1774 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; // max __u32
1775 theObject->variant.fileVariant.topLevel = 0;
1776 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1778 case YAFFS_OBJECT_TYPE_DIRECTORY:
1779 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1781 case YAFFS_OBJECT_TYPE_SYMLINK:
1782 // No action required
1784 case YAFFS_OBJECT_TYPE_HARDLINK:
1785 // No action required
1787 case YAFFS_OBJECT_TYPE_SPECIAL:
1788 // No action required
1790 case YAFFS_OBJECT_TYPE_UNKNOWN:
1791 // todo this should not happen
1799 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1801 yaffs_Object *theObject = NULL;
1805 theObject = yaffs_FindObjectByNumber(dev,number);
1810 theObject = yaffs_CreateNewObject(dev,number,type);
1817 YCHAR *yaffs_CloneString(const YCHAR *str)
1819 YCHAR *newStr = NULL;
1823 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1824 yaffs_strcpy(newStr,str);
1832 // Mknod (create) a new object.
1833 // equivalentObject only has meaning for a hard link;
1834 // aliasString only has meaning for a sumlink.
1835 // rdev only has meaning for devices (a subset of special objects)
1836 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1837 yaffs_Object *parent,
1842 yaffs_Object *equivalentObject,
1843 const YCHAR *aliasString,
1848 yaffs_Device *dev = parent->myDev;
1850 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1851 if(yaffs_FindObjectByName(parent,name))
1856 in = yaffs_CreateNewObject(dev,-1,type);
1862 in->variantType = type;
1866 #ifdef CONFIG_YAFFS_WINCE
1867 yfsd_WinFileTimeNow(in->win_atime);
1868 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1869 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1872 in->st_atime = in->st_mtime = in->st_ctime = Y_CURRENT_TIME;
1878 in->nDataChunks = 0;
1880 yaffs_SetObjectName(in,name);
1883 yaffs_AddObjectToDirectory(parent,in);
1885 in->myDev = parent->myDev;
1890 case YAFFS_OBJECT_TYPE_SYMLINK:
1891 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1893 case YAFFS_OBJECT_TYPE_HARDLINK:
1894 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1895 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1896 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1898 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1899 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1900 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1901 case YAFFS_OBJECT_TYPE_UNKNOWN:
1905 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1906 yaffs_UpdateObjectHeader(in,name,0,0) < 0)
1908 // Could not create the object header, fail the creation
1909 yaffs_DestroyObject(in);
1918 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid)
1920 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1923 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid)
1925 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1928 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1930 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL,parent,name,mode,uid,gid,NULL,NULL,rdev);
1933 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid,const YCHAR *alias)
1935 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1938 // NB yaffs_Link returns the object id of the equivalent object.
1939 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name, yaffs_Object *equivalentObject)
1941 // Get the real object in case we were fed a hard link as an equivalent object
1942 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1944 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1946 return equivalentObject;
1956 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const YCHAR *newName,int force)
1963 newDir = obj->parent; // use the old directory
1966 if(newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1968 T(YAFFS_TRACE_ALWAYS,(TSTR("tragendy: yaffs_ChangeObjectName: newDir is not a directory"TENDSTR)));
1972 // TODO: Do we need this different handling for YAFFS2 and YAFFS1??
1973 if(obj->myDev->isYaffs2)
1975 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1979 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1982 deleteOp = (newDir == obj->myDev->deletedDir);
1984 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1985 // duplicate names are allowed.
1986 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1990 !yaffs_FindObjectByName(newDir,newName)) &&
1991 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1993 yaffs_SetObjectName(obj,newName);
1996 yaffs_AddObjectToDirectory(newDir,obj);
1998 if(unlinkOp) obj->unlinked = 1;
2000 // If it is a deletion then we mark it as a shrink for gc purposes.
2001 if(yaffs_UpdateObjectHeader(obj,newName,0,deleteOp) >= 0)
2012 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName, yaffs_Object *newDir, const YCHAR *newName)
2017 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2018 // Special case for case insemsitive systems (eg. WinCE).
2019 // While look-up is case insensitive, the name isn't.
2020 // THerefore we might want to change x.txt to X.txt
2021 if(oldDir == newDir && yaffs_strcmp(oldName,newName) == 0)
2027 obj = yaffs_FindObjectByName(oldDir,oldName);
2028 if(obj && obj->renameAllowed)
2030 return yaffs_ChangeObjectName(obj,newDir,newName,force);
2038 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
2040 // Scan the buckets and check that the lists
2041 // have as many members as the count says there are
2044 struct list_head *j;
2047 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
2051 list_for_each(j,&dev->objectBucket[bucket].list)
2056 if(countEm != dev->objectBucket[bucket].count)
2058 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
2067 void yaffs_ObjectTest(yaffs_Device *dev)
2069 yaffs_Object *in[1000];
2071 yaffs_Object *inold[1000];
2075 memset(in,0,1000*sizeof(yaffs_Object *));
2076 memset(inold,0,1000*sizeof(yaffs_Object *));
2078 yaffs_CheckObjectHashSanity(dev);
2080 for(j = 0; j < 10; j++)
2084 for(i = 0; i < 1000; i++)
2086 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
2089 YINFO("No more inodes");
2093 inNo[i] = in[i]->objectId;
2097 for(i = 0; i < 1000; i++)
2099 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
2101 //T(("Differnce in look up test\n"));
2105 // T(("Look up ok\n"));
2109 yaffs_CheckObjectHashSanity(dev);
2111 for(i = 0; i < 1000; i+=3)
2113 yaffs_FreeObject(in[i]);
2118 yaffs_CheckObjectHashSanity(dev);
2125 /////////////////////////// Block Management and Page Allocation ///////////////////
2128 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
2130 dev->allocationBlock = -1; // force it to get a new one
2131 //Todo we're assuming the malloc will pass.
2132 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2133 // Set up dynamic blockinfo stuff.
2134 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
2135 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2136 if(dev->blockInfo && dev->chunkBits)
2138 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
2139 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
2147 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2149 YFREE(dev->blockInfo);
2150 dev->blockInfo = NULL;
2151 YFREE(dev->chunkBits);
2152 dev->chunkBits = NULL;
2156 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev, yaffs_BlockInfo *bi)
2162 if(!dev->isYaffs2) return 1; // disqualification only applies to yaffs2.
2164 if(!bi->hasShrinkHeader) return 1; // can gc
2167 // Find the oldest dirty sequence number if we don't know it and save it
2168 // so we don't have to keep recomputing it.
2169 if(!dev->oldestDirtySequence)
2171 seq = dev->sequenceNumber;
2173 for(i = dev->startBlock; i <= dev->endBlock; i++)
2175 b = yaffs_GetBlockInfo(dev,i);
2176 if(b->blockState == YAFFS_BLOCK_STATE_FULL &&
2177 (b->pagesInUse - b->softDeletions )< dev->nChunksPerBlock &&
2178 b->sequenceNumber < seq)
2180 seq = b->sequenceNumber;
2183 dev->oldestDirtySequence = seq;
2187 // Can't do gc of this block if there are any blocks older than this one that have
2189 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2196 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
2197 // for garbage collection.
2202 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,int aggressive)
2205 int b = dev->currentDirtyChecker;
2211 yaffs_BlockInfo *bi;
2212 static int nonAggressiveSkip = 0;
2214 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2216 // else (we're doing a leasurely gc), then we only bother to do this if the
2217 // block has only a few pages in use.
2220 nonAggressiveSkip--;
2222 if(!aggressive &&(nonAggressiveSkip > 0))
2227 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2230 iterations = dev->endBlock - dev->startBlock + 1;
2234 iterations = dev->endBlock - dev->startBlock + 1;
2235 iterations = iterations / 16;
2236 if(iterations > 200)
2242 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2245 if ( b < dev->startBlock || b > dev->endBlock)
2247 b = dev->startBlock;
2250 if(b < dev->startBlock || b > dev->endBlock)
2252 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2256 bi = yaffs_GetBlockInfo(dev,b);
2258 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2259 (bi->pagesInUse - bi->softDeletions )< pagesInUse &&
2260 yaffs_BlockNotDisqualifiedFromGC(dev,bi))
2263 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2267 dev->currentDirtyChecker = b;
2271 T(YAFFS_TRACE_GC,(TSTR("GC Selected block %d with %d free" TENDSTR),dirtiest,dev->nChunksPerBlock - pagesInUse));
2274 dev->oldestDirtySequence = 0; // clear this
2278 nonAggressiveSkip = 4;
2285 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2287 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2291 // If the block is still healthy erase it and mark as clean.
2292 // If the block has had a data failure, then retire it.
2293 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2295 if(!bi->needsRetiring)
2297 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2300 dev->nErasureFailures++;
2301 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2305 if(erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE))
2308 for(i = 0; i < dev->nChunksPerBlock; i++)
2310 if(!yaffs_CheckChunkErased(dev,blockNo * dev->nChunksPerBlock + i))
2312 T(YAFFS_TRACE_ERROR,(TSTR(">>Block %d erasure supposedly OK, but chunk %d not erased" TENDSTR),blockNo,i));
2320 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2321 dev->nErasedBlocks++;
2323 bi->softDeletions = 0;
2324 bi->hasShrinkHeader=0;
2325 yaffs_ClearChunkBits(dev,blockNo);
2327 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2331 yaffs_RetireBlock(dev,blockNo);
2332 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2337 static void yaffs_DumpBlockStats(yaffs_Device *dev)
2340 yaffs_BlockInfo *bi;
2342 for(i= dev->startBlock; i <=dev->endBlock; i++)
2344 bi = yaffs_GetBlockInfo(dev,i);
2345 T(YAFFS_TRACE_ALLOCATE,(TSTR("%3d state %d shrink %d inuse %d/%d seq %d pages"),i,
2346 bi->blockState,bi->hasShrinkHeader,bi->pagesInUse,bi->softDeletions,bi->sequenceNumber));
2348 for(j = 0; j < dev->nChunksPerBlock; j++)
2350 if(yaffs_CheckChunkBit(dev,i,j))
2352 T(YAFFS_TRACE_ALLOCATE,(TSTR(" %d"),j));
2356 T(YAFFS_TRACE_ALLOCATE,(TSTR(" " TENDSTR)));
2363 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2367 yaffs_BlockInfo *bi;
2372 if(j < 0 || j > 100)
2375 yaffs_DumpBlockStats(dev);
2380 if(dev->nErasedBlocks < 1)
2382 // Hoosterman we've got a problem.
2383 // Can't get space to gc
2384 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2389 // Find an empty block.
2391 for(i = dev->startBlock; i <= dev->endBlock; i++)
2393 dev->allocationBlockFinder++;
2394 if(dev->allocationBlockFinder < dev->startBlock || dev->allocationBlockFinder> dev->endBlock)
2396 dev->allocationBlockFinder = dev->startBlock;
2399 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2401 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2403 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2404 dev->sequenceNumber++;
2405 bi->sequenceNumber = dev->sequenceNumber;
2406 dev->nErasedBlocks--;
2407 T(YAFFS_TRACE_ALLOCATE,(TSTR("Allocated block %d, seq %d, %d left" TENDSTR),dev->allocationBlockFinder,dev->sequenceNumber, dev->nErasedBlocks));
2408 return dev->allocationBlockFinder;
2413 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs tragedy: no more eraased blocks, but there should have been %d" TENDSTR),dev->nErasedBlocks));
2424 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2427 yaffs_BlockInfo *bi;
2429 if(dev->allocationBlock < 0)
2431 // Get next block to allocate off
2432 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2433 dev->allocationPage = 0;
2436 if(!useReserve && dev->nErasedBlocks </*=*/ dev->nReservedBlocks)
2438 // Not enough space to allocate unless we're allowed to use the reserve.
2442 if(dev->nErasedBlocks < dev->nReservedBlocks && dev->allocationPage == 0)
2444 T(YAFFS_TRACE_ALLOCATE,(TSTR("Allocating reserve" TENDSTR)));
2448 // Next page please....
2449 if(dev->allocationBlock >= 0)
2451 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2453 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2454 dev->allocationPage;
2456 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2458 dev->allocationPage++;
2462 // If the block is full set the state to full
2463 if(dev->allocationPage >= dev->nChunksPerBlock)
2465 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2466 dev->allocationBlock = -1;
2473 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2479 // To determine if we have enough space we just look at the
2480 // number of erased blocks.
2481 // The cache is allowed to use reserved blocks.
2483 static int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
2485 return (dev->nErasedBlocks >= dev->nReservedBlocks);
2489 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2493 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2495 if(dev->allocationBlock> 0)
2497 n += (dev->nChunksPerBlock - dev->allocationPage);
2504 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2510 int retVal = YAFFS_OK;
2514 int chunksBefore = yaffs_GetErasedChunks(dev);
2517 yaffs_ExtendedTags tags;
2519 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2521 yaffs_Object *object;
2523 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2525 T(YAFFS_TRACE_TRACING,(TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR),block,bi->pagesInUse,bi->hasShrinkHeader));
2526 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2528 bi->hasShrinkHeader = 0; // clear the flag so that the block can erase
2531 if(!yaffs_StillSomeChunkBits(dev,block))
2533 T(YAFFS_TRACE_TRACING,(TSTR("Collecting block %d that has no chunks in use" TENDSTR),block));
2534 yaffs_BlockBecameDirty(dev,block);
2539 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
2541 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2542 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2543 chunkInBlock++, oldChunk++ )
2545 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2548 // This page is in use and might need to be copied off
2552 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2554 yaffs_InitialiseTags(&tags);
2556 yaffs_ReadChunkWithTagsFromNAND(dev,oldChunk,buffer, &tags);
2558 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2560 T(YAFFS_TRACE_GC_DETAIL,(TSTR("Collecting page %d, %d %d %d " TENDSTR),chunkInBlock,tags.objectId,tags.chunkId,tags.byteCount));
2564 T(YAFFS_TRACE_ERROR,(TSTR("page %d in gc has no object " TENDSTR),oldChunk));
2567 if(object && object->deleted && tags.chunkId != 0)
2569 // Data chunk in a deleted file, throw it away
2570 // It's a deleted data chunk,
2571 // No need to copy this, just forget about it and fix up the
2574 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2575 object->nDataChunks--;
2577 if(object->nDataChunks <= 0)
2579 // remeber to clean up the object
2580 dev->gcCleanupList[cleanups] = tags.objectId;
2585 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2587 // Deleted object header with no data chunks.
2588 // Can be discarded and the file deleted.
2589 object->chunkId = 0;
2590 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2591 object->variant.fileVariant.top = NULL;
2592 yaffs_DoGenericObjectDeletion(object);
2597 // It's either a data chunk in a live file or
2598 // an ObjectHeader, so we're interested in it.
2599 // NB Need to keep the ObjectHeaders of deleted files
2600 // until the whole file has been deleted off
2601 tags.serialNumber++;
2605 newChunk = yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags,1);
2609 retVal = YAFFS_FAIL;
2614 // Ok, now fix up the Tnodes etc.
2616 if(tags.chunkId == 0)
2619 object->chunkId = newChunk;
2620 object->serial = tags.serialNumber;
2624 // It's a data chunk
2625 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2630 yaffs_DeleteChunk(dev,oldChunk,markNAND,__LINE__);
2635 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
2638 // Do any required cleanups
2639 for(i = 0; i < cleanups; i++)
2641 // Time to delete the file too
2642 object = yaffs_FindObjectByNumber(dev,dev->gcCleanupList[i]);
2645 yaffs_FreeTnode(dev,object->variant.fileVariant.top);
2646 object->variant.fileVariant.top = NULL;
2647 T(YAFFS_TRACE_GC,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2648 yaffs_DoGenericObjectDeletion(object);
2655 if(chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev)))
2657 T(YAFFS_TRACE_GC,(TSTR("gc did not increase free chunks before %d after %d" TENDSTR),chunksBefore,chunksAfter));
2664 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2666 // find a file to delete
2667 struct list_head *i;
2671 //Scan the unlinked files looking for one to delete
2672 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2676 l = list_entry(i, yaffs_Object,siblings);
2687 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2689 // This does background deletion on unlinked files.. only deleted ones.
2690 // If we don't have a file we're working on then find one
2691 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2693 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2696 // OK, we're working on a file...
2697 if(dev->unlinkedDeletion)
2699 yaffs_Object *obj = dev->unlinkedDeletion;
2701 int limit; // Number of chunks to delete in a file.
2702 // NB this can be exceeded, but not by much.
2706 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2708 if(obj->nDataChunks == 0)
2710 // Done all the deleting of data chunks.
2711 // Now dump the header and clean up
2712 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2713 obj->variant.fileVariant.top = NULL;
2714 yaffs_DoGenericObjectDeletion(obj);
2715 dev->nDeletedFiles--;
2716 dev->nUnlinkedFiles--;
2717 dev->nBackgroundDeletions++;
2718 dev->unlinkedDeletion = NULL;
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 ///////////////////////////////////////
2792 void yaffs_CalcTagsECC(yaffs_Tags *tags)
2796 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
2803 for(i = 0; i < 8; i++)
2805 for(j = 1; j &0xff; j<<=1)
2820 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
2822 unsigned ecc = tags->ecc;
2824 yaffs_CalcTagsECC(tags);
2828 if(ecc && ecc <= 64)
2830 // TODO: Handle the failure better. Retire?
2831 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
2835 b[ecc / 8] ^= (1 << (ecc & 7));
2837 // Now recvalc the ecc
2838 yaffs_CalcTagsECC(tags);
2840 return 1; // recovered error
2844 // Wierd ecc failure value
2845 // TODO Need to do somethiong here
2846 return -1; //unrecovered error
2852 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2854 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2856 yaffs_CalcTagsECC(tagsPtr);
2858 sparePtr->tagByte0 = tu->asBytes[0];
2859 sparePtr->tagByte1 = tu->asBytes[1];
2860 sparePtr->tagByte2 = tu->asBytes[2];
2861 sparePtr->tagByte3 = tu->asBytes[3];
2862 sparePtr->tagByte4 = tu->asBytes[4];
2863 sparePtr->tagByte5 = tu->asBytes[5];
2864 sparePtr->tagByte6 = tu->asBytes[6];
2865 sparePtr->tagByte7 = tu->asBytes[7];
2868 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2870 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2873 tu->asBytes[0]= sparePtr->tagByte0;
2874 tu->asBytes[1]= sparePtr->tagByte1;
2875 tu->asBytes[2]= sparePtr->tagByte2;
2876 tu->asBytes[3]= sparePtr->tagByte3;
2877 tu->asBytes[4]= sparePtr->tagByte4;
2878 tu->asBytes[5]= sparePtr->tagByte5;
2879 tu->asBytes[6]= sparePtr->tagByte6;
2880 tu->asBytes[7]= sparePtr->tagByte7;
2882 result = yaffs_CheckECCOnTags(tagsPtr);
2885 dev->tagsEccFixed++;
2889 dev->tagsEccUnfixed++;
2893 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2895 memset(spare,0xFF,sizeof(yaffs_Spare));
2901 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_ExtendedTags *tags, int useReserve)
2903 // NB There must be tags, data is optional
2904 // If there is data, then an ECC is calculated on it.
2913 //yaffs_SpareInitialise(&spare);
2915 //if(!dev->useNANDECC && buffer)
2917 // yaffs_CalcECC(buffer,&spare);
2920 //yaffs_LoadTagsIntoSpare(&spare,tags);
2922 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2927 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId, int chunkInObject)
2929 return ( tags->chunkId == chunkInObject &&
2930 tags->objectId == objectId &&
2931 !tags->chunkDeleted) ? 1 : 0;
2935 /////////////////////////////////////////////////////////////////////////////////////////////////////////
2938 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_ExtendedTags *tags)
2940 //Get the Tnode, then get the level 0 offset chunk offset
2943 yaffs_ExtendedTags localTags;
2946 yaffs_Device *dev = in->myDev;
2951 // Passed a NULL, so use our own tags space
2955 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2959 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2961 retVal = yaffs_FindChunkInGroup(dev,theChunk,tags,in->objectId,chunkInInode);
2966 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_ExtendedTags *tags)
2968 //Get the Tnode, then get the level 0 offset chunk offset
2971 yaffs_ExtendedTags localTags;
2973 yaffs_Device *dev = in->myDev;
2978 // Passed a NULL, so use our own tags space
2982 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2987 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2989 retVal = yaffs_FindChunkInGroup(dev,theChunk,tags,in->objectId,chunkInInode);
2991 // Delete the entry in the filestructure (if found)
2994 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2999 //T(("No level 0 found for %d\n", chunkInInode));
3004 //T(("Could not find %d to delete\n",chunkInInode));
3010 #ifdef YAFFS_PARANOID
3012 static int yaffs_CheckFileSanity(yaffs_Object *in)
3020 yaffs_Tags localTags;
3021 yaffs_Tags *tags = &localTags;
3026 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3028 //T(("Object not a file\n"));
3032 objId = in->objectId;
3033 fSize = in->variant.fileVariant.fileSize;
3034 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
3036 for(chunk = 1; chunk <= nChunks; chunk++)
3038 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
3043 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
3045 if(yaffs_CheckChunkBits(dev,theChunk/dev->nChunksPerBlock,theChunk%dev->nChunksPerBlock))
3049 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
3050 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
3058 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
3059 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
3068 //T(("No level 0 found for %d\n", chunk));
3072 return failed ? YAFFS_FAIL : YAFFS_OK;
3077 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
3079 // NB inScan is zero unless scanning. For forward scanning, inScan is > 0 for backward scanning inScan is < 0
3081 yaffs_Device *dev = in->myDev;
3083 yaffs_ExtendedTags existingTags;
3084 yaffs_ExtendedTags newTags;
3085 unsigned existingSerial, newSerial;
3087 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3089 // Just ignore an attempt at putting a chunk into a non-file during scanning
3090 // If it is not during Scanning then something went wrong!
3093 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy:attempt to put data chunk into a non-file" TENDSTR)));
3097 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
3101 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
3107 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
3111 // If we're scanning then we need to test for duplicates
3112 // NB This does not need to be efficient since it should only ever
3113 // happen when the power fails during a write, then only one
3114 // chunk should ever be affected.
3116 // Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3119 if(existingChunk != 0)
3121 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
3122 // thus we have to do a FindChunkInFile to get the real chunk id.
3124 // We have a duplicate now we need to decide which one to use:
3126 // Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3127 // Forward scanning YAFFS2: The new one is what we use, dump the old one.
3128 // YAFFS1: Get both sets of tags and compare serial numbers.
3134 // No need to do this for backward scanning
3135 yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND, NULL,&newTags);
3139 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
3142 if(existingChunk <=0)
3144 //Hoosterman - how did this happen?
3146 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
3151 // NB The deleted flags should be false, otherwise the chunks will
3152 // not be loaded during a scan
3154 newSerial = newTags.serialNumber;
3155 existingSerial = existingTags.serialNumber;
3157 if( (inScan >= 0) &&
3158 ( in->myDev->isYaffs2 ||
3159 existingChunk <= 0 ||
3160 ((existingSerial+1) & 3) == newSerial))
3162 // Forward scanning or not during scanning
3165 // Delete the old one and drop through to update the tnode
3166 yaffs_DeleteChunk(dev,existingChunk,1,__LINE__);
3170 // Backward scanning or we want to use the existing one
3172 // Delete the new one and return early so that the tnode isn't changed
3173 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
3180 if(existingChunk == 0)
3185 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
3192 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
3194 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
3196 if(chunkInNAND >= 0)
3198 return yaffs_ReadChunkWithTagsFromNAND(in->myDev,chunkInNAND,buffer,NULL);
3202 T(YAFFS_TRACE_NANDACCESS,(TSTR("Chunk %d not found zero instead" TENDSTR),chunkInNAND));
3204 memset(buffer,0,in->myDev->nBytesPerChunk); // get sane data if you read a hole
3211 void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND,int lyn)
3215 yaffs_ExtendedTags tags;
3216 yaffs_BlockInfo *bi;
3218 if(chunkId <= 0) return;
3221 block = chunkId / dev->nChunksPerBlock;
3222 page = chunkId % dev->nChunksPerBlock;
3224 bi = yaffs_GetBlockInfo(dev,block);
3226 T(YAFFS_TRACE_DELETION,(TSTR("line %d delete of chunk %d" TENDSTR),lyn,chunkId));
3229 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
3232 // yaffs_SpareInitialise(&spare);
3234 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
3236 //read data before write, to ensure correct ecc
3237 //if we're using MTD verification under Linux
3238 yaffs_ReadChunkFromNAND(dev,chunkId,NULL,&spare,0);
3241 yaffs_InitialiseTags(&tags);
3243 tags.chunkDeleted = 1;
3246 yaffs_WriteChunkWithTagsToNAND(dev,chunkId,NULL,&tags);
3247 yaffs_HandleUpdateChunk(dev,chunkId,&tags);
3251 dev->nUnmarkedDeletions++;
3255 // Pull out of the management area.
3256 // If the whole block became dirty, this will kick off an erasure.
3257 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3258 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3259 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3260 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)
3264 yaffs_ClearChunkBit(dev,block,page);
3267 if(bi->pagesInUse == 0 &&
3268 !bi->hasShrinkHeader &&
3269 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3270 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING)
3272 yaffs_BlockBecameDirty(dev,block);
3278 // T(("Bad news deleting chunk %d\n",chunkId));
3286 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
3288 // Find old chunk Need to do this to get serial number
3289 // Write new one and patch into tree.
3290 // Invalidate old tags.
3293 yaffs_ExtendedTags prevTags;
3296 yaffs_ExtendedTags newTags;
3298 yaffs_Device *dev = in->myDev;
3300 yaffs_CheckGarbageCollection(dev);
3302 // Get the previous chunk at this location in the file if it exists
3303 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
3306 yaffs_InitialiseTags(&newTags);
3308 newTags.chunkId = chunkInInode;
3309 newTags.objectId = in->objectId;
3310 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3311 newTags.byteCount = nBytes;
3313 // yaffs_CalcTagsECC(&newTags);
3315 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
3319 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
3322 if(prevChunkId >= 0)
3324 yaffs_DeleteChunk(dev,prevChunkId,1,__LINE__);
3328 yaffs_CheckFileSanity(in);
3339 // UpdateObjectHeader updates the header on NAND for an object.
3340 // If name is not NULL, then that new name is used.
3342 int yaffs_UpdateObjectHeader(yaffs_Object *in,const YCHAR *name, int force,int isShrink)
3345 yaffs_BlockInfo *bi;
3347 yaffs_Device *dev = in->myDev;
3353 yaffs_ExtendedTags newTags;
3355 __u8 *buffer = NULL;
3356 YCHAR oldName[YAFFS_MAX_NAME_LENGTH+1];
3358 // __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
3360 yaffs_ObjectHeader *oh = NULL;
3361 // yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
3364 if(!in->fake || force)
3367 yaffs_CheckGarbageCollection(dev);
3369 buffer = yaffs_GetTempBuffer(in->myDev,__LINE__);
3370 oh = (yaffs_ObjectHeader *)buffer;
3372 prevChunkId = in->chunkId;
3374 if(prevChunkId >= 0)
3376 yaffs_ReadChunkWithTagsFromNAND(dev,prevChunkId,buffer,NULL);
3377 memcpy(oldName,oh->name,sizeof(oh->name));
3380 memset(buffer,0xFF,dev->nBytesPerChunk);
3383 oh->type = in->variantType;
3385 oh->st_mode = in->st_mode;
3387 #ifdef CONFIG_YAFFS_WINCE
3388 oh->win_atime[0] = in->win_atime[0];
3389 oh->win_ctime[0] = in->win_ctime[0];
3390 oh->win_mtime[0] = in->win_mtime[0];
3391 oh->win_atime[1] = in->win_atime[1];
3392 oh->win_ctime[1] = in->win_ctime[1];
3393 oh->win_mtime[1] = in->win_mtime[1];
3395 oh->st_uid = in->st_uid;
3396 oh->st_gid = in->st_gid;
3397 oh->st_atime = in->st_atime;
3398 oh->st_mtime = in->st_mtime;
3399 oh->st_ctime = in->st_ctime;
3400 oh->st_rdev = in->st_rdev;
3404 oh->parentObjectId = in->parent->objectId;
3408 oh->parentObjectId = 0;
3411 //oh->sum = in->sum;
3414 memset(oh->name,0,sizeof(oh->name));
3415 yaffs_strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3417 else if(prevChunkId)
3419 memcpy(oh->name, oldName,sizeof(oh->name));
3423 memset(oh->name,0,sizeof(oh->name));
3426 oh->isShrink = isShrink;
3428 switch(in->variantType)
3430 case YAFFS_OBJECT_TYPE_UNKNOWN:
3431 // Should not happen
3433 case YAFFS_OBJECT_TYPE_FILE:
3434 oh->fileSize = (oh->parentObjectId == YAFFS_OBJECTID_DELETED ||
3435 oh->parentObjectId == YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.fileVariant.fileSize;
3437 case YAFFS_OBJECT_TYPE_HARDLINK:
3438 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3440 case YAFFS_OBJECT_TYPE_SPECIAL:
3443 case YAFFS_OBJECT_TYPE_DIRECTORY:
3446 case YAFFS_OBJECT_TYPE_SYMLINK:
3447 yaffs_strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3448 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3453 yaffs_InitialiseTags(&newTags);
3455 newTags.chunkId = 0;
3456 newTags.objectId = in->objectId;
3457 newTags.serialNumber = in->serial;
3459 // Add extra info for file header
3461 newTags.extraHeaderInfoAvailable = 1;
3462 newTags.extraParentObjectId = oh->parentObjectId;
3463 newTags.extraFileLength = oh->fileSize;
3464 newTags.extraIsShrinkHeader = oh->isShrink;
3465 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3466 newTags.extraObjectType = in->variantType;
3468 // Create new chunk in NAND
3469 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3474 in->chunkId = newChunkId;
3476 if(prevChunkId >= 0)
3478 yaffs_DeleteChunk(dev,prevChunkId,1,__LINE__);
3483 // If this was a shrink, then mark the block that the chunk lives on
3486 bi = yaffs_GetBlockInfo(in->myDev,newChunkId / in->myDev->nChunksPerBlock);
3487 bi->hasShrinkHeader = 1;
3492 retVal = newChunkId;
3497 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
3503 /////////////////////// Short Operations Cache ////////////////////////////////
3504 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3505 // reads might be short sequential reads, and a lot of writes may be short
3506 // sequential writes. eg. scanning/writing a jpeg file.
3507 // In these cases, a short read/write cache can provide a huge perfomance benefit
3508 // with dumb-as-a-rock code.
3509 // There are a limited number (~10) of cache chunks per device so that we don't
3510 // need a very intelligent search.
3516 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3518 yaffs_Device *dev = obj->myDev;
3521 yaffs_ChunkCache *cache;
3522 int chunkWritten = 0;
3524 int nCaches = obj->myDev->nShortOpCaches;
3531 // Find the dirty cache for this object with the lowest chunk id.
3532 for(i = 0; i < nCaches; i++)
3534 if(dev->srCache[i].object == obj &&
3535 dev->srCache[i].dirty)
3537 if(!cache || dev->srCache[i].chunkId < lowest)
3539 cache = &dev->srCache[i];
3540 lowest = cache->chunkId;
3545 if(cache && !cache->locked)
3547 //Write it out and free it up
3550 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3552 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3554 nBytes= YAFFS_BYTES_PER_CHUNK;
3557 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3563 cache->object = NULL;
3566 } while(cache && chunkWritten > 0);
3570 //Hoosterman, disk full while writing cache out.
3571 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3579 // Grab us a chunk for use.
3580 // First look for an empty one.
3581 // Then look for the least recently used non-dirty one.
3582 // Then look for the least recently used dirty one...., flush and look again.
3583 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3589 if(dev->nShortOpCaches > 0)
3591 for(i = 0; i < dev->nShortOpCaches; i++)
3593 if(!dev->srCache[i].object)
3595 //T(("Grabbing empty %d\n",i));
3597 //printf("Grabbing empty %d\n",i);
3599 return &dev->srCache[i];
3606 usage = 0; // just to stop the compiler grizzling
3608 for(i = 0; i < dev->nShortOpCaches; i++)
3610 if(!dev->srCache[i].dirty &&
3611 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3614 usage = dev->srCache[i].lastUse;
3619 //T(("Grabbing non-empty %d\n",theOne));
3621 //if(theOne >= 0) printf("Grabbed non-empty cache %d\n",theOne);
3623 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3633 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3635 yaffs_ChunkCache *cache;
3636 yaffs_Object *theObj;
3641 if(dev->nShortOpCaches > 0)
3643 // Try find a non-dirty one...
3645 cache = yaffs_GrabChunkCacheWorker(dev);
3649 // They were all dirty, find the last recently used object and flush
3650 // its cache, then find again.
3651 // NB what's here is not very accurate, we actually flush the object
3652 // the last recently used page.
3654 // With locking we can't assume we can use entry zero
3662 for(i = 0; i < dev->nShortOpCaches; i++)
3664 if( dev->srCache[i].object &&
3665 !dev->srCache[i].locked &&
3666 (dev->srCache[i].lastUse < usage || !cache))
3668 usage = dev->srCache[i].lastUse;
3669 theObj = dev->srCache[i].object;
3670 cache = &dev->srCache[i];
3675 if(!cache || cache->dirty)
3679 yaffs_FlushFilesChunkCache(theObj);
3682 cache = yaffs_GrabChunkCacheWorker(dev);
3686 //printf(" pushout %d\n",pushout);
3698 // Find a cached chunk
3699 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3701 yaffs_Device *dev = obj->myDev;
3703 if(dev->nShortOpCaches > 0)
3705 for(i = 0; i < dev->nShortOpCaches; i++)
3707 if(dev->srCache[i].object == obj &&
3708 dev->srCache[i].chunkId == chunkId)
3712 return &dev->srCache[i];
3719 // Mark the chunk for the least recently used algorithym
3720 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3723 if(dev->nShortOpCaches > 0)
3725 if( dev->srLastUse < 0 ||
3726 dev->srLastUse > 100000000)
3728 // Reset the cache usages
3730 for(i = 1; i < dev->nShortOpCaches; i++)
3732 dev->srCache[i].lastUse = 0;
3739 cache->lastUse = dev->srLastUse;
3748 // Invalidate a single cache page.
3749 // Do this when a whole page gets written,
3750 // ie the short cache for this page is no longer valid.
3751 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3753 if(object->myDev->nShortOpCaches > 0)
3755 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3759 cache->object = NULL;
3765 // Invalidate all the cache pages associated with this object
3766 // Do this whenever ther file is deleted or resized.
3767 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3770 yaffs_Device *dev = in->myDev;
3772 if(dev->nShortOpCaches > 0)
3774 // Now invalidate it.
3775 for(i = 0; i < dev->nShortOpCaches; i++)
3777 if(dev->srCache[i].object == in)
3779 dev->srCache[i].object = NULL;
3789 ///////////////////////// File read/write ///////////////////////////////
3790 // Read and write have very similar structures.
3791 // In general the read/write has three parts to it
3792 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3793 // * Some complete chunks
3794 // * An incomplete chunk to end off with
3796 // Curve-balls: the first chunk might also be the last chunk.
3798 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3807 yaffs_ChunkCache *cache;
3815 chunk = offset / dev->nBytesPerChunk + 1; // The first chunk is 1
3816 start = offset % dev->nBytesPerChunk;
3818 // OK now check for the curveball where the start and end are in
3820 if( (start + n) < dev->nBytesPerChunk)
3826 nToCopy = dev->nBytesPerChunk - start;
3829 cache = yaffs_FindChunkCache(in,chunk);
3831 // If the chunk is already in the cache or it is less than a whole chunk
3832 // then use the cache (if there is caching)
3833 // else bypass the cache.
3834 if( cache || nToCopy != dev->nBytesPerChunk)
3836 if(dev->nShortOpCaches > 0)
3839 // If we can't find the data in the cache, then load it up.
3843 cache = yaffs_GrabChunkCache(in->myDev);
3845 cache->chunkId = chunk;
3848 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3852 yaffs_UseChunkCache(dev,cache,0);
3856 #ifdef CONFIG_YAFFS_WINCE
3857 yfsd_UnlockYAFFS(TRUE);
3859 memcpy(buffer,&cache->data[start],nToCopy);
3861 #ifdef CONFIG_YAFFS_WINCE
3862 yfsd_LockYAFFS(TRUE);
3868 // Read into the local buffer then copy...
3870 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3871 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3872 #ifdef CONFIG_YAFFS_WINCE
3873 yfsd_UnlockYAFFS(TRUE);
3875 memcpy(buffer,&localBuffer[start],nToCopy);
3877 #ifdef CONFIG_YAFFS_WINCE
3878 yfsd_LockYAFFS(TRUE);
3880 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
3886 #ifdef CONFIG_YAFFS_WINCE
3887 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3889 // Under WinCE can't do direct transfer. Need to use a local buffer.
3890 // This is because we otherwise screw up WinCE's memory mapper
3891 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3893 #ifdef CONFIG_YAFFS_WINCE
3894 yfsd_UnlockYAFFS(TRUE);
3896 memcpy(buffer,localBuffer,dev->nBytesPerChunk);
3898 #ifdef CONFIG_YAFFS_WINCE
3899 yfsd_LockYAFFS(TRUE);
3900 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
3904 // A full chunk. Read directly into the supplied buffer.
3905 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3921 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3930 int startOfWrite = offset;
3931 int chunkWritten = 0;
3939 while(n > 0 && chunkWritten >= 0)
3941 chunk = offset / dev->nBytesPerChunk + 1;
3942 start = offset % dev->nBytesPerChunk;
3945 // OK now check for the curveball where the start and end are in
3948 if( (start + n) < dev->nBytesPerChunk)
3952 // Now folks, to calculate how many bytes to write back....
3953 // If we're overwriting and not writing to then end of file then
3954 // we need to write back as much as was there before.
3956 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * dev->nBytesPerChunk);
3958 if(nBytesRead > dev->nBytesPerChunk)
3960 nBytesRead = dev->nBytesPerChunk;
3963 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3968 nToCopy = dev->nBytesPerChunk - start;
3969 nToWriteBack = dev->nBytesPerChunk;
3972 if(nToCopy != dev->nBytesPerChunk)
3974 // An incomplete start or end chunk (or maybe both start and end chunk)
3975 if(dev->nShortOpCaches > 0)
3977 yaffs_ChunkCache *cache;
3978 // If we can't find the data in the cache, then load it up.
3979 cache = yaffs_FindChunkCache(in,chunk);
3980 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3982 cache = yaffs_GrabChunkCache(in->myDev);
3984 cache->chunkId = chunk;
3987 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3992 yaffs_UseChunkCache(dev,cache,1);
3994 #ifdef CONFIG_YAFFS_WINCE
3995 yfsd_UnlockYAFFS(TRUE);
3998 memcpy(&cache->data[start],buffer,nToCopy);
4000 #ifdef CONFIG_YAFFS_WINCE
4001 yfsd_LockYAFFS(TRUE);
4004 cache->nBytes = nToWriteBack;
4008 chunkWritten = -1; // fail the write
4013 // An incomplete start or end chunk (or maybe both start and end chunk)
4014 // Read into the local buffer then copy, then copy over and write back.
4016 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
4018 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
4020 #ifdef CONFIG_YAFFS_WINCE
4021 yfsd_UnlockYAFFS(TRUE);
4024 memcpy(&localBuffer[start],buffer,nToCopy);
4026 #ifdef CONFIG_YAFFS_WINCE
4027 yfsd_LockYAFFS(TRUE);
4029 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,nToWriteBack,0);
4031 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
4033 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
4040 #ifdef CONFIG_YAFFS_WINCE
4041 // Under WinCE can't do direct transfer. Need to use a local buffer.
4042 // This is because we otherwise screw up WinCE's memory mapper
4043 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
4044 #ifdef CONFIG_YAFFS_WINCE
4045 yfsd_UnlockYAFFS(TRUE);
4047 memcpy(localBuffer,buffer,dev->nBytesPerChunk);
4048 #ifdef CONFIG_YAFFS_WINCE
4049 yfsd_LockYAFFS(TRUE);
4051 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,dev->nBytesPerChunk,0);
4052 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
4054 // A full chunk. Write directly from the supplied buffer.
4055 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,dev->nBytesPerChunk,0);
4057 // Since we've overwritten the cached data, we better invalidate it.
4058 yaffs_InvalidateChunkCache(in,chunk);
4059 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
4062 if(chunkWritten >= 0)
4072 // Update file object
4074 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
4076 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4084 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4087 yaffs_Device *dev = in->myDev;
4088 int oldFileSize = in->variant.fileVariant.fileSize;
4091 int lastDel = 1 + (oldFileSize-1)/dev->nBytesPerChunk;
4093 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1)/
4094 dev->nBytesPerChunk;
4098 // Delete backwards so that we don't end up with holes if
4099 // power is lost part-way through the operation.
4100 for(i = lastDel; i >= startDel; i--)
4102 // NB this could be optimised somewhat,
4103 // eg. could retrieve the tags and write them without
4104 // using yaffs_DeleteChunk
4106 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
4109 if(chunkId < (dev->startBlock * dev->nChunksPerBlock) ||
4110 chunkId >= ((dev->endBlock+1) * dev->nChunksPerBlock))
4112 T(YAFFS_TRACE_ALWAYS,(TSTR("Found daft chunkId %d for %d"TENDSTR),chunkId,i));
4117 yaffs_DeleteChunk(dev,chunkId,1,__LINE__);
4124 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
4127 int oldFileSize = in->variant.fileVariant.fileSize;
4128 int sizeOfPartialChunk;
4129 yaffs_Device *dev = in->myDev;
4131 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
4134 yaffs_FlushFilesChunkCache(in);
4135 yaffs_InvalidateWholeChunkCache(in);
4137 yaffs_CheckGarbageCollection(dev);
4139 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
4141 return yaffs_GetFileSize(in);
4144 if(newSize < oldFileSize)
4147 yaffs_PruneResizedChunks(in,newSize);
4149 if(sizeOfPartialChunk != 0)
4151 int lastChunk = 1+ newSize/dev->nBytesPerChunk;
4152 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
4154 // Got to read and rewrite the last chunk with its new size and zero pad
4155 yaffs_ReadChunkDataFromObject(in,lastChunk,localBuffer);
4157 memset(localBuffer + sizeOfPartialChunk,0, dev->nBytesPerChunk - sizeOfPartialChunk);
4159 yaffs_WriteChunkDataToObject(in,lastChunk,localBuffer,sizeOfPartialChunk,1);
4161 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
4164 in->variant.fileVariant.fileSize = newSize;
4166 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
4168 // Write a new object header to show we've shrunk the file
4169 // Do this only if the file is not in the deleted directories.
4170 if(in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4171 in->parent->objectId != YAFFS_OBJECTID_DELETED
4174 yaffs_UpdateObjectHeader(in,NULL, 0, 1);
4188 loff_t yaffs_GetFileSize(yaffs_Object *obj)
4190 obj = yaffs_GetEquivalentObject(obj);
4192 switch(obj->variantType)
4194 case YAFFS_OBJECT_TYPE_FILE:
4195 return obj->variant.fileVariant.fileSize;
4196 case YAFFS_OBJECT_TYPE_SYMLINK:
4197 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4205 // yaffs_FlushFile() updates the file's
4208 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
4213 //T(("flushing object header\n"));
4215 yaffs_FlushFilesChunkCache(in);
4218 #ifdef CONFIG_YAFFS_WINCE
4219 yfsd_WinFileTimeNow(in->win_mtime);
4222 in->st_mtime = Y_CURRENT_TIME;
4227 retVal = (yaffs_UpdateObjectHeader(in,NULL,0,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
4239 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
4242 // First off, invalidate the file's data in the cache, without flushing.
4243 yaffs_InvalidateWholeChunkCache(in);
4245 if(in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir))
4247 // Move to the unlinked directory so we have a record that it was deleted.
4248 yaffs_ChangeObjectName(in, in->myDev->deletedDir,NULL,0);
4253 yaffs_RemoveObjectFromDirectory(in);
4254 yaffs_DeleteChunk(in->myDev,in->chunkId,1,__LINE__);
4260 in->myInode->u.generic_ip = NULL;
4266 yaffs_FreeObject(in);
4271 // yaffs_DeleteFile deletes the whole file data
4272 // and the inode associated with the file.
4273 // It does not delete the links associated with the file.
4274 static int yaffs_UnlinkFile(yaffs_Object *in)
4277 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
4279 // Delete the file data & tnodes
4281 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
4284 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
4286 return yaffs_DoGenericObjectDeletion(in);
4289 int immediateDeletion=0;
4294 //in->myDev->nUnlinkedFiles++;
4295 //in->renameAllowed = 0;
4299 immediateDeletion = 1;
4305 immediateDeletion = 1;
4309 if(immediateDeletion)
4311 retVal = yaffs_ChangeObjectName(in, in->myDev->deletedDir,NULL,0);
4312 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
4314 in->myDev->nDeletedFiles++;
4315 if( 0 && in->myDev->isYaffs2)
4317 yaffs_ResizeFile(in,0);
4319 yaffs_SoftDeleteFile(in);
4323 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
4333 int yaffs_DeleteFile(yaffs_Object *in)
4335 int retVal = YAFFS_OK;
4337 if(in->nDataChunks > 0)
4339 // Use soft deletion
4342 retVal = yaffs_UnlinkFile(in);
4344 if(retVal == YAFFS_OK &&
4349 in->myDev->nDeletedFiles++;
4350 yaffs_SoftDeleteFile(in);
4352 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4356 // The file has no data chunks so we toss it immediately
4357 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
4358 in->variant.fileVariant.top = NULL;
4359 yaffs_DoGenericObjectDeletion(in);
4365 static int yaffs_DeleteDirectory(yaffs_Object *in)
4367 //First check that the directory is empty.
4368 if(list_empty(&in->variant.directoryVariant.children))
4370 return yaffs_DoGenericObjectDeletion(in);
4377 static int yaffs_DeleteSymLink(yaffs_Object *in)
4379 YFREE(in->variant.symLinkVariant.alias);
4381 return yaffs_DoGenericObjectDeletion(in);
4384 static int yaffs_DeleteHardLink(yaffs_Object *in)
4386 // remove this hardlink from the list assocaited with the equivalent
4388 list_del(&in->hardLinks);
4389 return yaffs_DoGenericObjectDeletion(in);
4393 static void yaffs_DestroyObject(yaffs_Object *obj)
4395 switch(obj->variantType)
4397 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
4398 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
4399 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
4400 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
4401 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
4402 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
4407 static int yaffs_UnlinkWorker(yaffs_Object *obj)
4411 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4413 return yaffs_DeleteHardLink(obj);
4415 else if(!list_empty(&obj->hardLinks))
4417 // Curve ball: We're unlinking an object that has a hardlink.
4419 // This problem arises because we are not strictly following
4420 // The Linux link/inode model.
4422 // We can't really delete the object.
4423 // Instead, we do the following:
4424 // - Select a hardlink.
4425 // - Unhook it from the hard links
4426 // - Unhook it from its parent directory (so that the rename can work)
4427 // - Rename the object to the hardlink's name.
4428 // - Delete the hardlink
4433 YCHAR name[YAFFS_MAX_NAME_LENGTH+1];
4435 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
4437 list_del_init(&hl->hardLinks);
4438 list_del_init(&hl->siblings);
4440 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
4442 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
4444 if(retVal == YAFFS_OK)
4446 retVal = yaffs_DoGenericObjectDeletion(hl);
4453 switch(obj->variantType)
4455 case YAFFS_OBJECT_TYPE_FILE:
4456 return yaffs_UnlinkFile(obj);
4458 case YAFFS_OBJECT_TYPE_DIRECTORY:
4459 return yaffs_DeleteDirectory(obj);
4461 case YAFFS_OBJECT_TYPE_SYMLINK:
4462 return yaffs_DeleteSymLink(obj);
4464 case YAFFS_OBJECT_TYPE_SPECIAL:
4465 return yaffs_DoGenericObjectDeletion(obj);
4467 case YAFFS_OBJECT_TYPE_HARDLINK:
4468 case YAFFS_OBJECT_TYPE_UNKNOWN:
4475 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
4479 obj = yaffs_FindObjectByName(dir,name);
4481 if(obj && obj->unlinkAllowed)
4483 return yaffs_UnlinkWorker(obj);
4490 //////////////// Initialisation Scanning /////////////////
4494 // For now we use the SmartMedia check.
4495 // We look at the blockStatus byte in the first two chunks
4496 // These must be 0xFF to pass as OK.
4497 // todo: this function needs to be modifyable foir different NAND types
4498 // and different chunk sizes. Suggest make this into a per-device configurable
4500 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
4502 yaffsExtendedTags *tags;
4504 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&tags,1);
4506 if(yaffs_CountBits(spare.blockStatus) < 7)
4511 if(spare.blockStatus != 0xFF)
4516 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
4519 if(yaffs_CountBits(spare.blockStatus) < 7)
4524 if(spare.blockStatus != 0xFF)
4545 static int yaffs_Scan(yaffs_Device *dev)
4547 yaffs_ExtendedTags tags;
4552 int nBlocksToScan = 0;
4557 yaffs_BlockState state;
4558 yaffs_Object *hardList = NULL;
4560 yaffs_BlockInfo *bi;
4562 yaffs_ObjectHeader *oh;
4564 yaffs_Object *parent;
4565 int nBlocks = dev->endBlock - dev->startBlock + 1;
4569 yaffs_BlockIndex *blockIndex = NULL;
4571 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_Scan starts startblk %d endblk %d..." TENDSTR),dev->startBlock,dev->endBlock));
4573 chunkData = yaffs_GetTempBuffer(dev,__LINE__);
4576 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4580 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4584 // Scan all the blocks to determine their state
4585 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
4587 bi = yaffs_GetBlockInfo(dev,blk);
4588 yaffs_ClearChunkBits(dev,blk);
4590 bi->softDeletions = 0;
4592 yaffs_QueryInitialBlockState(dev,blk,&state,&sequenceNumber);
4594 bi->blockState = state;
4595 bi->sequenceNumber = sequenceNumber;
4597 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("Block scanning block %d state %d seq %d" TENDSTR),blk,state,sequenceNumber));
4599 if(state == YAFFS_BLOCK_STATE_DEAD)
4601 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
4603 else if(state == YAFFS_BLOCK_STATE_EMPTY)
4605 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("Block empty " TENDSTR)));
4606 dev->nErasedBlocks++;
4607 dev->nFreeChunks += dev->nChunksPerBlock;
4609 else if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
4612 // Determine the highest sequence number
4613 if( dev->isYaffs2 &&
4614 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4615 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER)
4618 blockIndex[nBlocksToScan].seq = sequenceNumber;
4619 blockIndex[nBlocksToScan].block = blk;
4623 if(sequenceNumber >= dev->sequenceNumber)
4625 dev->sequenceNumber = sequenceNumber;
4628 else if(dev->isYaffs2)
4630 // TODO: Nasty sequence number!
4631 T(YAFFS_TRACE_SCAN,(TSTR("Block scanning block %d has bad sequence number %d" TENDSTR),blk,sequenceNumber));
4638 // Dungy old bubble sort for now...
4641 yaffs_BlockIndex temp;
4645 for(i = 0; i < nBlocksToScan; i++)
4646 for(j = i+1; j < nBlocksToScan; j++)
4647 if(blockIndex[i].seq > blockIndex[j].seq)
4649 temp = blockIndex[j];
4650 blockIndex[j] = blockIndex[i];
4651 blockIndex[i] = temp;
4656 // Now scan the blocks looking at the data.
4660 endIterator = nBlocksToScan-1;
4661 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("%d blocks to be scanned" TENDSTR),nBlocksToScan));
4665 startIterator = dev->startBlock;
4666 endIterator = dev->endBlock;
4669 // For each block....
4670 for(blockIterator = startIterator; blockIterator <= endIterator; blockIterator++)
4675 // get the block to scan in the correct order
4676 blk = blockIndex[blockIterator].block;
4680 blk = blockIterator;
4684 bi = yaffs_GetBlockInfo(dev,blk);
4685 state = bi->blockState;
4689 // For each chunk in each block that needs scanning....
4690 for(c = 0; c < dev->nChunksPerBlock &&
4691 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++)
4693 // Read the tags and decide what to do
4694 chunk = blk * dev->nChunksPerBlock + c;
4696 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,NULL,&tags);
4698 // Let's have a good look at this chunk...
4701 if(!dev->isYaffs2 && tags.chunkDeleted)
4706 dev->nFreeChunks ++;
4707 //T((" %d %d deleted\n",blk,c));
4709 else if(!tags.chunkUsed)
4711 // An unassigned chunk in the block
4712 // This means that either the block is empty or
4713 // this is the one being allocated from
4717 // We're looking at the first chunk in the block so the block is unused
4718 state = YAFFS_BLOCK_STATE_EMPTY;
4719 dev->nErasedBlocks++;
4723 // this is the block being allocated from
4724 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4725 state = YAFFS_BLOCK_STATE_ALLOCATING;
4726 dev->allocationBlock = blk;
4727 dev->allocationPage = c;
4728 dev->allocationBlockFinder = blk; // Set it to here to encourage the allocator to
4729 // go forth from here.
4730 //Yaffs2 sanity check:
4731 // This should be the one with the highest sequence number
4732 if(dev->isYaffs2 && (dev->sequenceNumber != bi->sequenceNumber))
4734 T(YAFFS_TRACE_ALWAYS,
4735 (TSTR("yaffs: Allocation block %d was not highest sequence id: block seq = %d, dev seq = %d" TENDSTR),
4736 blk,bi->sequenceNumber,dev->sequenceNumber));
4740 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4742 else if(tags.chunkId > 0)
4744 // chunkId > 0 so it is a data chunk...
4745 unsigned int endpos;
4747 yaffs_SetChunkBit(dev,blk,c);
4750 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4751 // PutChunkIntoFile checks for a clash (two data chunks with
4752 // the same chunkId).
4753 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4754 endpos = (tags.chunkId - 1)* dev->nBytesPerChunk + tags.byteCount;
4755 if(in->variantType == YAFFS_OBJECT_TYPE_FILE && in->variant.fileVariant.scannedFileSize <endpos)
4757 in->variant.fileVariant.scannedFileSize = endpos;
4758 if(!dev->useHeaderFileSize)
4760 in->variant.fileVariant.fileSize = in->variant.fileVariant.scannedFileSize;
4764 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4768 // chunkId == 0, so it is an ObjectHeader.
4769 // Thus, we read in the object header and make the object
4770 yaffs_SetChunkBit(dev,blk,c);
4773 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,chunkData,NULL);
4775 oh = (yaffs_ObjectHeader *)chunkData;
4777 in = yaffs_FindObjectByNumber(dev,tags.objectId);
4778 if(in && in->variantType != oh->type)
4780 // This should not happen, but somehow
4781 // Wev'e ended up with an objectId that has been reused but not yet
4782 // deleted, and worse still it has changed type. Delete the old object.
4784 yaffs_DestroyObject(in);
4789 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4793 // We have already filled this one. We have a duplicate and need to resolve it.
4795 unsigned existingSerial = in->serial;
4796 unsigned newSerial = tags.serialNumber;
4798 if( dev->isYaffs2 ||
4799 ((existingSerial+1) & 3) == newSerial)
4801 // Use new one - destroy the exisiting one
4802 yaffs_DeleteChunk(dev,in->chunkId,1,__LINE__);
4807 // Use existing - destroy this one.
4808 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
4813 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4814 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4816 // We only load some info, don't fiddle with directory structure
4818 in->variantType = oh->type;
4820 in->st_mode = oh->st_mode;
4821 #ifdef CONFIG_YAFFS_WINCE
4822 in->win_atime[0] = oh->win_atime[0];
4823 in->win_ctime[0] = oh->win_ctime[0];
4824 in->win_mtime[0] = oh->win_mtime[0];
4825 in->win_atime[1] = oh->win_atime[1];
4826 in->win_ctime[1] = oh->win_ctime[1];
4827 in->win_mtime[1] = oh->win_mtime[1];
4829 in->st_uid = oh->st_uid;
4830 in->st_gid = oh->st_gid;
4831 in->st_atime = oh->st_atime;
4832 in->st_mtime = oh->st_mtime;
4833 in->st_ctime = oh->st_ctime;
4834 in->st_rdev = oh->st_rdev;
4836 in->chunkId = chunk;
4841 // we need to load this info
4844 in->variantType = oh->type;
4846 in->st_mode = oh->st_mode;
4847 #ifdef CONFIG_YAFFS_WINCE
4848 in->win_atime[0] = oh->win_atime[0];
4849 in->win_ctime[0] = oh->win_ctime[0];
4850 in->win_mtime[0] = oh->win_mtime[0];
4851 in->win_atime[1] = oh->win_atime[1];
4852 in->win_ctime[1] = oh->win_ctime[1];
4853 in->win_mtime[1] = oh->win_mtime[1];
4855 in->st_uid = oh->st_uid;
4856 in->st_gid = oh->st_gid;
4857 in->st_atime = oh->st_atime;
4858 in->st_mtime = oh->st_mtime;
4859 in->st_ctime = oh->st_ctime;
4860 in->st_rdev = oh->st_rdev;
4862 in->chunkId = chunk;
4864 yaffs_SetObjectName(in,oh->name);
4867 // directory stuff...
4868 // hook up to parent
4870 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4871 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4873 // Set up as a directory
4874 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4875 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4877 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4879 // Hoosterman, another problem....
4880 // We're trying to use a non-directory as a directory
4882 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found." TENDSTR)));
4883 parent = dev->lostNFoundDir;
4886 yaffs_AddObjectToDirectory(parent,in);
4888 if(0 && (parent == dev->deletedDir ||
4889 parent == dev->unlinkedDir))
4891 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4892 dev->nDeletedFiles++;
4895 // Note re hardlinks.
4896 // Since we might scan a hardlink before its equivalent object is scanned
4897 // we put them all in a list.
4898 // After scanning is complete, we should have all the objects, so we run through this
4899 // list and fix up all the chains.
4901 switch(in->variantType)
4903 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4905 case YAFFS_OBJECT_TYPE_FILE:
4906 if(dev->isYaffs2 && oh->isShrink)
4908 // Prune back the shrunken chunks
4909 yaffs_PruneResizedChunks(in,oh->fileSize);
4910 // Mark the block as having a shrinkHeader
4911 bi->hasShrinkHeader = 1;
4914 if(dev->useHeaderFileSize)
4916 in->variant.fileVariant.fileSize = oh->fileSize;
4919 case YAFFS_OBJECT_TYPE_HARDLINK:
4920 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4921 in->hardLinks.next = (struct list_head *)hardList;
4924 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4926 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4928 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4929 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4933 if(parent == dev->deletedDir)
4935 yaffs_DestroyObject(in);
4936 bi->hasShrinkHeader = 1;
4938 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4943 if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
4945 // If we got this far while scanning, then the block is fully allocated.
4946 state = YAFFS_BLOCK_STATE_FULL;
4949 bi->blockState = state;
4951 // Now let's see if it was dirty
4952 if( bi->pagesInUse == 0 &&
4953 !bi->hasShrinkHeader &&
4954 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4956 yaffs_BlockBecameDirty(dev,blk);
4966 // Ok, we've done all the scanning.
4968 // Fix up the hard link chains.
4969 // We should now have scanned all the objects, now it's time to add these
4974 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4976 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4980 // Add the hardlink pointers
4981 hl->variant.hardLinkVariant.equivalentObject=in;
4982 list_add(&hl->hardLinks,&in->hardLinks);
4986 //Todo Need to report/handle this better.
4987 // Got a problem... hardlink to a non-existant object
4988 hl->variant.hardLinkVariant.equivalentObject=NULL;
4989 INIT_LIST_HEAD(&hl->hardLinks);
4996 struct list_head *i;
4997 struct list_head *n;
5000 // Soft delete all the unlinked files
5001 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
5005 l = list_entry(i, yaffs_Object,siblings);
5006 yaffs_DestroyObject(l);
5011 yaffs_ReleaseTempBuffer(dev,chunkData,__LINE__);
5013 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_Scan ends" TENDSTR)));
5019 static int yaffs_ScanBackwards(yaffs_Device *dev)
5021 yaffs_ExtendedTags tags;
5026 int nBlocksToScan = 0;
5031 yaffs_BlockState state;
5032 yaffs_Object *hardList = NULL;
5034 yaffs_BlockInfo *bi;
5036 yaffs_ObjectHeader *oh;
5038 yaffs_Object *parent;
5039 int nBlocks = dev->endBlock - dev->startBlock + 1;
5043 yaffs_BlockIndex *blockIndex = NULL;
5048 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5052 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_ScanBackwards starts startblk %d endblk %d..." TENDSTR),dev->startBlock,dev->endBlock));
5054 chunkData = yaffs_GetTempBuffer(dev,__LINE__);
5057 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5061 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5065 // Scan all the blocks to determine their state
5066 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
5068 bi = yaffs_GetBlockInfo(dev,blk);
5069 yaffs_ClearChunkBits(dev,blk);
5071 bi->softDeletions = 0;
5073 yaffs_QueryInitialBlockState(dev,blk,&state,&sequenceNumber);
5075 bi->blockState = state;
5076 bi->sequenceNumber = sequenceNumber;
5078 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("Block scanning block %d state %d seq %d" TENDSTR),blk,state,sequenceNumber));
5080 if(state == YAFFS_BLOCK_STATE_DEAD)
5082 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
5084 else if(state == YAFFS_BLOCK_STATE_EMPTY)
5086 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("Block empty " TENDSTR)));
5087 dev->nErasedBlocks++;
5088 dev->nFreeChunks += dev->nChunksPerBlock;
5090 else if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
5093 // Determine the highest sequence number
5094 if( dev->isYaffs2 &&
5095 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5096 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER)
5099 blockIndex[nBlocksToScan].seq = sequenceNumber;
5100 blockIndex[nBlocksToScan].block = blk;
5104 if(sequenceNumber >= dev->sequenceNumber)
5106 dev->sequenceNumber = sequenceNumber;
5109 else if(dev->isYaffs2)
5111 // TODO: Nasty sequence number!
5112 T(YAFFS_TRACE_SCAN,(TSTR("Block scanning block %d has bad sequence number %d" TENDSTR),blk,sequenceNumber));
5119 // Dungy old bubble sort for now...
5122 yaffs_BlockIndex temp;
5126 for(i = 0; i < nBlocksToScan; i++)
5127 for(j = i+1; j < nBlocksToScan; j++)
5128 if(blockIndex[i].seq > blockIndex[j].seq)
5130 temp = blockIndex[j];
5131 blockIndex[j] = blockIndex[i];
5132 blockIndex[i] = temp;
5137 // Now scan the blocks looking at the data.
5141 endIterator = nBlocksToScan-1;
5142 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("%d blocks to be scanned" TENDSTR),nBlocksToScan));
5146 // For each block.... backwards
5147 for(blockIterator = endIterator; blockIterator >= startIterator; blockIterator--)
5150 // get the block to scan in the correct order
5151 blk = blockIndex[blockIterator].block;
5154 bi = yaffs_GetBlockInfo(dev,blk);
5155 state = bi->blockState;
5159 if( 0 && // Disable since this is redundant.
5160 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
5162 // Let's look at the first chunk in the block
5163 chunk = blk * dev->nChunksPerBlock;
5165 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,NULL,&tags);
5167 // Let's have a good look at this chunk...
5171 // An unassigned chunk in the block
5172 // This means that either the block is empty or
5173 // this is the one being allocated from
5175 // We're looking at the first chunk in the block so the block is unused
5176 state = YAFFS_BLOCK_STATE_EMPTY;
5177 dev->nErasedBlocks++;
5178 dev->nFreeChunks += dev->nChunksPerBlock;
5183 // For each chunk in each block that needs scanning....
5184 for(c = dev->nChunksPerBlock-1; c >= 0 &&
5185 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5186 state == YAFFS_BLOCK_STATE_ALLOCATING); c--)
5188 // Scan backwards...
5189 // Read the tags and decide what to do
5190 chunk = blk * dev->nChunksPerBlock + c;
5192 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,NULL,&tags);
5194 // Let's have a good look at this chunk...
5198 // An unassigned chunk in the block
5199 // This means that either the block is empty or
5200 // this is the one being allocated from
5204 // We're looking at the first chunk in the block so the block is unused
5205 state = YAFFS_BLOCK_STATE_EMPTY;
5206 dev->nErasedBlocks++;
5210 // this is the block being allocated from
5211 if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
5213 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
5215 state = YAFFS_BLOCK_STATE_ALLOCATING;
5216 dev->allocationBlock = blk;
5217 dev->allocationPage = c;
5218 dev->allocationBlockFinder = blk; // Set it to here to encourage the allocator to
5219 // go forth from here.
5220 //Yaffs2 sanity check:
5221 // This should be the one with the highest sequence number
5222 if(dev->isYaffs2 && (dev->sequenceNumber != bi->sequenceNumber))
5224 T(YAFFS_TRACE_ALWAYS,
5225 (TSTR("yaffs: Allocation block %d was not highest sequence id: block seq = %d, dev seq = %d" TENDSTR),
5226 blk,bi->sequenceNumber,dev->sequenceNumber));
5230 dev->nFreeChunks ++;
5232 else if(tags.chunkId > 0)
5234 // chunkId > 0 so it is a data chunk...
5235 unsigned int endpos;
5237 __u32 chunkBase = (tags.chunkId - 1)* dev->nBytesPerChunk;
5239 yaffs_SetChunkBit(dev,blk,c);
5242 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
5243 if(in->variantType == YAFFS_OBJECT_TYPE_FILE &&
5244 chunkBase < in->variant.fileVariant.shrinkSize)
5246 // This has not been invalidated by a resize
5247 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,-1);
5250 // File size is calculated by looking at the data chunks if we have not
5251 // seen an object header yet. Stop this practice once we find an object header.
5252 endpos = (tags.chunkId - 1)* dev->nBytesPerChunk + tags.byteCount;
5253 if(!in->valid && // have not got an object header yet
5254 in->variant.fileVariant.scannedFileSize <endpos)
5256 in->variant.fileVariant.scannedFileSize = endpos;
5257 in->variant.fileVariant.fileSize = in->variant.fileVariant.scannedFileSize;
5263 // This chunk has been invalidated by a resize, so delete
5264 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
5268 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
5272 // chunkId == 0, so it is an ObjectHeader.
5273 // Thus, we read in the object header and make the object
5274 yaffs_SetChunkBit(dev,blk,c);
5280 if(tags.extraHeaderInfoAvailable)
5282 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,tags.extraObjectType);
5286 if(!in || !in->valid)
5289 // If we don't have valid info then we need to read the chunk
5290 // TODO In future we can probably defer reading the chunk and
5291 // living with invalid data until needed.
5293 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,chunkData,NULL);
5295 oh = (yaffs_ObjectHeader *)chunkData;
5298 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
5304 // TODO Hoosterman we have a problem!
5305 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: Could not make object for object %d at chunk %d during scan" TENDSTR),tags.objectId,chunk));
5311 // We have already filled this one. We have a duplicate that will be discarded, but
5312 // we first have to suck out resize info if it is a file.
5314 if( (in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5315 ((oh && oh->type == YAFFS_OBJECT_TYPE_FILE) ||
5316 (tags.extraHeaderInfoAvailable && tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5319 __u32 thisSize = (oh) ? oh->fileSize : tags.extraFileLength;
5320 __u32 parentObjectId = (oh) ? oh->parentObjectId : tags.extraParentObjectId;
5321 unsigned isShrink = (oh) ? oh->isShrink : tags.extraIsShrinkHeader;
5323 // If it is deleted (unlinked at start also means deleted)
5324 // we treat the file size as being zeroed at this point.
5325 if(parentObjectId == YAFFS_OBJECTID_DELETED ||
5326 parentObjectId == YAFFS_OBJECTID_UNLINKED)
5332 if(in->variant.fileVariant.shrinkSize > thisSize)
5334 in->variant.fileVariant.shrinkSize = thisSize;
5339 bi->hasShrinkHeader = 1;
5343 // Use existing - destroy this one.
5344 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
5349 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5350 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5352 // We only load some info, don't fiddle with directory structure
5354 in->variantType = oh->type;
5356 in->st_mode = oh->st_mode;
5357 #ifdef CONFIG_YAFFS_WINCE
5358 in->win_atime[0] = oh->win_atime[0];
5359 in->win_ctime[0] = oh->win_ctime[0];
5360 in->win_mtime[0] = oh->win_mtime[0];
5361 in->win_atime[1] = oh->win_atime[1];
5362 in->win_ctime[1] = oh->win_ctime[1];
5363 in->win_mtime[1] = oh->win_mtime[1];
5365 in->st_uid = oh->st_uid;
5366 in->st_gid = oh->st_gid;
5367 in->st_atime = oh->st_atime;
5368 in->st_mtime = oh->st_mtime;
5369 in->st_ctime = oh->st_ctime;
5370 in->st_rdev = oh->st_rdev;
5372 in->chunkId = chunk;
5377 // we need to load this info
5380 in->variantType = oh->type;
5382 in->st_mode = oh->st_mode;
5383 #ifdef CONFIG_YAFFS_WINCE
5384 in->win_atime[0] = oh->win_atime[0];
5385 in->win_ctime[0] = oh->win_ctime[0];
5386 in->win_mtime[0] = oh->win_mtime[0];
5387 in->win_atime[1] = oh->win_atime[1];
5388 in->win_ctime[1] = oh->win_ctime[1];
5389 in->win_mtime[1] = oh->win_mtime[1];
5391 in->st_uid = oh->st_uid;
5392 in->st_gid = oh->st_gid;
5393 in->st_atime = oh->st_atime;
5394 in->st_mtime = oh->st_mtime;
5395 in->st_ctime = oh->st_ctime;
5396 in->st_rdev = oh->st_rdev;
5398 in->chunkId = chunk;
5400 yaffs_SetObjectName(in,oh->name);
5403 // directory stuff...
5404 // hook up to parent
5406 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
5407 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
5409 // Set up as a directory
5410 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
5411 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
5413 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5415 // Hoosterman, another problem....
5416 // We're trying to use a non-directory as a directory
5418 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found." TENDSTR)));
5419 parent = dev->lostNFoundDir;
5422 yaffs_AddObjectToDirectory(parent,in);
5424 if((parent == dev->deletedDir ||
5425 parent == dev->unlinkedDir))
5427 in->deleted = 1; // If it is unlinked at start up then it wants deleting
5432 // Mark the block as having a shrinkHeader
5433 bi->hasShrinkHeader = 1;
5437 // Note re hardlinks.
5438 // Since we might scan a hardlink before its equivalent object is scanned
5439 // we put them all in a list.
5440 // After scanning is complete, we should have all the objects, so we run through this
5441 // list and fix up all the chains.
5443 switch(in->variantType)
5445 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
5447 case YAFFS_OBJECT_TYPE_FILE:
5450 if(in->variant.fileVariant.scannedFileSize < oh->fileSize)
5452 in->variant.fileVariant.fileSize = oh->fileSize;
5453 in->variant.fileVariant.scannedFileSize = in->variant.fileVariant.fileSize;
5458 if(in->variant.fileVariant.shrinkSize > oh->fileSize)
5460 in->variant.fileVariant.shrinkSize = oh->fileSize;
5465 case YAFFS_OBJECT_TYPE_HARDLINK:
5466 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
5467 in->hardLinks.next = (struct list_head *)hardList;
5470 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
5472 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
5474 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
5475 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
5480 if(parent == dev->deletedDir)
5482 yaffs_DestroyObject(in);
5483 bi->hasShrinkHeader = 1;
5486 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
5491 if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
5493 // If we got this far while scanning, then the block is fully allocated.
5494 state = YAFFS_BLOCK_STATE_FULL;
5497 bi->blockState = state;
5499 // Now let's see if it was dirty
5500 if( bi->pagesInUse == 0 &&
5501 !bi->hasShrinkHeader &&
5502 bi->blockState == YAFFS_BLOCK_STATE_FULL)
5504 yaffs_BlockBecameDirty(dev,blk);
5514 // Ok, we've done all the scanning.
5516 // Fix up the hard link chains.
5517 // We should now have scanned all the objects, now it's time to add these
5522 hardList = (yaffs_Object *)(hardList->hardLinks.next);
5524 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
5528 // Add the hardlink pointers
5529 hl->variant.hardLinkVariant.equivalentObject=in;
5530 list_add(&hl->hardLinks,&in->hardLinks);
5534 //Todo Need to report/handle this better.
5535 // Got a problem... hardlink to a non-existant object
5536 hl->variant.hardLinkVariant.equivalentObject=NULL;
5537 INIT_LIST_HEAD(&hl->hardLinks);
5544 struct list_head *i;
5545 struct list_head *n;
5549 // Soft delete all the unlinked files
5550 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
5554 l = list_entry(i, yaffs_Object,siblings);
5555 yaffs_DestroyObject(l);
5559 // Soft delete all the deletedDir files
5560 list_for_each_safe(i,n,&dev->deletedDir->variant.directoryVariant.children)
5564 l = list_entry(i, yaffs_Object,siblings);
5565 yaffs_DestroyObject(l);
5571 yaffs_ReleaseTempBuffer(dev,chunkData,__LINE__);
5573 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5580 ////////////////////////// Directory Functions /////////////////////////
5583 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
5588 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: Trying to add an object to a null pointer directory" TENDSTR)));
5591 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5593 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: Trying to add an object to a non-directory" TENDSTR)));
5597 if(obj->siblings.prev == NULL)
5600 INIT_LIST_HEAD(&obj->siblings);
5603 else if(!list_empty(&obj->siblings))
5605 // If it is holed up somewhere else, un hook it
5606 list_del_init(&obj->siblings);
5609 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
5610 obj->parent = directory;
5612 if(directory == obj->myDev->unlinkedDir || directory == obj->myDev->deletedDir)
5615 obj->myDev->nUnlinkedFiles++;
5616 obj->renameAllowed = 0;
5620 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
5622 list_del_init(&obj->siblings);
5626 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const YCHAR *name)
5630 struct list_head *i;
5631 YCHAR buffer[YAFFS_MAX_NAME_LENGTH+1];
5638 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: yaffs_FindObjectByName: null pointer directory"TENDSTR)));
5641 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5643 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: yaffs_FindObjectByName: non-directory"TENDSTR)));
5647 sum = yaffs_CalcNameSum(name);
5649 list_for_each(i,&directory->variant.directoryVariant.children)
5653 l = list_entry(i, yaffs_Object,siblings);
5655 // Special case for lost-n-found
5656 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
5658 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
5663 else if(yaffs_SumCompare(l->sum, sum)||
5664 l->chunkId <= 0) //LostnFound cunk called Objxxx
5667 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
5668 if(yaffs_strcmp(name,buffer) == 0)
5681 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
5683 struct list_head *i;
5689 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: yaffs_FindObjectByName: null pointer directory"TENDSTR)));
5692 if(theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5694 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: yaffs_FindObjectByName: non-directory"TENDSTR)));
5698 list_for_each(i,&theDir->variant.directoryVariant.children)
5702 l = list_entry(i, yaffs_Object,siblings);
5715 // GetEquivalentObject dereferences any hard links to get to the
5718 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
5720 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
5722 // We want the object id of the equivalent object, not this one
5723 obj = obj->variant.hardLinkVariant.equivalentObject;
5729 int yaffs_GetObjectName(yaffs_Object *obj,YCHAR *name,int buffSize)
5731 memset(name,0,buffSize * sizeof(YCHAR));
5733 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
5735 yaffs_strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
5737 else if(obj->chunkId <= 0)
5741 yaffs_sprintf(locName,_Y("%s%d"),YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
5742 yaffs_strncpy(name,locName,buffSize - 1);
5745 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5746 else if(obj->shortName[0])
5748 yaffs_strcpy(name,obj->shortName);
5753 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev,__LINE__);
5755 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
5757 memset(buffer,0,obj->myDev->nBytesPerChunk);
5759 if(obj->chunkId >= 0)
5761 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
5763 yaffs_strncpy(name,oh->name,buffSize - 1);
5765 yaffs_ReleaseTempBuffer(obj->myDev,buffer,__LINE__);
5768 return yaffs_strlen(name);
5771 int yaffs_GetObjectFileLength(yaffs_Object *obj)
5774 // Dereference any hard linking
5775 obj = yaffs_GetEquivalentObject(obj);
5777 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
5779 return obj->variant.fileVariant.fileSize;
5781 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5783 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5787 // Only a directory should drop through to here
5788 return obj->myDev->nBytesPerChunk;
5792 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
5795 struct list_head *i;
5799 count++; // the object itself
5801 list_for_each(i,&obj->hardLinks)
5803 count++; // add the hard links;
5810 int yaffs_GetObjectInode(yaffs_Object *obj)
5812 obj = yaffs_GetEquivalentObject(obj);
5814 return obj->objectId;
5817 unsigned yaffs_GetObjectType(yaffs_Object *obj)
5819 obj = yaffs_GetEquivalentObject(obj);
5821 switch(obj->variantType)
5823 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
5824 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
5825 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
5826 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
5827 case YAFFS_OBJECT_TYPE_SPECIAL:
5828 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
5829 if(S_ISCHR(obj->st_mode)) return DT_CHR;
5830 if(S_ISBLK(obj->st_mode)) return DT_BLK;
5831 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
5832 default: return DT_REG; break;
5836 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
5838 obj = yaffs_GetEquivalentObject(obj);
5839 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5841 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5845 return yaffs_CloneString(_Y(""));
5849 #ifndef CONFIG_YAFFS_WINCE
5851 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
5853 unsigned int valid = attr->ia_valid;
5855 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
5856 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
5857 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
5859 if(valid & ATTR_ATIME) obj->st_atime = Y_TIME_CONVERT(attr->ia_atime);
5860 if(valid & ATTR_CTIME) obj->st_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5861 if(valid & ATTR_MTIME) obj->st_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5863 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
5865 yaffs_UpdateObjectHeader(obj,NULL,1,0);
5870 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
5872 unsigned int valid = 0;
5874 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
5875 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
5876 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
5878 Y_TIME_CONVERT(attr->ia_atime)= obj->st_atime; valid |= ATTR_ATIME;
5879 Y_TIME_CONVERT(attr->ia_ctime) = obj->st_ctime; valid |= ATTR_CTIME;
5880 Y_TIME_CONVERT(attr->ia_mtime) = obj->st_mtime; valid |= ATTR_MTIME;
5882 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
5884 attr->ia_valid = valid;
5892 int yaffs_DumpObject(yaffs_Object *obj)
5894 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
5896 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
5898 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
5900 // if(obj->chunkId >= 0)
5902 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
5905 yaffs_GetObjectName(obj,name,256);
5907 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),
5908 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
5909 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5912 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
5913 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
5914 obj->sum, obj->chunkId));
5915 switch(obj->variantType)
5917 case YAFFS_OBJECT_TYPE_FILE:
5918 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
5920 case YAFFS_OBJECT_TYPE_DIRECTORY:
5921 YPRINTF((" DIRECTORY\n"));
5923 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
5924 case YAFFS_OBJECT_TYPE_SYMLINK:
5925 case YAFFS_OBJECT_TYPE_UNKNOWN:
5934 ///////////////////////// Initialisation code ///////////////////////////
5937 int yaffs_CheckDevFunctions(const yaffs_Device *dev)
5940 // Common functions, gotta have
5941 if(!dev->eraseBlockInNAND ||
5942 !dev->initialiseNAND) return 0;
5944 #ifdef CONFIG_YAFFS_YAFFS2
5946 // Can use the "with tags" style interface for yaffs1 or yaffs2
5947 if(dev->writeChunkWithTagsToNAND &&
5948 dev->readChunkWithTagsFromNAND &&
5949 !dev->writeChunkToNAND &&
5950 !dev->readChunkFromNAND &&
5951 dev->markNANDBlockBad &&
5952 dev->queryNANDBlock) return 1;
5955 // Can use the "spare" style interface for yaffs1
5956 if(!dev->isYaffs2 &&
5957 !dev->writeChunkWithTagsToNAND &&
5958 !dev->readChunkWithTagsFromNAND &&
5959 dev->writeChunkToNAND &&
5960 dev->readChunkFromNAND &&
5961 !dev->markNANDBlockBad &&
5962 !dev->queryNANDBlock) return 1;
5968 int yaffs_GutsInitialise(yaffs_Device *dev)
5975 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5976 // Check stuff that must be set
5980 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Need a device" TENDSTR)));
5984 // Check geometry parameters.
5986 if( (dev->isYaffs2 && dev->nBytesPerChunk <1024) ||
5987 (!dev->isYaffs2 && dev->nBytesPerChunk !=512) ||
5988 dev->nChunksPerBlock < 2 ||
5989 dev->nReservedBlocks < 2 ||
5990 dev->startBlock <= 0 ||
5991 dev->endBlock <= 0 ||
5992 dev->endBlock <= (dev->startBlock + dev->nReservedBlocks + 2) // otherwise it is too small
5995 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s " TENDSTR),
5996 dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6000 if(yaffs_InitialiseNAND(dev) != YAFFS_OK)
6002 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6006 // Got the right mix of functions?
6008 if(!yaffs_CheckDevFunctions(dev))
6011 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6016 // This is really a compilation check.
6017 if(!yaffs_CheckStructures())
6019 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6025 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
6031 // Finished with most checks. One or two more checks happen later on too.
6037 nBlocks = dev->endBlock - dev->startBlock + 1;
6041 // OK now calculate a few things for the device
6042 // Calculate chunkGroupBits.
6043 // We need to find the next power of 2 > than endBlock
6045 x = dev->nChunksPerBlock * (dev->endBlock+1);
6047 for(bits = extraBits = 0; x > 1; bits++)
6049 if(x & 1) extraBits++;
6053 if(extraBits > 0) bits++;
6056 // Level0 Tnodes are 16 bits, so if the bitwidth of the
6057 // chunk range we're using is greater than 16 we need
6058 // to figure out chunk shift and chunkGroupSize
6061 dev->chunkGroupBits = 0;
6065 dev->chunkGroupBits = bits - 16;
6068 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6070 if(dev->nChunksPerBlock < dev->chunkGroupSize)
6072 // We have a problem because the soft delete won't work if
6073 // the chunk group size > chunks per block.
6074 // This can be remedied by using larger "virtual blocks".
6075 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: chunk group too large\n" TENDSTR)));
6081 // OK, we've finished verifying the device, lets continue with initialisation
6083 // More device initialisation
6084 dev->garbageCollections = 0;
6085 dev->passiveGarbageCollections = 0;
6086 dev->currentDirtyChecker = 0;
6087 dev->bufferedBlock = -1;
6088 dev->doingBufferedBlockRewrite = 0;
6089 dev->nDeletedFiles = 0;
6090 dev->nBackgroundDeletions=0;
6091 dev->nUnlinkedFiles = 0;
6094 dev->tagsEccFixed=0;
6095 dev->tagsEccUnfixed=0;
6096 dev->nErasureFailures = 0;
6097 dev->nErasedBlocks = 0;
6099 //dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
6100 // Initialise temporary buffers
6103 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
6105 dev->tempBuffer[i].line = 0; // not in use
6106 dev->tempBuffer[i].buffer = YMALLOC(dev->nBytesPerChunk);
6112 yaffs_InitialiseBlocks(dev,nBlocks);
6114 yaffs_InitialiseTnodes(dev);
6116 yaffs_InitialiseObjects(dev);
6118 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6120 if(dev->nShortOpCaches > 0)
6124 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
6126 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6129 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6131 for(i=0; i < dev->nShortOpCaches; i++)
6133 dev->srCache[i].object = NULL;
6134 dev->srCache[i].lastUse = 0;
6135 dev->srCache[i].dirty = 0;
6136 dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
6144 // Initialise the unlinked, root and lost and found directories
6145 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = dev->deletedDir = NULL;
6147 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6148 dev->deletedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_DELETED, S_IFDIR);
6150 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
6151 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6152 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
6156 dev->useHeaderFileSize = 1;
6159 // Now scan the flash.
6162 yaffs_ScanBackwards(dev);
6167 dev->nPageReads = 0;
6168 dev->nPageWrites = 0;
6169 dev->nBlockErasures = 0;
6171 dev->nRetriedWrites = 0;
6173 dev->nRetiredBlocks = 0;
6175 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6180 void yaffs_Deinitialise(yaffs_Device *dev)
6186 yaffs_DeinitialiseBlocks(dev);
6187 yaffs_DeinitialiseTnodes(dev);
6188 yaffs_DeinitialiseObjects(dev);
6189 if(dev->nShortOpCaches > 0)
6192 for(i=0; i < dev->nShortOpCaches; i++)
6194 YFREE(dev->srCache[i].data);
6197 YFREE(dev->srCache);
6200 YFREE(dev->gcCleanupList);
6202 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
6204 YFREE(dev->tempBuffer[i].buffer);
6214 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
6216 int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
6218 struct list_head *i;
6222 // To the free chunks add the chunks that are in the deleted unlinked files.
6223 list_for_each(i,&dev->deletedDir->variant.directoryVariant.children)
6225 l = list_entry(i, yaffs_Object,siblings);
6229 nFree += l->nDataChunks;
6234 // printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
6236 if(nFree < 0) nFree = 0;
6244 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
6249 int nDirtyCacheChunks=0;
6251 yaffs_BlockInfo *blk;
6253 struct list_head *i;
6256 for(nFree = 0, b = dev->startBlock; b <= dev->endBlock; b++)
6258 blk = yaffs_GetBlockInfo(dev,b);
6260 switch(blk->blockState)
6262 case YAFFS_BLOCK_STATE_EMPTY:
6263 case YAFFS_BLOCK_STATE_ALLOCATING:
6264 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse); break;
6272 // To the free chunks add the chunks that are in the deleted unlinked files.
6273 list_for_each(i,&dev->deletedDir->variant.directoryVariant.children)
6277 l = list_entry(i, yaffs_Object,siblings);
6281 pending += l->nDataChunks;
6288 //printf("___________ really free is %d, pending %d, nFree is %d\n",nFree,pending, nFree+pending);
6290 if(nFree != dev->nFreeChunks)
6292 // printf("___________Different! really free is %d, nFreeChunks %d\n",nFree dev->nFreeChunks);
6297 // Now count the number of dirty chunks in the cache and subtract those
6301 for(i = 0; i < dev->nShortOpCaches; i++)
6303 if(dev->srCache[i].dirty) nDirtyCacheChunks++;
6307 nFree -= nDirtyCacheChunks;
6309 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6311 if(nFree < 0) nFree = 0;
6319 /////////////////// YAFFS test code //////////////////////////////////
6321 #define yaffs_CheckStruct(structure,syze, name) \
6322 if(sizeof(structure) != syze) \
6324 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
6325 return YAFFS_FAIL; \
6329 static int yaffs_CheckStructures(void)
6331 // yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
6332 // yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
6333 // yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
6334 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6335 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
6337 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
6344 void yaffs_GutsTest(yaffs_Device *dev)
6347 if(yaffs_CheckStructures() != YAFFS_OK)
6349 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
6353 yaffs_TnodeTest(dev);
6354 yaffs_ObjectTest(dev);