2 * YAFFS: Yet another FFS. A NAND-flash specific file system.
4 * Copyright (C) 2002 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
16 const char *yaffs_guts_c_version="$Id: yaffs_guts.c,v 1.13 2005-08-01 04:53:01 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
25 #include "yaffs_tagscompat.h"
27 #ifdef CONFIG_YAFFS_WINCE
28 void yfsd_LockYAFFS(BOOL fsLockOnly);
29 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
32 #define YAFFS_PASSIVE_GC_CHUNKS 2
35 // Use Steven Hill's ECC struff instead
36 // External functions for ECC on data
37 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
38 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
39 #define yaffs_ECCCalculate(data,ecc) nand_calculate_ecc(data,ecc)
40 #define yaffs_ECCCorrect(data,read_ecc,calc_ecc) nand_correct_ecc(data,read_ecc,calc_ecc)
42 #include "yaffs_ecc.h"
46 // countBits is a quick way of counting the number of bits in a byte.
47 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
49 static const char yaffs_countBitsTable[256] =
51 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
52 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
53 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
54 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
55 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
56 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
57 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
58 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
59 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
60 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
61 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
62 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
63 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
64 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
65 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
66 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
69 static int yaffs_CountBits(__u8 x)
72 retVal = yaffs_countBitsTable[x];
80 // Stuff using yea olde tags
81 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
82 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
84 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
85 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
92 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *buffer, yaffs_ExtendedTags *tags);
93 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *data, yaffs_ExtendedTags *tags);
94 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo);
95 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device *dev,int blockNo, yaffs_BlockState *state,unsigned *sequenceNumber);
97 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_ExtendedTags *tags, int useReserve);
99 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
101 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
103 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
104 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
105 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const YCHAR *name, int force,int isShrink, int shadows);
106 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
107 static int yaffs_CheckStructures(void);
108 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
109 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
111 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
113 static __u8 *yaffs_GetTempBuffer(yaffs_Device *dev,int lineNo);
114 static void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo);
117 // Robustification (if it ever comes about...)
118 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
120 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
122 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
123 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_ExtendedTags *tags);
124 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_ExtendedTags *tags);
126 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
128 static int yaffs_UnlinkWorker(yaffs_Object *obj);
129 static void yaffs_DestroyObject(yaffs_Object *obj);
132 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1,int dataSize);
135 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId, int chunkInObject);
138 loff_t yaffs_GetFileSize(yaffs_Object *obj);
141 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
143 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
145 #ifdef YAFFS_PARANOID
146 static int yaffs_CheckFileSanity(yaffs_Object *in);
148 #define yaffs_CheckFileSanity(in)
151 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
152 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
154 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *buffer, yaffs_ExtendedTags *tags)
156 chunkInNAND -= dev->chunkOffset;
158 if(dev->readChunkWithTagsFromNAND)
159 return dev->readChunkWithTagsFromNAND(dev,chunkInNAND,buffer,tags);
161 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,tags);
164 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_ExtendedTags *tags)
166 chunkInNAND -= dev->chunkOffset;
170 tags->sequenceNumber = dev->sequenceNumber;
172 if(!yaffs_ValidateTags(tags))
174 T(YAFFS_TRACE_ERROR,(TSTR("Writing uninitialised tags" TENDSTR)));
177 T(YAFFS_TRACE_WRITE,(TSTR("Writing chunk %d tags %d %d"TENDSTR),chunkInNAND,tags->objectId,tags->chunkId));
181 T(YAFFS_TRACE_ERROR,(TSTR("Writing with no tags" TENDSTR)));
185 if(dev->writeChunkWithTagsToNAND)
186 return dev->writeChunkWithTagsToNAND(dev,chunkInNAND,buffer,tags);
188 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,chunkInNAND,buffer,tags);
191 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device *dev, int blockNo)
193 blockNo -= dev->blockOffset;
195 if(dev->markNANDBlockBad)
196 return dev->markNANDBlockBad(dev,blockNo);
198 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev,blockNo);
200 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device *dev,int blockNo, yaffs_BlockState *state, unsigned *sequenceNumber)
202 blockNo -= dev->blockOffset;
204 if(dev->queryNANDBlock)
205 return dev->queryNANDBlock(dev,blockNo,state,sequenceNumber);
207 return yaffs_TagsCompatabilityQueryNANDBlock(dev,blockNo,state,sequenceNumber);
210 static int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
214 blockInNAND -= dev->blockOffset;
216 dev->nBlockErasures++;
217 result = dev->eraseBlockInNAND(dev,blockInNAND);
219 if(!result)result = dev->eraseBlockInNAND(dev,blockInNAND); // If at first we don't succeed, try again *once*.
223 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
225 return dev->initialiseNAND(dev);
231 // Temporary buffer manipulations
233 static __u8 *yaffs_GetTempBuffer(yaffs_Device *dev,int lineNo)
236 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
238 if(dev->tempBuffer[i].line == 0)
240 dev->tempBuffer[i].line = lineNo;
241 if((i+1) > dev->maxTemp)
243 dev->maxTemp = i + 1;
244 for(j = 0; j <= i; j++)
245 dev->tempBuffer[j].maxLine = dev->tempBuffer[j].line;
248 return dev->tempBuffer[i].buffer;
252 T(YAFFS_TRACE_BUFFERS,(TSTR("Out of temp buffers at line %d, other held by lines:"),lineNo));
253 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
255 T(YAFFS_TRACE_BUFFERS,(TSTR(" %d "),dev->tempBuffer[i].line));
257 T(YAFFS_TRACE_BUFFERS,(TSTR(" "TENDSTR)));
259 dev->unmanagedTempAllocations++;
260 // Get an unmanaged one
261 return YMALLOC(dev->nBytesPerChunk);
266 static void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer, int lineNo)
269 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
271 if(dev->tempBuffer[i].buffer == buffer)
273 dev->tempBuffer[i].line = 0;
280 // assume it is an unmanaged one.
281 T(YAFFS_TRACE_BUFFERS,(TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),lineNo));
283 dev->unmanagedTempDeallocations++;
289 // Chunk bitmap manipulations
291 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
293 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock)
295 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),blk));
298 return dev->chunkBits + (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
301 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev,int blk)
303 __u8 *blkBits = yaffs_BlockBits(dev,blk);
305 memset(blkBits,0,dev->chunkBitmapStride);
308 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev,int blk,int chunk)
310 __u8 *blkBits = yaffs_BlockBits(dev,blk);
312 blkBits[chunk/8] &= ~ (1<<(chunk & 7));
315 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev,int blk,int chunk)
317 __u8 *blkBits = yaffs_BlockBits(dev,blk);
319 blkBits[chunk/8] |= (1<<(chunk & 7));
322 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev,int blk,int chunk)
324 __u8 *blkBits = yaffs_BlockBits(dev,blk);
325 return (blkBits[chunk/8] & (1<<(chunk & 7))) ? 1 :0;
328 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev,int blk)
330 __u8 *blkBits = yaffs_BlockBits(dev,blk);
332 for(i = 0; i < dev->chunkBitmapStride; i++)
334 if(*blkBits) return 1;
341 static Y_INLINE int yaffs_HashFunction(int n)
343 return (n % YAFFS_NOBJECT_BUCKETS);
347 yaffs_Object *yaffs_Root(yaffs_Device *dev)
352 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
354 return dev->lostNFoundDir;
360 int yaffs_CheckFF(__u8 *buffer,int nBytes)
362 //Horrible, slow implementation
365 if(*buffer != 0xFF) return 0;
371 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
374 int retval = YAFFS_OK;
375 __u8 *data = yaffs_GetTempBuffer(dev,__LINE__);
376 yaffs_ExtendedTags tags;
378 // NCB dev->readChunkWithTagsFromNAND(dev,chunkInNAND,data,&tags);
379 yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,data,&tags);
381 if(!yaffs_CheckFF(data,dev->nBytesPerChunk) || tags.chunkUsed)
383 T(YAFFS_TRACE_NANDACCESS,(TSTR("Chunk %d not erased" TENDSTR),chunkInNAND));
387 yaffs_ReleaseTempBuffer(dev,data,__LINE__);
396 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_ExtendedTags *tags,int useReserve)
406 chunk = yaffs_AllocateChunk(dev,useReserve);
411 // First check this chunk is erased...
412 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
413 writeOk = yaffs_CheckChunkErased(dev,chunk);
417 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
421 writeOk = yaffs_WriteChunkWithTagsToNAND(dev,chunk,data,tags);
427 // Copy the data into the robustification buffer.
428 // NB We do this at the end to prevent duplicates in the case of a write error.
430 yaffs_HandleWriteChunkOk(dev,chunk,data,tags);
434 yaffs_HandleWriteChunkError(dev,chunk);
438 } while(chunk >= 0 && ! writeOk);
442 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
443 dev->nRetriedWrites+= (attempts - 1);
454 // Functions for robustisizing
458 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
461 yaffs_MarkBlockBad(dev,blockInNAND);
463 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
465 dev->nRetiredBlocks++;
470 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
472 dev->doingBufferedBlockRewrite = 1;
474 // Remove erased chunks
475 // Rewrite existing chunks to a new block
476 // Set current write block to the new block
478 dev->doingBufferedBlockRewrite = 0;
484 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
486 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
488 // Mark the block for retirement
489 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
490 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
494 // Just do a garbage collection on the affected block then retire the block
499 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
505 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_ExtendedTags *tags)
509 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_ExtendedTags *tags)
513 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
515 int blockInNAND = chunkInNAND/dev->nChunksPerBlock;
517 // Mark the block for retirement
518 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
520 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
526 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1,int dataSize)
530 if( memcmp(d0,d1,dataSize) != 0 ||
531 s0->tagByte0 != s1->tagByte0 ||
532 s0->tagByte1 != s1->tagByte1 ||
533 s0->tagByte2 != s1->tagByte2 ||
534 s0->tagByte3 != s1->tagByte3 ||
535 s0->tagByte4 != s1->tagByte4 ||
536 s0->tagByte5 != s1->tagByte5 ||
537 s0->tagByte6 != s1->tagByte6 ||
538 s0->tagByte7 != s1->tagByte7 ||
539 s0->ecc1[0] != s1->ecc1[0] ||
540 s0->ecc1[1] != s1->ecc1[1] ||
541 s0->ecc1[2] != s1->ecc1[2] ||
542 s0->ecc2[0] != s1->ecc2[0] ||
543 s0->ecc2[1] != s1->ecc2[1] ||
544 s0->ecc2[2] != s1->ecc2[2] )
554 ///////////////////////// Object management //////////////////
555 // List of spare objects
556 // The list is hooked together using the first pointer
559 // static yaffs_Object *yaffs_freeObjects = NULL;
561 // static int yaffs_nFreeObjects;
563 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
565 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
568 static __u16 yaffs_CalcNameSum(const YCHAR *name)
573 YUCHAR *bname = (YUCHAR *)name;
576 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
579 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
580 sum += yaffs_toupper(*bname) * i;
591 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
593 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
594 if(name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
596 yaffs_strcpy(obj->shortName,name);
600 obj->shortName[0]=_Y('\0');
603 obj->sum = yaffs_CalcNameSum(name);
607 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
609 yaffs_ECCCalculate(data , spare->ecc1);
610 yaffs_ECCCalculate(&data[256] , spare->ecc2);
615 ///////////////////////// TNODES ///////////////////////
617 // List of spare tnodes
618 // The list is hooked together using the first pointer
621 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
623 // static int yaffs_nFreeTnodes;
625 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
629 // yaffs_CreateTnodes creates a bunch more tnodes and
630 // adds them to the tnode free list.
631 // Don't use this function directly
633 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
636 yaffs_Tnode *newTnodes;
637 yaffs_TnodeList *tnl;
639 if(nTnodes < 1) return YAFFS_OK;
643 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
647 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
651 // Hook them into the free list
652 for(i = 0; i < nTnodes - 1; i++)
654 newTnodes[i].internal[0] = &newTnodes[i+1];
655 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
656 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
660 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
661 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
662 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
664 dev->freeTnodes = newTnodes;
665 dev->nFreeTnodes+= nTnodes;
666 dev->nTnodesCreated += nTnodes;
668 // Now add this bunch of tnodes to a list for freeing up.
669 // NB If we can't add this to the management list it isn't fatal
670 // but it just means we can't free this bunch of tnodes later.
671 tnl = YMALLOC(sizeof(yaffs_TnodeList));
674 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
679 tnl->tnodes = newTnodes;
680 tnl->next = dev->allocatedTnodeList;
681 dev->allocatedTnodeList = tnl;
685 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
692 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
693 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
695 yaffs_Tnode *tn = NULL;
697 // If there are none left make more
700 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
705 tn = dev->freeTnodes;
706 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
707 if(tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1)
709 // Hoosterman, this thing looks like it isn't in the list
710 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 1" TENDSTR)));
713 dev->freeTnodes = dev->freeTnodes->internal[0];
716 memset(tn,0,sizeof(yaffs_Tnode));
724 // FreeTnode frees up a tnode and puts it back on the free list
725 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
729 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
730 if(tn->internal[YAFFS_NTNODES_INTERNAL] != 0)
732 // Hoosterman, this thing looks like it is already in the list
733 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Tnode list bug 2" TENDSTR)));
735 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
737 tn->internal[0] = dev->freeTnodes;
738 dev->freeTnodes = tn;
744 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
746 // Free the list of allocated tnodes
747 yaffs_TnodeList *tmp;
749 while(dev->allocatedTnodeList)
751 tmp = dev->allocatedTnodeList->next;
753 YFREE(dev->allocatedTnodeList->tnodes);
754 YFREE(dev->allocatedTnodeList);
755 dev->allocatedTnodeList = tmp;
759 dev->freeTnodes = NULL;
760 dev->nFreeTnodes = 0;
763 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
765 dev->allocatedTnodeList = NULL;
766 dev->freeTnodes = NULL;
767 dev->nFreeTnodes = 0;
768 dev->nTnodesCreated = 0;
773 void yaffs_TnodeTest(yaffs_Device *dev)
778 yaffs_Tnode *tn[1000];
780 YINFO("Testing TNodes");
782 for(j = 0; j < 50; j++)
784 for(i = 0; i < 1000; i++)
786 tn[i] = yaffs_GetTnode(dev);
789 YALERT("Getting tnode failed");
792 for(i = 0; i < 1000; i+=3)
794 yaffs_FreeTnode(dev,tn[i]);
803 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
805 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
806 // The look up tree is represented by the top tnode and the number of topLevel
807 // in the tree. 0 means only the level 0 tnode is in the tree.
810 // FindLevel0Tnode finds the level 0 tnode, if one exists.
811 // Used when reading.....
812 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
815 yaffs_Tnode *tn = fStruct->top;
817 int requiredTallness;
818 int level = fStruct->topLevel;
820 // Check sane level and chunk Id
821 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
824 // sprintf(str,"Bad level %d",level);
829 if(chunkId > YAFFS_MAX_CHUNK_ID)
832 // sprintf(str,"Bad chunkId %d",chunkId);
837 // First check we're tall enough (ie enough topLevel)
839 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
840 requiredTallness = 0;
843 i >>= YAFFS_TNODES_INTERNAL_BITS;
848 if(requiredTallness > fStruct->topLevel)
850 // Not tall enough, so we can't find it, return NULL.
855 // Traverse down to level 0
856 while (level > 0 && tn)
858 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
859 YAFFS_TNODES_INTERNAL_MASK];
867 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
868 // This happens in two steps:
869 // 1. If the tree isn't tall enough, then make it taller.
870 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
872 // Used when modifying the tree.
874 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
879 int requiredTallness;
886 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
888 // Check sane level and page Id
889 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
892 // sprintf(str,"Bad level %d",fStruct->topLevel);
897 if(chunkId > YAFFS_MAX_CHUNK_ID)
900 // sprintf(str,"Bad chunkId %d",chunkId);
905 // First check we're tall enough (ie enough topLevel)
907 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
908 requiredTallness = 0;
911 x >>= YAFFS_TNODES_INTERNAL_BITS;
915 //T((TSTR(" required=%d"),requiredTallness));
918 if(requiredTallness > fStruct->topLevel)
920 // Not tall enough,gotta make the tree taller
921 for(i = fStruct->topLevel; i < requiredTallness; i++)
923 //T((TSTR(" add new top")));
925 tn = yaffs_GetTnode(dev);
929 tn->internal[0] = fStruct->top;
934 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
938 fStruct->topLevel = requiredTallness;
942 // Traverse down to level 0, adding anything we need
944 l = fStruct->topLevel;
948 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
949 YAFFS_TNODES_INTERNAL_MASK;
951 //T((TSTR(" [%d:%d]"),l,i));
955 //T((TSTR(" added")));
957 tn->internal[x] = yaffs_GetTnode(dev);
960 tn = tn->internal[x];
971 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk, yaffs_ExtendedTags *tags, int objectId, int chunkInInode)
976 for(j = 0; theChunk && j < dev->chunkGroupSize; j++)
978 if(yaffs_CheckChunkBit(dev,theChunk / dev->nChunksPerBlock,theChunk % dev->nChunksPerBlock))
980 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL,tags);
981 if(yaffs_TagsMatch(tags,objectId,chunkInInode))
993 // DeleteWorker scans backwards through the tnode tree and deletes all the
994 // chunks and tnodes in the file
995 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
997 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
1002 yaffs_ExtendedTags tags;
1004 yaffs_Device *dev = in->myDev;
1014 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1018 if(limit && (*limit) < 0)
1024 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
1025 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
1029 yaffs_FreeTnode(dev,tn->internal[i]);
1030 tn->internal[i] = NULL;
1035 return (allDone) ? 1 : 0;
1041 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0 && !hitLimit; i--)
1046 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
1048 theChunk = tn->level0[i] << dev->chunkGroupBits;
1050 foundChunk = yaffs_FindChunkInGroup(dev,theChunk,&tags,in->objectId,chunkInInode);
1054 yaffs_DeleteChunk(dev,foundChunk,1,__LINE__);
1071 return (i < 0) ? 1 : 0;
1083 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1086 yaffs_BlockInfo *theBlock;
1088 T(YAFFS_TRACE_DELETION,(TSTR("soft delete chunk %d" TENDSTR),chunk));
1090 theBlock = yaffs_GetBlockInfo(dev, chunk/dev->nChunksPerBlock);
1093 theBlock->softDeletions++;
1098 // SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1099 // All soft deleting does is increment the block's softdelete count and pulls the chunk out
1101 // THus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1103 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset)
1108 yaffs_Device *dev = in->myDev;
1116 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
1120 allDone = yaffs_SoftDeleteWorker(in,tn->internal[i],level - 1,
1121 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i);
1124 yaffs_FreeTnode(dev,tn->internal[i]);
1125 tn->internal[i] = NULL;
1129 //Hoosterman... how could this happen.
1133 return (allDone) ? 1 : 0;
1138 for(i = YAFFS_NTNODES_LEVEL0 -1; i >=0; i--)
1142 // Note this does not find the real chunk, only the chunk group.
1143 // We make an assumption that a chunk group is niot larger than a block.
1144 theChunk = (tn->level0[i] << dev->chunkGroupBits);
1146 yaffs_SoftDeleteChunk(dev,theChunk);
1163 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1166 obj->variantType == YAFFS_OBJECT_TYPE_FILE &&
1169 if(obj->nDataChunks <= 0)
1171 // Empty file with no duplicate object headers, just delete it immediately
1172 yaffs_FreeTnode(obj->myDev,obj->variant.fileVariant.top);
1173 obj->variant.fileVariant.top = NULL;
1174 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: Deleting empty file %d" TENDSTR),obj->objectId));
1175 yaffs_DoGenericObjectDeletion(obj);
1179 yaffs_SoftDeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0);
1180 obj->softDeleted = 1;
1189 // Pruning removes any part of the file structure tree that is beyond the
1190 // bounds of the file (ie that does not point to chunks).
1192 // A file should only get pruned when its size is reduced.
1194 // Before pruning, the chunks must be pulled from the tree and the
1195 // level 0 tnode entries must be zeroed out.
1196 // Could also use this for file deletion, but that's probably better handled
1197 // by a special case.
1199 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1201 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1210 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1212 if(tn->internal[i] && level > 0)
1214 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1223 if(hasData == 0 && del0)
1225 // Free and return NULL
1227 yaffs_FreeTnode(dev,tn);
1237 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1244 if(fStruct->topLevel > 0)
1246 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1248 // Now we have a tree with all the non-zero branches NULL but the height
1249 // is the same as it was.
1250 // Let's see if we can trim internal tnodes to shorten the tree.
1251 // We can do this if only the 0th element in the tnode is in use
1252 // (ie all the non-zero are NULL)
1254 while(fStruct->topLevel && !done)
1259 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1269 fStruct->top = tn->internal[0];
1270 fStruct->topLevel--;
1271 yaffs_FreeTnode(dev,tn);
1287 /////////////////////// End of File Structure functions. /////////////////
1289 // yaffs_CreateFreeObjects creates a bunch more objects and
1290 // adds them to the object free list.
1291 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1294 yaffs_Object *newObjects;
1295 yaffs_ObjectList *list;
1297 if(nObjects < 1) return YAFFS_OK;
1299 // make these things
1301 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1305 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1309 // Hook them into the free list
1310 for(i = 0; i < nObjects - 1; i++)
1312 newObjects[i].siblings.next = (struct list_head *)(&newObjects[i+1]);
1315 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1316 dev->freeObjects = newObjects;
1317 dev->nFreeObjects+= nObjects;
1318 dev->nObjectsCreated+= nObjects;
1320 // Now add this bunch of Objects to a list for freeing up.
1322 list = YMALLOC(sizeof(yaffs_ObjectList));
1325 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1329 list->objects = newObjects;
1330 list->next = dev->allocatedObjectList;
1331 dev->allocatedObjectList = list;
1340 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1341 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1343 yaffs_Object *tn = NULL;
1345 // If there are none left make more
1346 if(!dev->freeObjects)
1348 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1351 if(dev->freeObjects)
1353 tn = dev->freeObjects;
1354 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1355 dev->nFreeObjects--;
1357 // Now sweeten it up...
1359 memset(tn,0,sizeof(yaffs_Object));
1362 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1363 INIT_LIST_HEAD(&(tn->hardLinks));
1364 INIT_LIST_HEAD(&(tn->hashLink));
1365 INIT_LIST_HEAD(&tn->siblings);
1367 // Add it to the lost and found directory.
1368 // NB Can't put root or lostNFound in lostNFound so
1369 // check if lostNFound exists first
1370 if(dev->lostNFoundDir)
1372 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1380 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1383 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1386 obj->fake = 1; // it is fake so it has no NAND presence...
1387 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1388 obj->unlinkAllowed= 0; // ... or unlink it
1391 obj->yst_mode = mode;
1393 obj->chunkId = 0; // Not a valid chunk.
1401 static void yaffs_UnhashObject(yaffs_Object *tn)
1404 yaffs_Device *dev = tn->myDev;
1407 // If it is still linked into the bucket list, free from the list
1408 if(!list_empty(&tn->hashLink))
1410 list_del_init(&tn->hashLink);
1411 bucket = yaffs_HashFunction(tn->objectId);
1412 dev->objectBucket[bucket].count--;
1418 // FreeObject frees up a Object and puts it back on the free list
1419 static void yaffs_FreeObject(yaffs_Object *tn)
1422 yaffs_Device *dev = tn->myDev;
1427 // We're still hooked up to a cached inode.
1428 // Don't delete now, but mark for later deletion
1429 tn->deferedFree = 1;
1434 yaffs_UnhashObject(tn);
1436 // Link into the free list.
1437 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1438 dev->freeObjects = tn;
1439 dev->nFreeObjects++;
1446 void yaffs_HandleDeferedFree(yaffs_Object *obj)
1448 if(obj->deferedFree)
1450 yaffs_FreeObject(obj);
1458 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1460 // Free the list of allocated Objects
1462 yaffs_ObjectList *tmp;
1464 while( dev->allocatedObjectList)
1466 tmp = dev->allocatedObjectList->next;
1467 YFREE(dev->allocatedObjectList->objects);
1468 YFREE(dev->allocatedObjectList);
1470 dev->allocatedObjectList = tmp;
1473 dev->freeObjects = NULL;
1474 dev->nFreeObjects = 0;
1477 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1481 dev->allocatedObjectList = NULL;
1482 dev->freeObjects = NULL;
1483 dev->nFreeObjects = 0;
1485 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1487 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1488 dev->objectBucket[i].count = 0;
1498 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1503 int lowest = 999999;
1506 // First let's see if we can find one that's empty.
1508 for(i = 0; i < 10 && lowest > 0; i++)
1511 x %= YAFFS_NOBJECT_BUCKETS;
1512 if(dev->objectBucket[x].count < lowest)
1514 lowest = dev->objectBucket[x].count;
1520 // If we didn't find an empty list, then try
1521 // looking a bit further for a short one
1523 for(i = 0; i < 10 && lowest > 3; i++)
1526 x %= YAFFS_NOBJECT_BUCKETS;
1527 if(dev->objectBucket[x].count < lowest)
1529 lowest = dev->objectBucket[x].count;
1538 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1540 int bucket = yaffs_FindNiceObjectBucket(dev);
1542 // Now find an object value that has not already been taken
1543 // by scanning the list.
1546 struct list_head *i;
1548 __u32 n = (__u32)bucket;
1550 //yaffs_CheckObjectHashSanity();
1555 n += YAFFS_NOBJECT_BUCKETS;
1556 if(1 ||dev->objectBucket[bucket].count > 0)
1558 list_for_each(i,&dev->objectBucket[bucket].list)
1560 // If there is already one in the list
1561 if(i && list_entry(i, yaffs_Object,hashLink)->objectId == n)
1569 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1574 static void yaffs_HashObject(yaffs_Object *in)
1576 int bucket = yaffs_HashFunction(in->objectId);
1577 yaffs_Device *dev = in->myDev;
1579 if(!list_empty(&in->hashLink))
1585 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1586 dev->objectBucket[bucket].count++;
1590 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1592 int bucket = yaffs_HashFunction(number);
1593 struct list_head *i;
1596 list_for_each(i,&dev->objectBucket[bucket].list)
1598 // Look if it is in the list
1601 in = list_entry(i, yaffs_Object,hashLink);
1602 if(in->objectId == number)
1605 // Don't tell the VFS about this one if it is defered free
1620 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1623 yaffs_Object *theObject;
1627 number = yaffs_CreateNewObjectNumber(dev);
1630 theObject = yaffs_AllocateEmptyObject(dev);
1634 theObject->fake = 0;
1635 theObject->renameAllowed = 1;
1636 theObject->unlinkAllowed = 1;
1637 theObject->objectId = number;
1638 yaffs_HashObject(theObject);
1639 theObject->variantType = type;
1640 #ifdef CONFIG_YAFFS_WINCE
1641 yfsd_WinFileTimeNow(theObject->win_atime);
1642 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1643 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1647 theObject->yst_atime = theObject->yst_mtime = theObject->yst_ctime = Y_CURRENT_TIME;
1651 case YAFFS_OBJECT_TYPE_FILE:
1652 theObject->variant.fileVariant.fileSize = 0;
1653 theObject->variant.fileVariant.scannedFileSize = 0;
1654 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; // max __u32
1655 theObject->variant.fileVariant.topLevel = 0;
1656 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1658 case YAFFS_OBJECT_TYPE_DIRECTORY:
1659 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1661 case YAFFS_OBJECT_TYPE_SYMLINK:
1662 // No action required
1664 case YAFFS_OBJECT_TYPE_HARDLINK:
1665 // No action required
1667 case YAFFS_OBJECT_TYPE_SPECIAL:
1668 // No action required
1670 case YAFFS_OBJECT_TYPE_UNKNOWN:
1671 // todo this should not happen
1679 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1681 yaffs_Object *theObject = NULL;
1685 theObject = yaffs_FindObjectByNumber(dev,number);
1690 theObject = yaffs_CreateNewObject(dev,number,type);
1697 static YCHAR *yaffs_CloneString(const YCHAR *str)
1699 YCHAR *newStr = NULL;
1703 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1704 yaffs_strcpy(newStr,str);
1712 // Mknod (create) a new object.
1713 // equivalentObject only has meaning for a hard link;
1714 // aliasString only has meaning for a sumlink.
1715 // rdev only has meaning for devices (a subset of special objects)
1716 static yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1717 yaffs_Object *parent,
1722 yaffs_Object *equivalentObject,
1723 const YCHAR *aliasString,
1728 yaffs_Device *dev = parent->myDev;
1730 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1731 if(yaffs_FindObjectByName(parent,name))
1736 in = yaffs_CreateNewObject(dev,-1,type);
1742 in->variantType = type;
1744 in->yst_mode = mode;
1746 #ifdef CONFIG_YAFFS_WINCE
1747 yfsd_WinFileTimeNow(in->win_atime);
1748 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1749 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1752 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1754 in->yst_rdev = rdev;
1758 in->nDataChunks = 0;
1760 yaffs_SetObjectName(in,name);
1763 yaffs_AddObjectToDirectory(parent,in);
1765 in->myDev = parent->myDev;
1770 case YAFFS_OBJECT_TYPE_SYMLINK:
1771 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1773 case YAFFS_OBJECT_TYPE_HARDLINK:
1774 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1775 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1776 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1778 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1779 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1780 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1781 case YAFFS_OBJECT_TYPE_UNKNOWN:
1785 if(/*yaffs_GetNumberOfFreeChunks(dev) <= 0 || */
1786 yaffs_UpdateObjectHeader(in,name,0,0,0) < 0)
1788 // Could not create the object header, fail the creation
1789 yaffs_DestroyObject(in);
1798 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid)
1800 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1803 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid)
1805 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1808 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1810 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL,parent,name,mode,uid,gid,NULL,NULL,rdev);
1813 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const YCHAR *name, __u32 mode, __u32 uid, __u32 gid,const YCHAR *alias)
1815 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1818 // NB yaffs_Link returns the object id of the equivalent object.
1819 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name, yaffs_Object *equivalentObject)
1821 // Get the real object in case we were fed a hard link as an equivalent object
1822 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1824 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1826 return equivalentObject;
1836 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const YCHAR *newName,int force,int shadows)
1841 yaffs_Object * existingTarget;
1845 newDir = obj->parent; // use the old directory
1848 if(newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1850 T(YAFFS_TRACE_ALWAYS,(TSTR("tragendy: yaffs_ChangeObjectName: newDir is not a directory"TENDSTR)));
1854 // TODO: Do we need this different handling for YAFFS2 and YAFFS1??
1855 if(obj->myDev->isYaffs2)
1857 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1861 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1864 deleteOp = (newDir == obj->myDev->deletedDir);
1866 existingTarget = yaffs_FindObjectByName(newDir,newName);
1868 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1869 // duplicate names are allowed.
1870 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1876 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1878 yaffs_SetObjectName(obj,newName);
1881 yaffs_AddObjectToDirectory(newDir,obj);
1883 if(unlinkOp) obj->unlinked = 1;
1885 // If it is a deletion then we mark it as a shrink for gc purposes.
1886 if(yaffs_UpdateObjectHeader(obj,newName,0,deleteOp,shadows) >= 0)
1897 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName, yaffs_Object *newDir, const YCHAR *newName)
1900 yaffs_Object *existingTarget;
1903 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1904 // Special case for case insemsitive systems (eg. WinCE).
1905 // While look-up is case insensitive, the name isn't.
1906 // THerefore we might want to change x.txt to X.txt
1907 if(oldDir == newDir && yaffs_strcmp(oldName,newName) == 0)
1913 obj = yaffs_FindObjectByName(oldDir,oldName);
1915 if(obj && obj->renameAllowed)
1918 // Now do the handling for an existing target, if there is one
1920 existingTarget = yaffs_FindObjectByName(newDir,newName);
1921 if(existingTarget &&
1922 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1923 !list_empty(&existingTarget->variant.directoryVariant.children))
1925 // There is a target that is a non-empty directory, so we have to fail
1926 return YAFFS_FAIL; // EEXIST or ENOTEMPTY
1928 else if(existingTarget)
1930 // Nuke the target first, using shadowing
1931 yaffs_ChangeObjectName(obj,newDir,newName,force,existingTarget->objectId);
1932 yaffs_Unlink(newDir,newName);
1936 return yaffs_ChangeObjectName(obj,newDir,newName,force,0);
1944 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1946 // Scan the buckets and check that the lists
1947 // have as many members as the count says there are
1950 struct list_head *j;
1953 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1957 list_for_each(j,&dev->objectBucket[bucket].list)
1962 if(countEm != dev->objectBucket[bucket].count)
1964 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1973 void yaffs_ObjectTest(yaffs_Device *dev)
1975 yaffs_Object *in[1000];
1977 yaffs_Object *inold[1000];
1981 memset(in,0,1000*sizeof(yaffs_Object *));
1982 memset(inold,0,1000*sizeof(yaffs_Object *));
1984 yaffs_CheckObjectHashSanity(dev);
1986 for(j = 0; j < 10; j++)
1990 for(i = 0; i < 1000; i++)
1992 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1995 YINFO("No more inodes");
1999 inNo[i] = in[i]->objectId;
2003 for(i = 0; i < 1000; i++)
2005 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
2007 //T(("Differnce in look up test\n"));
2011 // T(("Look up ok\n"));
2015 yaffs_CheckObjectHashSanity(dev);
2017 for(i = 0; i < 1000; i+=3)
2019 yaffs_FreeObject(in[i]);
2024 yaffs_CheckObjectHashSanity(dev);
2031 /////////////////////////// Block Management and Page Allocation ///////////////////
2034 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
2036 dev->allocationBlock = -1; // force it to get a new one
2037 //Todo we're assuming the malloc will pass.
2038 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2039 // Set up dynamic blockinfo stuff.
2040 dev->chunkBitmapStride = (dev->nChunksPerBlock+7)/8;
2041 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2042 if(dev->blockInfo && dev->chunkBits)
2044 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
2045 memset(dev->chunkBits,0,dev->chunkBitmapStride * nBlocks);
2053 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2055 YFREE(dev->blockInfo);
2056 dev->blockInfo = NULL;
2057 YFREE(dev->chunkBits);
2058 dev->chunkBits = NULL;
2062 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev, yaffs_BlockInfo *bi)
2068 if(!dev->isYaffs2) return 1; // disqualification only applies to yaffs2.
2070 if(!bi->hasShrinkHeader) return 1; // can gc
2073 // Find the oldest dirty sequence number if we don't know it and save it
2074 // so we don't have to keep recomputing it.
2075 if(!dev->oldestDirtySequence)
2077 seq = dev->sequenceNumber;
2079 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++)
2081 b = yaffs_GetBlockInfo(dev,i);
2082 if(b->blockState == YAFFS_BLOCK_STATE_FULL &&
2083 (b->pagesInUse - b->softDeletions )< dev->nChunksPerBlock &&
2084 b->sequenceNumber < seq)
2086 seq = b->sequenceNumber;
2089 dev->oldestDirtySequence = seq;
2093 // Can't do gc of this block if there are any blocks older than this one that have
2095 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2102 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
2103 // for garbage collection.
2108 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,int aggressive)
2111 int b = dev->currentDirtyChecker;
2117 yaffs_BlockInfo *bi;
2118 static int nonAggressiveSkip = 0;
2120 // If we're doing aggressive GC then we are happy to take a less-dirty block, and
2122 // else (we're doing a leasurely gc), then we only bother to do this if the
2123 // block has only a few pages in use.
2126 nonAggressiveSkip--;
2128 if(!aggressive &&(nonAggressiveSkip > 0))
2133 pagesInUse = (aggressive)? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2137 iterations = dev->internalEndBlock - dev->internalStartBlock + 1;
2141 iterations = dev->internalEndBlock - dev->internalStartBlock + 1;
2142 iterations = iterations / 16;
2143 if(iterations > 200)
2149 for(i = 0; i <= iterations && pagesInUse > 0 ; i++)
2152 if ( b < dev->internalStartBlock || b > dev->internalEndBlock)
2154 b = dev->internalStartBlock;
2157 if(b < dev->internalStartBlock || b > dev->internalEndBlock)
2159 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
2163 bi = yaffs_GetBlockInfo(dev,b);
2165 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2166 (bi->pagesInUse - bi->softDeletions )< pagesInUse &&
2167 yaffs_BlockNotDisqualifiedFromGC(dev,bi))
2170 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2174 dev->currentDirtyChecker = b;
2178 T(YAFFS_TRACE_GC,(TSTR("GC Selected block %d with %d free" TENDSTR),dirtiest,dev->nChunksPerBlock - pagesInUse));
2181 dev->oldestDirtySequence = 0; // clear this
2185 nonAggressiveSkip = 4;
2192 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
2194 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
2198 // If the block is still healthy erase it and mark as clean.
2199 // If the block has had a data failure, then retire it.
2200 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2202 if(!bi->needsRetiring)
2204 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
2207 dev->nErasureFailures++;
2208 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
2212 if(erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE))
2215 for(i = 0; i < dev->nChunksPerBlock; i++)
2217 if(!yaffs_CheckChunkErased(dev,blockNo * dev->nChunksPerBlock + i))
2219 T(YAFFS_TRACE_ERROR,(TSTR(">>Block %d erasure supposedly OK, but chunk %d not erased" TENDSTR),blockNo,i));
2227 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2228 dev->nErasedBlocks++;
2230 bi->softDeletions = 0;
2231 bi->hasShrinkHeader=0;
2232 yaffs_ClearChunkBits(dev,blockNo);
2234 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
2238 dev->nFreeChunks -= dev->nChunksPerBlock; // We lost a block of free space
2240 yaffs_RetireBlock(dev,blockNo);
2241 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
2246 static void yaffs_DumpBlockStats(yaffs_Device *dev)
2249 yaffs_BlockInfo *bi;
2251 for(i= dev->internalStartBlock; i <=dev->internalEndBlock; i++)
2253 bi = yaffs_GetBlockInfo(dev,i);
2254 T(YAFFS_TRACE_ALLOCATE,(TSTR("%3d state %d shrink %d inuse %d/%d seq %d pages"),i,
2255 bi->blockState,bi->hasShrinkHeader,bi->pagesInUse,bi->softDeletions,bi->sequenceNumber));
2257 for(j = 0; j < dev->nChunksPerBlock; j++)
2259 if(yaffs_CheckChunkBit(dev,i,j))
2261 T(YAFFS_TRACE_ALLOCATE,(TSTR(" %d"),j));
2265 T(YAFFS_TRACE_ALLOCATE,(TSTR(" " TENDSTR)));
2272 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2276 yaffs_BlockInfo *bi;
2281 if(j < 0 || j > 100)
2284 yaffs_DumpBlockStats(dev);
2289 if(dev->nErasedBlocks < 1)
2291 // Hoosterman we've got a problem.
2292 // Can't get space to gc
2293 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2298 // Find an empty block.
2300 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++)
2302 dev->allocationBlockFinder++;
2303 if(dev->allocationBlockFinder < dev->internalStartBlock || dev->allocationBlockFinder> dev->internalEndBlock)
2305 dev->allocationBlockFinder = dev->internalStartBlock;
2308 bi = yaffs_GetBlockInfo(dev,dev->allocationBlockFinder);
2310 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
2312 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2313 dev->sequenceNumber++;
2314 bi->sequenceNumber = dev->sequenceNumber;
2315 dev->nErasedBlocks--;
2316 T(YAFFS_TRACE_ALLOCATE,(TSTR("Allocated block %d, seq %d, %d left" TENDSTR),dev->allocationBlockFinder,dev->sequenceNumber, dev->nErasedBlocks));
2317 return dev->allocationBlockFinder;
2322 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs tragedy: no more eraased blocks, but there should have been %d" TENDSTR),dev->nErasedBlocks));
2332 // To determine if we have enough space we just look at the
2333 // number of erased blocks.
2335 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2337 int reservedChunks = (dev->nReservedBlocks * dev->nChunksPerBlock);
2338 return (dev->nFreeChunks > reservedChunks);
2342 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
2345 yaffs_BlockInfo *bi;
2347 if(dev->allocationBlock < 0)
2349 // Get next block to allocate off
2350 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2351 dev->allocationPage = 0;
2354 if(!useReserve && !yaffs_CheckSpaceForAllocation(dev))
2356 // Not enough space to allocate unless we're allowed to use the reserve.
2360 if(dev->nErasedBlocks < dev->nReservedBlocks && dev->allocationPage == 0)
2362 T(YAFFS_TRACE_ALLOCATE,(TSTR("Allocating reserve" TENDSTR)));
2366 // Next page please....
2367 if(dev->allocationBlock >= 0)
2369 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
2371 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2372 dev->allocationPage;
2374 yaffs_SetChunkBit(dev,dev->allocationBlock,dev->allocationPage);
2376 dev->allocationPage++;
2380 // If the block is full set the state to full
2381 if(dev->allocationPage >= dev->nChunksPerBlock)
2383 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2384 dev->allocationBlock = -1;
2391 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2399 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2403 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2405 if(dev->allocationBlock> 0)
2407 n += (dev->nChunksPerBlock - dev->allocationPage);
2414 static int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
2420 int retVal = YAFFS_OK;
2424 int chunksBefore = yaffs_GetErasedChunks(dev);
2427 yaffs_ExtendedTags tags;
2429 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
2431 yaffs_Object *object;
2433 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2435 T(YAFFS_TRACE_TRACING,(TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR),block,bi->pagesInUse,bi->hasShrinkHeader));
2436 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
2438 //yaffs_VerifyFreeChunks(dev);
2440 bi->hasShrinkHeader = 0; // clear the flag so that the block can erase
2442 dev->nFreeChunks -= bi->softDeletions; // Take off the number of soft deleted entries because
2443 // they're going to get really deleted during GC.
2447 if(!yaffs_StillSomeChunkBits(dev,block))
2449 T(YAFFS_TRACE_TRACING,(TSTR("Collecting block %d that has no chunks in use" TENDSTR),block));
2450 yaffs_BlockBecameDirty(dev,block);
2455 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
2457 for(chunkInBlock = 0,oldChunk = block * dev->nChunksPerBlock;
2458 chunkInBlock < dev->nChunksPerBlock && yaffs_StillSomeChunkBits(dev,block);
2459 chunkInBlock++, oldChunk++ )
2461 if(yaffs_CheckChunkBit(dev,block,chunkInBlock))
2464 // This page is in use and might need to be copied off
2468 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
2470 yaffs_InitialiseTags(&tags);
2472 yaffs_ReadChunkWithTagsFromNAND(dev,oldChunk,buffer, &tags);
2474 object = yaffs_FindObjectByNumber(dev,tags.objectId);
2476 T(YAFFS_TRACE_GC_DETAIL,(TSTR("Collecting page %d, %d %d %d " TENDSTR),chunkInBlock,tags.objectId,tags.chunkId,tags.byteCount));
2480 T(YAFFS_TRACE_ERROR,(TSTR("page %d in gc has no object " TENDSTR),oldChunk));
2483 if(object && object->deleted && tags.chunkId != 0)
2485 // Data chunk in a deleted file, throw it away
2486 // It's a soft deleted data chunk,
2487 // No need to copy this, just forget about it and fix up the
2490 //yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
2491 object->nDataChunks--;
2493 if(object->nDataChunks <= 0)
2495 // remeber to clean up the object
2496 dev->gcCleanupList[cleanups] = tags.objectId;
2501 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
2503 // Deleted object header with no data chunks.
2504 // Can be discarded and the file deleted.
2505 object->chunkId = 0;
2506 yaffs_FreeTnode(object->myDev,object->variant.fileVariant.top);
2507 object->variant.fileVariant.top = NULL;
2508 yaffs_DoGenericObjectDeletion(object);
2513 // It's either a data chunk in a live file or
2514 // an ObjectHeader, so we're interested in it.
2515 // NB Need to keep the ObjectHeaders of deleted files
2516 // until the whole file has been deleted off
2517 tags.serialNumber++;
2521 newChunk = yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags,1);
2525 retVal = YAFFS_FAIL;
2530 // Ok, now fix up the Tnodes etc.
2532 if(tags.chunkId == 0)
2535 object->chunkId = newChunk;
2536 object->serial = tags.serialNumber;
2540 // It's a data chunk
2541 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2546 yaffs_DeleteChunk(dev,oldChunk,markNAND,__LINE__);
2551 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
2553 //yaffs_VerifyFreeChunks(dev);
2555 // Do any required cleanups
2556 for(i = 0; i < cleanups; i++)
2558 // Time to delete the file too
2559 object = yaffs_FindObjectByNumber(dev,dev->gcCleanupList[i]);
2562 yaffs_FreeTnode(dev,object->variant.fileVariant.top);
2563 object->variant.fileVariant.top = NULL;
2564 T(YAFFS_TRACE_GC,(TSTR("yaffs: About to finally delete object %d" TENDSTR),object->objectId));
2565 yaffs_DoGenericObjectDeletion(object);
2572 if(chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev)))
2574 T(YAFFS_TRACE_GC,(TSTR("gc did not increase free chunks before %d after %d" TENDSTR),chunksBefore,chunksAfter));
2580 //yaffs_VerifyFreeChunks(dev);
2586 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2588 // find a file to delete
2589 struct list_head *i;
2593 //Scan the unlinked files looking for one to delete
2594 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2598 l = list_entry(i, yaffs_Object,siblings);
2609 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2611 // This does background deletion on unlinked files.. only deleted ones.
2612 // If we don't have a file we're working on then find one
2613 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2615 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2618 // OK, we're working on a file...
2619 if(dev->unlinkedDeletion)
2621 yaffs_Object *obj = dev->unlinkedDeletion;
2623 int limit; // Number of chunks to delete in a file.
2624 // NB this can be exceeded, but not by much.
2628 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2630 if(obj->nDataChunks == 0)
2632 // Done all the deleting of data chunks.
2633 // Now dump the header and clean up
2634 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2635 obj->variant.fileVariant.top = NULL;
2636 yaffs_DoGenericObjectDeletion(obj);
2637 dev->nDeletedFiles--;
2638 dev->nUnlinkedFiles--;
2639 dev->nBackgroundDeletions++;
2640 dev->unlinkedDeletion = NULL;
2649 // New garbage collector
2650 // If we're very low on erased blocks then we do aggressive garbage collection
2651 // otherwise we do "leasurely" garbage collection.
2652 // Aggressive gc looks further (whole array) and will accept dirtier blocks.
2653 // Passive gc only inspects smaller areas and will only accept cleaner blocks.
2655 // The idea is to help clear out space in a more spread-out manner.
2656 // Dunno if it really does anything useful.
2658 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2662 int gcOk = YAFFS_OK;
2665 //yaffs_VerifyFreeChunks(dev);
2669 // Bail out so we don't get recursive gc
2673 // This loop should pass the first time.
2674 // We'll only see looping here if the erase of the collected block fails.
2678 if(dev->nErasedBlocks < dev->nReservedBlocks)
2680 // We need a block soon...
2685 // We're in no hurry
2689 block = yaffs_FindBlockForGarbageCollection(dev,aggressive);
2693 dev->garbageCollections++;
2696 dev->passiveGarbageCollections++;
2699 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),dev->nErasedBlocks,aggressive));
2701 gcOk = yaffs_GarbageCollectBlock(dev,block);
2704 if(dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0)
2706 T(YAFFS_TRACE_GC,(TSTR("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d" TENDSTR),dev->nErasedBlocks,maxTries,block));
2708 } while((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0) && (maxTries < 2));
2710 return aggressive ? gcOk: YAFFS_OK;
2714 //////////////////////////// TAGS ///////////////////////////////////////
2720 void yaffs_CalcTagsECC(yaffs_Tags *tags)
2724 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
2731 for(i = 0; i < 8; i++)
2733 for(j = 1; j &0xff; j<<=1)
2748 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
2750 unsigned ecc = tags->ecc;
2752 yaffs_CalcTagsECC(tags);
2756 if(ecc && ecc <= 64)
2758 // TODO: Handle the failure better. Retire?
2759 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
2763 b[ecc / 8] ^= (1 << (ecc & 7));
2765 // Now recvalc the ecc
2766 yaffs_CalcTagsECC(tags);
2768 return 1; // recovered error
2772 // Wierd ecc failure value
2773 // TODO Need to do somethiong here
2774 return -1; //unrecovered error
2780 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2782 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2784 yaffs_CalcTagsECC(tagsPtr);
2786 sparePtr->tagByte0 = tu->asBytes[0];
2787 sparePtr->tagByte1 = tu->asBytes[1];
2788 sparePtr->tagByte2 = tu->asBytes[2];
2789 sparePtr->tagByte3 = tu->asBytes[3];
2790 sparePtr->tagByte4 = tu->asBytes[4];
2791 sparePtr->tagByte5 = tu->asBytes[5];
2792 sparePtr->tagByte6 = tu->asBytes[6];
2793 sparePtr->tagByte7 = tu->asBytes[7];
2796 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2798 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2801 tu->asBytes[0]= sparePtr->tagByte0;
2802 tu->asBytes[1]= sparePtr->tagByte1;
2803 tu->asBytes[2]= sparePtr->tagByte2;
2804 tu->asBytes[3]= sparePtr->tagByte3;
2805 tu->asBytes[4]= sparePtr->tagByte4;
2806 tu->asBytes[5]= sparePtr->tagByte5;
2807 tu->asBytes[6]= sparePtr->tagByte6;
2808 tu->asBytes[7]= sparePtr->tagByte7;
2810 result = yaffs_CheckECCOnTags(tagsPtr);
2813 dev->tagsEccFixed++;
2817 dev->tagsEccUnfixed++;
2821 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2823 memset(spare,0xFF,sizeof(yaffs_Spare));
2829 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_ExtendedTags *tags, int useReserve)
2831 // NB There must be tags, data is optional
2832 // If there is data, then an ECC is calculated on it.
2841 //yaffs_SpareInitialise(&spare);
2843 //if(!dev->useNANDECC && buffer)
2845 // yaffs_CalcECC(buffer,&spare);
2848 //yaffs_LoadTagsIntoSpare(&spare,tags);
2850 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2855 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId, int chunkInObject)
2857 return ( tags->chunkId == chunkInObject &&
2858 tags->objectId == objectId &&
2859 !tags->chunkDeleted) ? 1 : 0;
2863 /////////////////////////////////////////////////////////////////////////////////////////////////////////
2866 static int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_ExtendedTags *tags)
2868 //Get the Tnode, then get the level 0 offset chunk offset
2871 yaffs_ExtendedTags localTags;
2874 yaffs_Device *dev = in->myDev;
2879 // Passed a NULL, so use our own tags space
2883 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2887 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2889 retVal = yaffs_FindChunkInGroup(dev,theChunk,tags,in->objectId,chunkInInode);
2894 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_ExtendedTags *tags)
2896 //Get the Tnode, then get the level 0 offset chunk offset
2899 yaffs_ExtendedTags localTags;
2901 yaffs_Device *dev = in->myDev;
2906 // Passed a NULL, so use our own tags space
2910 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2915 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2917 retVal = yaffs_FindChunkInGroup(dev,theChunk,tags,in->objectId,chunkInInode);
2919 // Delete the entry in the filestructure (if found)
2922 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2927 //T(("No level 0 found for %d\n", chunkInInode));
2932 //T(("Could not find %d to delete\n",chunkInInode));
2938 #ifdef YAFFS_PARANOID
2940 static int yaffs_CheckFileSanity(yaffs_Object *in)
2948 yaffs_Tags localTags;
2949 yaffs_Tags *tags = &localTags;
2954 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2956 //T(("Object not a file\n"));
2960 objId = in->objectId;
2961 fSize = in->variant.fileVariant.fileSize;
2962 nChunks = (fSize + in->myDev->nBytesPerChunk -1)/in->myDev->nBytesPerChunk;
2964 for(chunk = 1; chunk <= nChunks; chunk++)
2966 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2971 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2973 if(yaffs_CheckChunkBits(dev,theChunk/dev->nChunksPerBlock,theChunk%dev->nChunksPerBlock))
2977 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2978 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2986 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2987 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2996 //T(("No level 0 found for %d\n", chunk));
3000 return failed ? YAFFS_FAIL : YAFFS_OK;
3005 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
3007 // NB inScan is zero unless scanning. For forward scanning, inScan is > 0; for backward scanning inScan is < 0
3009 yaffs_Device *dev = in->myDev;
3011 yaffs_ExtendedTags existingTags;
3012 yaffs_ExtendedTags newTags;
3013 unsigned existingSerial, newSerial;
3015 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3017 // Just ignore an attempt at putting a chunk into a non-file during scanning
3018 // If it is not during Scanning then something went wrong!
3021 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy:attempt to put data chunk into a non-file" TENDSTR)));
3025 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
3029 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
3035 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
3039 // If we're scanning then we need to test for duplicates
3040 // NB This does not need to be efficient since it should only ever
3041 // happen when the power fails during a write, then only one
3042 // chunk should ever be affected.
3044 // Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3045 // Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3049 if(existingChunk != 0)
3051 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
3052 // thus we have to do a FindChunkInFile to get the real chunk id.
3054 // We have a duplicate now we need to decide which one to use:
3056 // Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3057 // Forward scanning YAFFS2: The new one is what we use, dump the old one.
3058 // YAFFS1: Get both sets of tags and compare serial numbers.
3064 // Only do this for forward scanning
3065 yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND, NULL,&newTags);
3069 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
3072 if(existingChunk <=0)
3074 //Hoosterman - how did this happen?
3076 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: existing chunk < 0 in scan" TENDSTR)));
3081 // NB The deleted flags should be false, otherwise the chunks will
3082 // not be loaded during a scan
3084 newSerial = newTags.serialNumber;
3085 existingSerial = existingTags.serialNumber;
3088 ( in->myDev->isYaffs2 ||
3089 existingChunk <= 0 ||
3090 ((existingSerial+1) & 3) == newSerial))
3092 // Forward scanning.
3094 // Delete the old one and drop through to update the tnode
3095 yaffs_DeleteChunk(dev,existingChunk,1,__LINE__);
3099 // Backward scanning or we want to use the existing one
3101 // Delete the new one and return early so that the tnode isn't changed
3102 yaffs_DeleteChunk(dev,chunkInNAND,1,__LINE__);
3109 if(existingChunk == 0)
3114 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
3121 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
3123 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
3125 if(chunkInNAND >= 0)
3127 return yaffs_ReadChunkWithTagsFromNAND(in->myDev,chunkInNAND,buffer,NULL);
3131 T(YAFFS_TRACE_NANDACCESS,(TSTR("Chunk %d not found zero instead" TENDSTR),chunkInNAND));
3133 memset(buffer,0,in->myDev->nBytesPerChunk); // get sane data if you read a hole
3140 void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId,int markNAND,int lyn)
3144 yaffs_ExtendedTags tags;
3145 yaffs_BlockInfo *bi;
3147 if(chunkId <= 0) return;
3150 block = chunkId / dev->nChunksPerBlock;
3151 page = chunkId % dev->nChunksPerBlock;
3153 bi = yaffs_GetBlockInfo(dev,block);
3155 T(YAFFS_TRACE_DELETION,(TSTR("line %d delete of chunk %d" TENDSTR),lyn,chunkId));
3158 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
3161 // yaffs_SpareInitialise(&spare);
3163 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
3165 //read data before write, to ensure correct ecc
3166 //if we're using MTD verification under Linux
3167 yaffs_ReadChunkFromNAND(dev,chunkId,NULL,&spare,0);
3170 yaffs_InitialiseTags(&tags);
3172 tags.chunkDeleted = 1;
3175 yaffs_WriteChunkWithTagsToNAND(dev,chunkId,NULL,&tags);
3176 yaffs_HandleUpdateChunk(dev,chunkId,&tags);
3180 dev->nUnmarkedDeletions++;
3184 // Pull out of the management area.
3185 // If the whole block became dirty, this will kick off an erasure.
3186 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3187 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3188 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3189 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)
3193 yaffs_ClearChunkBit(dev,block,page);
3197 if(bi->pagesInUse == 0 &&
3198 !bi->hasShrinkHeader &&
3199 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3200 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING)
3202 yaffs_BlockBecameDirty(dev,block);
3208 // T(("Bad news deleting chunk %d\n",chunkId));
3216 static int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
3218 // Find old chunk Need to do this to get serial number
3219 // Write new one and patch into tree.
3220 // Invalidate old tags.
3223 yaffs_ExtendedTags prevTags;
3226 yaffs_ExtendedTags newTags;
3228 yaffs_Device *dev = in->myDev;
3230 yaffs_CheckGarbageCollection(dev);
3232 // Get the previous chunk at this location in the file if it exists
3233 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
3236 yaffs_InitialiseTags(&newTags);
3238 newTags.chunkId = chunkInInode;
3239 newTags.objectId = in->objectId;
3240 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3241 newTags.byteCount = nBytes;
3243 // yaffs_CalcTagsECC(&newTags);
3245 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
3249 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
3252 if(prevChunkId >= 0)
3254 yaffs_DeleteChunk(dev,prevChunkId,1,__LINE__);
3258 yaffs_CheckFileSanity(in);
3269 // UpdateObjectHeader updates the header on NAND for an object.
3270 // If name is not NULL, then that new name is used.
3272 int yaffs_UpdateObjectHeader(yaffs_Object *in,const YCHAR *name, int force,int isShrink,int shadows)
3275 yaffs_BlockInfo *bi;
3277 yaffs_Device *dev = in->myDev;
3283 yaffs_ExtendedTags newTags;
3285 __u8 *buffer = NULL;
3286 YCHAR oldName[YAFFS_MAX_NAME_LENGTH+1];
3288 // __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
3290 yaffs_ObjectHeader *oh = NULL;
3291 // yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
3294 if(!in->fake || force)
3297 yaffs_CheckGarbageCollection(dev);
3299 buffer = yaffs_GetTempBuffer(in->myDev,__LINE__);
3300 oh = (yaffs_ObjectHeader *)buffer;
3302 prevChunkId = in->chunkId;
3304 if(prevChunkId >= 0)
3306 yaffs_ReadChunkWithTagsFromNAND(dev,prevChunkId,buffer,NULL);
3307 memcpy(oldName,oh->name,sizeof(oh->name));
3310 memset(buffer,0xFF,dev->nBytesPerChunk);
3313 oh->type = in->variantType;
3315 oh->yst_mode = in->yst_mode;
3318 oh->shadowsObject = shadows;
3320 #ifdef CONFIG_YAFFS_WINCE
3321 oh->win_atime[0] = in->win_atime[0];
3322 oh->win_ctime[0] = in->win_ctime[0];
3323 oh->win_mtime[0] = in->win_mtime[0];
3324 oh->win_atime[1] = in->win_atime[1];
3325 oh->win_ctime[1] = in->win_ctime[1];
3326 oh->win_mtime[1] = in->win_mtime[1];
3328 oh->yst_uid = in->yst_uid;
3329 oh->yst_gid = in->yst_gid;
3330 oh->yst_atime = in->yst_atime;
3331 oh->yst_mtime = in->yst_mtime;
3332 oh->yst_ctime = in->yst_ctime;
3333 oh->yst_rdev = in->yst_rdev;
3337 oh->parentObjectId = in->parent->objectId;
3341 oh->parentObjectId = 0;
3344 //oh->sum = in->sum;
3347 memset(oh->name,0,sizeof(oh->name));
3348 yaffs_strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
3350 else if(prevChunkId)
3352 memcpy(oh->name, oldName,sizeof(oh->name));
3356 memset(oh->name,0,sizeof(oh->name));
3359 oh->isShrink = isShrink;
3361 switch(in->variantType)
3363 case YAFFS_OBJECT_TYPE_UNKNOWN:
3364 // Should not happen
3366 case YAFFS_OBJECT_TYPE_FILE:
3367 oh->fileSize = (oh->parentObjectId == YAFFS_OBJECTID_DELETED ||
3368 oh->parentObjectId == YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.fileVariant.fileSize;
3370 case YAFFS_OBJECT_TYPE_HARDLINK:
3371 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
3373 case YAFFS_OBJECT_TYPE_SPECIAL:
3376 case YAFFS_OBJECT_TYPE_DIRECTORY:
3379 case YAFFS_OBJECT_TYPE_SYMLINK:
3380 yaffs_strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
3381 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3386 yaffs_InitialiseTags(&newTags);
3388 newTags.chunkId = 0;
3389 newTags.objectId = in->objectId;
3390 newTags.serialNumber = in->serial;
3392 // Add extra info for file header
3394 newTags.extraHeaderInfoAvailable = 1;
3395 newTags.extraParentObjectId = oh->parentObjectId;
3396 newTags.extraFileLength = oh->fileSize;
3397 newTags.extraIsShrinkHeader = oh->isShrink;
3398 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3399 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3400 newTags.extraObjectType = in->variantType;
3402 // Create new chunk in NAND
3403 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags, (prevChunkId >= 0) ? 1 : 0 );
3408 in->chunkId = newChunkId;
3410 if(prevChunkId >= 0)
3412 yaffs_DeleteChunk(dev,prevChunkId,1,__LINE__);
3417 // If this was a shrink, then mark the block that the chunk lives on
3420 bi = yaffs_GetBlockInfo(in->myDev,newChunkId / in->myDev->nChunksPerBlock);
3421 bi->hasShrinkHeader = 1;
3426 retVal = newChunkId;
3431 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
3437 /////////////////////// Short Operations Cache ////////////////////////////////
3438 // In many siturations where there is no high level buffering (eg WinCE) a lot of
3439 // reads might be short sequential reads, and a lot of writes may be short
3440 // sequential writes. eg. scanning/writing a jpeg file.
3441 // In these cases, a short read/write cache can provide a huge perfomance benefit
3442 // with dumb-as-a-rock code.
3443 // There are a limited number (~10) of cache chunks per device so that we don't
3444 // need a very intelligent search.
3450 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3452 yaffs_Device *dev = obj->myDev;
3453 int lowest = -99; // Stop compiler whining.
3455 yaffs_ChunkCache *cache;
3456 int chunkWritten = 0;
3458 int nCaches = obj->myDev->nShortOpCaches;
3465 // Find the dirty cache for this object with the lowest chunk id.
3466 for(i = 0; i < nCaches; i++)
3468 if(dev->srCache[i].object == obj &&
3469 dev->srCache[i].dirty)
3471 if(!cache || dev->srCache[i].chunkId < lowest)
3473 cache = &dev->srCache[i];
3474 lowest = cache->chunkId;
3479 if(cache && !cache->locked)
3481 //Write it out and free it up
3484 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
3486 if(nBytes > YAFFS_BYTES_PER_CHUNK)
3488 nBytes= YAFFS_BYTES_PER_CHUNK;
3491 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3497 cache->object = NULL;
3500 } while(cache && chunkWritten > 0);
3504 //Hoosterman, disk full while writing cache out.
3505 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3513 // Grab us a chunk for use.
3514 // First look for an empty one.
3515 // Then look for the least recently used non-dirty one.
3516 // Then look for the least recently used dirty one...., flush and look again.
3517 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3523 if(dev->nShortOpCaches > 0)
3525 for(i = 0; i < dev->nShortOpCaches; i++)
3527 if(!dev->srCache[i].object)
3529 //T(("Grabbing empty %d\n",i));
3531 //printf("Grabbing empty %d\n",i);
3533 return &dev->srCache[i];
3540 usage = 0; // just to stop the compiler grizzling
3542 for(i = 0; i < dev->nShortOpCaches; i++)
3544 if(!dev->srCache[i].dirty &&
3545 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
3548 usage = dev->srCache[i].lastUse;
3553 //T(("Grabbing non-empty %d\n",theOne));
3555 //if(theOne >= 0) printf("Grabbed non-empty cache %d\n",theOne);
3557 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3567 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3569 yaffs_ChunkCache *cache;
3570 yaffs_Object *theObj;
3575 if(dev->nShortOpCaches > 0)
3577 // Try find a non-dirty one...
3579 cache = yaffs_GrabChunkCacheWorker(dev);
3583 // They were all dirty, find the last recently used object and flush
3584 // its cache, then find again.
3585 // NB what's here is not very accurate, we actually flush the object
3586 // the last recently used page.
3588 // With locking we can't assume we can use entry zero
3596 for(i = 0; i < dev->nShortOpCaches; i++)
3598 if( dev->srCache[i].object &&
3599 !dev->srCache[i].locked &&
3600 (dev->srCache[i].lastUse < usage || !cache))
3602 usage = dev->srCache[i].lastUse;
3603 theObj = dev->srCache[i].object;
3604 cache = &dev->srCache[i];
3609 if(!cache || cache->dirty)
3613 yaffs_FlushFilesChunkCache(theObj);
3616 cache = yaffs_GrabChunkCacheWorker(dev);
3620 //printf(" pushout %d\n",pushout);
3632 // Find a cached chunk
3633 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
3635 yaffs_Device *dev = obj->myDev;
3637 if(dev->nShortOpCaches > 0)
3639 for(i = 0; i < dev->nShortOpCaches; i++)
3641 if(dev->srCache[i].object == obj &&
3642 dev->srCache[i].chunkId == chunkId)
3646 return &dev->srCache[i];
3653 // Mark the chunk for the least recently used algorithym
3654 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
3657 if(dev->nShortOpCaches > 0)
3659 if( dev->srLastUse < 0 ||
3660 dev->srLastUse > 100000000)
3662 // Reset the cache usages
3664 for(i = 1; i < dev->nShortOpCaches; i++)
3666 dev->srCache[i].lastUse = 0;
3673 cache->lastUse = dev->srLastUse;
3682 // Invalidate a single cache page.
3683 // Do this when a whole page gets written,
3684 // ie the short cache for this page is no longer valid.
3685 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3687 if(object->myDev->nShortOpCaches > 0)
3689 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
3693 cache->object = NULL;
3699 // Invalidate all the cache pages associated with this object
3700 // Do this whenever ther file is deleted or resized.
3701 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3704 yaffs_Device *dev = in->myDev;
3706 if(dev->nShortOpCaches > 0)
3708 // Now invalidate it.
3709 for(i = 0; i < dev->nShortOpCaches; i++)
3711 if(dev->srCache[i].object == in)
3713 dev->srCache[i].object = NULL;
3723 ///////////////////////// File read/write ///////////////////////////////
3724 // Read and write have very similar structures.
3725 // In general the read/write has three parts to it
3726 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3727 // * Some complete chunks
3728 // * An incomplete chunk to end off with
3730 // Curve-balls: the first chunk might also be the last chunk.
3732 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3741 yaffs_ChunkCache *cache;
3749 chunk = offset / dev->nBytesPerChunk + 1; // The first chunk is 1
3750 start = offset % dev->nBytesPerChunk;
3752 // OK now check for the curveball where the start and end are in
3754 if( (start + n) < dev->nBytesPerChunk)
3760 nToCopy = dev->nBytesPerChunk - start;
3763 cache = yaffs_FindChunkCache(in,chunk);
3765 // If the chunk is already in the cache or it is less than a whole chunk
3766 // then use the cache (if there is caching)
3767 // else bypass the cache.
3768 if( cache || nToCopy != dev->nBytesPerChunk)
3770 if(dev->nShortOpCaches > 0)
3773 // If we can't find the data in the cache, then load it up.
3777 cache = yaffs_GrabChunkCache(in->myDev);
3779 cache->chunkId = chunk;
3782 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3786 yaffs_UseChunkCache(dev,cache,0);
3790 #ifdef CONFIG_YAFFS_WINCE
3791 yfsd_UnlockYAFFS(TRUE);
3793 memcpy(buffer,&cache->data[start],nToCopy);
3795 #ifdef CONFIG_YAFFS_WINCE
3796 yfsd_LockYAFFS(TRUE);
3802 // Read into the local buffer then copy...
3804 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3805 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3806 #ifdef CONFIG_YAFFS_WINCE
3807 yfsd_UnlockYAFFS(TRUE);
3809 memcpy(buffer,&localBuffer[start],nToCopy);
3811 #ifdef CONFIG_YAFFS_WINCE
3812 yfsd_LockYAFFS(TRUE);
3814 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
3820 #ifdef CONFIG_YAFFS_WINCE
3821 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3823 // Under WinCE can't do direct transfer. Need to use a local buffer.
3824 // This is because we otherwise screw up WinCE's memory mapper
3825 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3827 #ifdef CONFIG_YAFFS_WINCE
3828 yfsd_UnlockYAFFS(TRUE);
3830 memcpy(buffer,localBuffer,dev->nBytesPerChunk);
3832 #ifdef CONFIG_YAFFS_WINCE
3833 yfsd_LockYAFFS(TRUE);
3834 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
3838 // A full chunk. Read directly into the supplied buffer.
3839 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3855 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes, int writeThrough)
3864 int startOfWrite = offset;
3865 int chunkWritten = 0;
3873 while(n > 0 && chunkWritten >= 0)
3875 chunk = offset / dev->nBytesPerChunk + 1;
3876 start = offset % dev->nBytesPerChunk;
3879 // OK now check for the curveball where the start and end are in
3882 if((start + n) < dev->nBytesPerChunk)
3886 // Now folks, to calculate how many bytes to write back....
3887 // If we're overwriting and not writing to then end of file then
3888 // we need to write back as much as was there before.
3890 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * dev->nBytesPerChunk);
3892 if(nBytesRead > dev->nBytesPerChunk)
3894 nBytesRead = dev->nBytesPerChunk;
3897 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3902 nToCopy = dev->nBytesPerChunk - start;
3903 nToWriteBack = dev->nBytesPerChunk;
3906 if(nToCopy != dev->nBytesPerChunk)
3908 // An incomplete start or end chunk (or maybe both start and end chunk)
3909 if(dev->nShortOpCaches > 0)
3911 yaffs_ChunkCache *cache;
3912 // If we can't find the data in the cache, then load it up.
3913 cache = yaffs_FindChunkCache(in,chunk);
3914 if(!cache && yaffs_CheckSpaceForAllocation(in->myDev))
3916 cache = yaffs_GrabChunkCache(in->myDev);
3918 cache->chunkId = chunk;
3921 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3926 yaffs_UseChunkCache(dev,cache,1);
3928 #ifdef CONFIG_YAFFS_WINCE
3929 yfsd_UnlockYAFFS(TRUE);
3932 memcpy(&cache->data[start],buffer,nToCopy);
3934 #ifdef CONFIG_YAFFS_WINCE
3935 yfsd_LockYAFFS(TRUE);
3938 cache->nBytes = nToWriteBack;
3942 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
3952 chunkWritten = -1; // fail the write
3957 // An incomplete start or end chunk (or maybe both start and end chunk)
3958 // Read into the local buffer then copy, then copy over and write back.
3960 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3962 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
3964 #ifdef CONFIG_YAFFS_WINCE
3965 yfsd_UnlockYAFFS(TRUE);
3968 memcpy(&localBuffer[start],buffer,nToCopy);
3970 #ifdef CONFIG_YAFFS_WINCE
3971 yfsd_LockYAFFS(TRUE);
3973 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,nToWriteBack,0);
3975 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
3977 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3984 #ifdef CONFIG_YAFFS_WINCE
3985 // Under WinCE can't do direct transfer. Need to use a local buffer.
3986 // This is because we otherwise screw up WinCE's memory mapper
3987 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
3988 #ifdef CONFIG_YAFFS_WINCE
3989 yfsd_UnlockYAFFS(TRUE);
3991 memcpy(localBuffer,buffer,dev->nBytesPerChunk);
3992 #ifdef CONFIG_YAFFS_WINCE
3993 yfsd_LockYAFFS(TRUE);
3995 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,dev->nBytesPerChunk,0);
3996 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
3998 // A full chunk. Write directly from the supplied buffer.
3999 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,dev->nBytesPerChunk,0);
4001 // Since we've overwritten the cached data, we better invalidate it.
4002 yaffs_InvalidateChunkCache(in,chunk);
4003 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
4006 if(chunkWritten >= 0)
4016 // Update file object
4018 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
4020 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4028 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4031 yaffs_Device *dev = in->myDev;
4032 int oldFileSize = in->variant.fileVariant.fileSize;
4035 int lastDel = 1 + (oldFileSize-1)/dev->nBytesPerChunk;
4037 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1)/
4038 dev->nBytesPerChunk;
4042 // Delete backwards so that we don't end up with holes if
4043 // power is lost part-way through the operation.
4044 for(i = lastDel; i >= startDel; i--)
4046 // NB this could be optimised somewhat,
4047 // eg. could retrieve the tags and write them without
4048 // using yaffs_DeleteChunk
4050 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
4053 if(chunkId < (dev->internalStartBlock * dev->nChunksPerBlock) ||
4054 chunkId >= ((dev->internalEndBlock+1) * dev->nChunksPerBlock))
4056 T(YAFFS_TRACE_ALWAYS,(TSTR("Found daft chunkId %d for %d"TENDSTR),chunkId,i));
4061 yaffs_DeleteChunk(dev,chunkId,1,__LINE__);
4068 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
4071 int oldFileSize = in->variant.fileVariant.fileSize;
4072 int sizeOfPartialChunk;
4073 yaffs_Device *dev = in->myDev;
4075 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
4078 yaffs_FlushFilesChunkCache(in);
4079 yaffs_InvalidateWholeChunkCache(in);
4081 yaffs_CheckGarbageCollection(dev);
4083 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
4085 return yaffs_GetFileSize(in);
4088 if(newSize < oldFileSize)
4091 yaffs_PruneResizedChunks(in,newSize);
4093 if(sizeOfPartialChunk != 0)
4095 int lastChunk = 1+ newSize/dev->nBytesPerChunk;
4096 __u8 *localBuffer = yaffs_GetTempBuffer(dev,__LINE__);
4098 // Got to read and rewrite the last chunk with its new size and zero pad
4099 yaffs_ReadChunkDataFromObject(in,lastChunk,localBuffer);
4101 memset(localBuffer + sizeOfPartialChunk,0, dev->nBytesPerChunk - sizeOfPartialChunk);
4103 yaffs_WriteChunkDataToObject(in,lastChunk,localBuffer,sizeOfPartialChunk,1);
4105 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
4108 in->variant.fileVariant.fileSize = newSize;
4110 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
4112 // Write a new object header to show we've shrunk the file
4113 // Do this only if the file is not in the deleted directories.
4114 if(in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4115 in->parent->objectId != YAFFS_OBJECTID_DELETED
4118 yaffs_UpdateObjectHeader(in,NULL, 0, 1,0);
4132 loff_t yaffs_GetFileSize(yaffs_Object *obj)
4134 obj = yaffs_GetEquivalentObject(obj);
4136 switch(obj->variantType)
4138 case YAFFS_OBJECT_TYPE_FILE:
4139 return obj->variant.fileVariant.fileSize;
4140 case YAFFS_OBJECT_TYPE_SYMLINK:
4141 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4149 // yaffs_FlushFile() updates the file's
4152 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
4157 //T(("flushing object header\n"));
4159 yaffs_FlushFilesChunkCache(in);
4162 #ifdef CONFIG_YAFFS_WINCE
4163 yfsd_WinFileTimeNow(in->win_mtime);
4166 in->yst_mtime = Y_CURRENT_TIME;
4171 retVal = (yaffs_UpdateObjectHeader(in,NULL,0,0,0) >= 0)? YAFFS_OK : YAFFS_FAIL;
4183 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
4186 // First off, invalidate the file's data in the cache, without flushing.
4187 yaffs_InvalidateWholeChunkCache(in);
4189 if(in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir))
4191 // Move to the unlinked directory so we have a record that it was deleted.
4192 yaffs_ChangeObjectName(in, in->myDev->deletedDir,NULL,0,0);
4197 yaffs_RemoveObjectFromDirectory(in);
4198 yaffs_DeleteChunk(in->myDev,in->chunkId,1,__LINE__);
4204 in->myInode->u.generic_ip = NULL;
4210 yaffs_FreeObject(in);
4215 // yaffs_DeleteFile deletes the whole file data
4216 // and the inode associated with the file.
4217 // It does not delete the links associated with the file.
4218 static int yaffs_UnlinkFile(yaffs_Object *in)
4221 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
4223 // Delete the file data & tnodes
4225 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
4228 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
4230 return yaffs_DoGenericObjectDeletion(in);
4233 int immediateDeletion=0;
4238 //in->myDev->nUnlinkedFiles++;
4239 //in->renameAllowed = 0;
4243 immediateDeletion = 1;
4249 immediateDeletion = 1;
4253 if(immediateDeletion)
4255 retVal = yaffs_ChangeObjectName(in, in->myDev->deletedDir,NULL,0,0);
4256 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
4258 in->myDev->nDeletedFiles++;
4259 if( 0 && in->myDev->isYaffs2)
4261 yaffs_ResizeFile(in,0);
4263 yaffs_SoftDeleteFile(in);
4267 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0,0);
4277 int yaffs_DeleteFile(yaffs_Object *in)
4279 int retVal = YAFFS_OK;
4281 if(in->nDataChunks > 0)
4283 // Use soft deletion
4286 retVal = yaffs_UnlinkFile(in);
4288 if(retVal == YAFFS_OK &&
4293 in->myDev->nDeletedFiles++;
4294 yaffs_SoftDeleteFile(in);
4296 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4300 // The file has no data chunks so we toss it immediately
4301 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
4302 in->variant.fileVariant.top = NULL;
4303 yaffs_DoGenericObjectDeletion(in);
4309 static int yaffs_DeleteDirectory(yaffs_Object *in)
4311 //First check that the directory is empty.
4312 if(list_empty(&in->variant.directoryVariant.children))
4314 return yaffs_DoGenericObjectDeletion(in);
4321 static int yaffs_DeleteSymLink(yaffs_Object *in)
4323 YFREE(in->variant.symLinkVariant.alias);
4325 return yaffs_DoGenericObjectDeletion(in);
4328 static int yaffs_DeleteHardLink(yaffs_Object *in)
4330 // remove this hardlink from the list assocaited with the equivalent
4332 list_del(&in->hardLinks);
4333 return yaffs_DoGenericObjectDeletion(in);
4337 static void yaffs_DestroyObject(yaffs_Object *obj)
4339 switch(obj->variantType)
4341 case YAFFS_OBJECT_TYPE_FILE: yaffs_DeleteFile(obj); break;
4342 case YAFFS_OBJECT_TYPE_DIRECTORY: yaffs_DeleteDirectory(obj); break;
4343 case YAFFS_OBJECT_TYPE_SYMLINK: yaffs_DeleteSymLink(obj); break;
4344 case YAFFS_OBJECT_TYPE_HARDLINK: yaffs_DeleteHardLink(obj); break;
4345 case YAFFS_OBJECT_TYPE_SPECIAL: yaffs_DoGenericObjectDeletion(obj); break;
4346 case YAFFS_OBJECT_TYPE_UNKNOWN: break; // should not happen.
4351 static int yaffs_UnlinkWorker(yaffs_Object *obj)
4355 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4357 return yaffs_DeleteHardLink(obj);
4359 else if(!list_empty(&obj->hardLinks))
4361 // Curve ball: We're unlinking an object that has a hardlink.
4363 // This problem arises because we are not strictly following
4364 // The Linux link/inode model.
4366 // We can't really delete the object.
4367 // Instead, we do the following:
4368 // - Select a hardlink.
4369 // - Unhook it from the hard links
4370 // - Unhook it from its parent directory (so that the rename can work)
4371 // - Rename the object to the hardlink's name.
4372 // - Delete the hardlink
4377 YCHAR name[YAFFS_MAX_NAME_LENGTH+1];
4379 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
4381 list_del_init(&hl->hardLinks);
4382 list_del_init(&hl->siblings);
4384 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
4386 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0,0);
4388 if(retVal == YAFFS_OK)
4390 retVal = yaffs_DoGenericObjectDeletion(hl);
4397 switch(obj->variantType)
4399 case YAFFS_OBJECT_TYPE_FILE:
4400 return yaffs_UnlinkFile(obj);
4402 case YAFFS_OBJECT_TYPE_DIRECTORY:
4403 return yaffs_DeleteDirectory(obj);
4405 case YAFFS_OBJECT_TYPE_SYMLINK:
4406 return yaffs_DeleteSymLink(obj);
4408 case YAFFS_OBJECT_TYPE_SPECIAL:
4409 return yaffs_DoGenericObjectDeletion(obj);
4411 case YAFFS_OBJECT_TYPE_HARDLINK:
4412 case YAFFS_OBJECT_TYPE_UNKNOWN:
4419 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
4423 obj = yaffs_FindObjectByName(dir,name);
4425 if(obj && obj->unlinkAllowed)
4427 return yaffs_UnlinkWorker(obj);
4434 //////////////// Initialisation Scanning /////////////////
4437 void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId, int backwardScanning)
4443 // For now we use the SmartMedia check.
4444 // We look at the blockStatus byte in the first two chunks
4445 // These must be 0xFF to pass as OK.
4446 // todo: this function needs to be modifyable foir different NAND types
4447 // and different chunk sizes. Suggest make this into a per-device configurable
4449 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
4451 yaffsExtendedTags *tags;
4453 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock,NULL,&tags,1);
4455 if(yaffs_CountBits(spare.blockStatus) < 7)
4460 if(spare.blockStatus != 0xFF)
4465 yaffs_ReadChunkFromNAND(dev,blk * dev->nChunksPerBlock + 1,NULL,&spare,1);
4468 if(yaffs_CountBits(spare.blockStatus) < 7)
4473 if(spare.blockStatus != 0xFF)
4494 static int yaffs_Scan(yaffs_Device *dev)
4496 yaffs_ExtendedTags tags;
4501 int nBlocksToScan = 0;
4506 yaffs_BlockState state;
4507 yaffs_Object *hardList = NULL;
4509 yaffs_BlockInfo *bi;
4511 yaffs_ObjectHeader *oh;
4513 yaffs_Object *parent;
4514 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4518 yaffs_BlockIndex *blockIndex = NULL;
4520 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),dev->internalStartBlock,dev->internalEndBlock));
4522 chunkData = yaffs_GetTempBuffer(dev,__LINE__);
4525 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4529 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4533 // Scan all the blocks to determine their state
4534 for(blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++)
4536 bi = yaffs_GetBlockInfo(dev,blk);
4537 yaffs_ClearChunkBits(dev,blk);
4539 bi->softDeletions = 0;
4541 yaffs_QueryInitialBlockState(dev,blk,&state,&sequenceNumber);
4543 bi->blockState = state;
4544 bi->sequenceNumber = sequenceNumber;
4546 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("Block scanning block %d state %d seq %d" TENDSTR),blk,state,sequenceNumber));
4548 if(state == YAFFS_BLOCK_STATE_DEAD)
4550 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
4552 else if(state == YAFFS_BLOCK_STATE_EMPTY)
4554 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("Block empty " TENDSTR)));
4555 dev->nErasedBlocks++;
4556 dev->nFreeChunks += dev->nChunksPerBlock;
4558 else if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
4561 // Determine the highest sequence number
4562 if( dev->isYaffs2 &&
4563 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4564 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER)
4567 blockIndex[nBlocksToScan].seq = sequenceNumber;
4568 blockIndex[nBlocksToScan].block = blk;
4572 if(sequenceNumber >= dev->sequenceNumber)
4574 dev->sequenceNumber = sequenceNumber;
4577 else if(dev->isYaffs2)
4579 // TODO: Nasty sequence number!
4580 T(YAFFS_TRACE_SCAN,(TSTR("Block scanning block %d has bad sequence number %d" TENDSTR),blk,sequenceNumber));
4587 // Dungy old bubble sort for now...
4590 yaffs_BlockIndex temp;
4594 for(i = 0; i < nBlocksToScan; i++)
4595 for(j = i+1; j < nBlocksToScan; j++)
4596 if(blockIndex[i].seq > blockIndex[j].seq)
4598 temp = blockIndex[j];
4599 blockIndex[j] = blockIndex[i];
4600 blockIndex[i] = temp;
4605 // Now scan the blocks looking at the data.
4609 endIterator = nBlocksToScan-1;
4610 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("%d blocks to be scanned" TENDSTR),nBlocksToScan));
4614 startIterator = dev->internalStartBlock;
4615 endIterator = dev->internalEndBlock;
4618 // For each block....
4619 for(blockIterator = startIterator; blockIterator <= endIterator; blockIterator++)
4624 // get the block to scan in the correct order
4625 blk = blockIndex[blockIterator].block;
4629 blk = blockIterator;
4633 bi = yaffs_GetBlockInfo(dev,blk);
4634 state = bi->blockState;
4638 // For each chunk in each block that needs scanning....
4639 for(c = 0; c < dev->nChunksPerBlock &&
4640 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++)
4642 // Read the tags and decide what to do
4643 chunk = blk * dev->nChunksPerBlock + c;
4645 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,NULL,&tags);
4647 // Let's have a good look at this chunk...
4650 if(!dev->isYaffs2 && tags.chunkDeleted)
4655 dev->nFreeChunks ++;
4656 //T((" %d %d deleted\n",blk,c));
4658 else if(!tags.chunkUsed)
4660 // An unassigned chunk in the block
4661 // This means that either the block is empty or
4662 // this is the one being allocated from
4666 // We're looking at the first chunk in the block so the block is unused
4667 state = YAFFS_BLOCK_STATE_EMPTY;
4668 dev->nErasedBlocks++;
4672 // this is the block being allocated from
4673 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
4674 state = YAFFS_BLOCK_STATE_ALLOCATING;
4675 dev->allocationBlock = blk;
4676 dev->allocationPage = c;
4677 dev->allocationBlockFinder = blk; // Set it to here to encourage the allocator to
4678 // go forth from here.
4679 //Yaffs2 sanity check:
4680 // This should be the one with the highest sequence number
4681 if(dev->isYaffs2 && (dev->sequenceNumber != bi->sequenceNumber))
4683 T(YAFFS_TRACE_ALWAYS,
4684 (TSTR("yaffs: Allocation block %d was not highest sequence id: block seq = %d, dev seq = %d" TENDSTR),
4685 blk,bi->sequenceNumber,dev->sequenceNumber));
4689 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4691 else if(tags.chunkId > 0)
4693 // chunkId > 0 so it is a data chunk...
4694 unsigned int endpos;
4696 yaffs_SetChunkBit(dev,blk,c);
4699 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
4700 // PutChunkIntoFile checks for a clash (two data chunks with
4701 // the same chunkId).
4702 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
4703 endpos = (tags.chunkId - 1)* dev->nBytesPerChunk + tags.byteCount;
4704 if(in->variantType == YAFFS_OBJECT_TYPE_FILE && in->variant.fileVariant.scannedFileSize <endpos)
4706 in->variant.fileVariant.scannedFileSize = endpos;
4707 if(!dev->useHeaderFileSize)
4709 in->variant.fileVariant.fileSize = in->variant.fileVariant.scannedFileSize;
4713 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
4717 // chunkId == 0, so it is an ObjectHeader.
4718 // Thus, we read in the object header and make the object
4719 yaffs_SetChunkBit(dev,blk,c);
4722 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,chunkData,NULL);
4724 oh = (yaffs_ObjectHeader *)chunkData;
4726 in = yaffs_FindObjectByNumber(dev,tags.objectId);
4727 if(in && in->variantType != oh->type)
4729 // This should not happen, but somehow
4730 // Wev'e ended up with an objectId that has been reused but not yet
4731 // deleted, and worse still it has changed type. Delete the old object.
4733 yaffs_DestroyObject(in);
4738 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
4740 if(oh->shadowsObject > 0)
4742 yaffs_HandleShadowedObject(dev,oh->shadowsObject,0);
4747 // We have already filled this one. We have a duplicate and need to resolve it.
4749 unsigned existingSerial = in->serial;
4750 unsigned newSerial = tags.serialNumber;
4752 if( dev->isYaffs2 ||
4753 ((existingSerial+1) & 3) == newSerial)
4755 // Use new one - destroy the exisiting one
4756 yaffs_DeleteChunk(dev,in->chunkId,1,__LINE__);
4761 // Use existing - destroy this one.
4762 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
4767 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4768 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4770 // We only load some info, don't fiddle with directory structure
4772 in->variantType = oh->type;
4774 in->yst_mode = oh->yst_mode;
4775 #ifdef CONFIG_YAFFS_WINCE
4776 in->win_atime[0] = oh->win_atime[0];
4777 in->win_ctime[0] = oh->win_ctime[0];
4778 in->win_mtime[0] = oh->win_mtime[0];
4779 in->win_atime[1] = oh->win_atime[1];
4780 in->win_ctime[1] = oh->win_ctime[1];
4781 in->win_mtime[1] = oh->win_mtime[1];
4783 in->yst_uid = oh->yst_uid;
4784 in->yst_gid = oh->yst_gid;
4785 in->yst_atime = oh->yst_atime;
4786 in->yst_mtime = oh->yst_mtime;
4787 in->yst_ctime = oh->yst_ctime;
4788 in->yst_rdev = oh->yst_rdev;
4790 in->chunkId = chunk;
4795 // we need to load this info
4798 in->variantType = oh->type;
4800 in->yst_mode = oh->yst_mode;
4801 #ifdef CONFIG_YAFFS_WINCE
4802 in->win_atime[0] = oh->win_atime[0];
4803 in->win_ctime[0] = oh->win_ctime[0];
4804 in->win_mtime[0] = oh->win_mtime[0];
4805 in->win_atime[1] = oh->win_atime[1];
4806 in->win_ctime[1] = oh->win_ctime[1];
4807 in->win_mtime[1] = oh->win_mtime[1];
4809 in->yst_uid = oh->yst_uid;
4810 in->yst_gid = oh->yst_gid;
4811 in->yst_atime = oh->yst_atime;
4812 in->yst_mtime = oh->yst_mtime;
4813 in->yst_ctime = oh->yst_ctime;
4814 in->yst_rdev = oh->yst_rdev;
4816 in->chunkId = chunk;
4818 yaffs_SetObjectName(in,oh->name);
4821 // directory stuff...
4822 // hook up to parent
4824 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
4825 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
4827 // Set up as a directory
4828 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
4829 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
4831 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4833 // Hoosterman, another problem....
4834 // We're trying to use a non-directory as a directory
4836 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found." TENDSTR)));
4837 parent = dev->lostNFoundDir;
4840 yaffs_AddObjectToDirectory(parent,in);
4842 if(0 && (parent == dev->deletedDir ||
4843 parent == dev->unlinkedDir))
4845 in->deleted = 1; // If it is unlinked at start up then it wants deleting
4846 dev->nDeletedFiles++;
4849 // Note re hardlinks.
4850 // Since we might scan a hardlink before its equivalent object is scanned
4851 // we put them all in a list.
4852 // After scanning is complete, we should have all the objects, so we run through this
4853 // list and fix up all the chains.
4855 switch(in->variantType)
4857 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
4859 case YAFFS_OBJECT_TYPE_FILE:
4860 if(dev->isYaffs2 && oh->isShrink)
4862 // Prune back the shrunken chunks
4863 yaffs_PruneResizedChunks(in,oh->fileSize);
4864 // Mark the block as having a shrinkHeader
4865 bi->hasShrinkHeader = 1;
4868 if(dev->useHeaderFileSize)
4870 in->variant.fileVariant.fileSize = oh->fileSize;
4873 case YAFFS_OBJECT_TYPE_HARDLINK:
4874 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
4875 in->hardLinks.next = (struct list_head *)hardList;
4878 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
4880 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
4882 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
4883 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
4887 if(parent == dev->deletedDir)
4889 yaffs_DestroyObject(in);
4890 bi->hasShrinkHeader = 1;
4892 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
4897 if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
4899 // If we got this far while scanning, then the block is fully allocated.
4900 state = YAFFS_BLOCK_STATE_FULL;
4903 bi->blockState = state;
4905 // Now let's see if it was dirty
4906 if( bi->pagesInUse == 0 &&
4907 !bi->hasShrinkHeader &&
4908 bi->blockState == YAFFS_BLOCK_STATE_FULL)
4910 yaffs_BlockBecameDirty(dev,blk);
4920 // Ok, we've done all the scanning.
4922 // Fix up the hard link chains.
4923 // We should now have scanned all the objects, now it's time to add these
4928 hardList = (yaffs_Object *)(hardList->hardLinks.next);
4930 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
4934 // Add the hardlink pointers
4935 hl->variant.hardLinkVariant.equivalentObject=in;
4936 list_add(&hl->hardLinks,&in->hardLinks);
4940 //Todo Need to report/handle this better.
4941 // Got a problem... hardlink to a non-existant object
4942 hl->variant.hardLinkVariant.equivalentObject=NULL;
4943 INIT_LIST_HEAD(&hl->hardLinks);
4949 // Handle the unlinked files. Since they were left in an unlinked state we should
4950 // just delete them.
4952 struct list_head *i;
4953 struct list_head *n;
4956 // Soft delete all the unlinked files
4957 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
4961 l = list_entry(i, yaffs_Object,siblings);
4962 yaffs_DestroyObject(l);
4967 yaffs_ReleaseTempBuffer(dev,chunkData,__LINE__);
4969 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_Scan ends" TENDSTR)));
4975 static int yaffs_ScanBackwards(yaffs_Device *dev)
4977 yaffs_ExtendedTags tags;
4982 int nBlocksToScan = 0;
4987 yaffs_BlockState state;
4988 yaffs_Object *hardList = NULL;
4990 yaffs_BlockInfo *bi;
4992 yaffs_ObjectHeader *oh;
4994 yaffs_Object *parent;
4995 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4999 yaffs_BlockIndex *blockIndex = NULL;
5004 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5008 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_ScanBackwards starts intstartblk %d intendblk %d..." TENDSTR),dev->internalStartBlock,dev->internalEndBlock));
5010 chunkData = yaffs_GetTempBuffer(dev,__LINE__);
5013 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5015 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5018 // Scan all the blocks to determine their state
5019 for(blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++)
5021 bi = yaffs_GetBlockInfo(dev,blk);
5022 yaffs_ClearChunkBits(dev,blk);
5024 bi->softDeletions = 0;
5026 yaffs_QueryInitialBlockState(dev,blk,&state,&sequenceNumber);
5028 bi->blockState = state;
5029 bi->sequenceNumber = sequenceNumber;
5031 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("Block scanning block %d state %d seq %d" TENDSTR),blk,state,sequenceNumber));
5033 if(state == YAFFS_BLOCK_STATE_DEAD)
5035 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
5037 else if(state == YAFFS_BLOCK_STATE_EMPTY)
5039 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("Block empty " TENDSTR)));
5040 dev->nErasedBlocks++;
5041 dev->nFreeChunks += dev->nChunksPerBlock;
5043 else if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
5046 // Determine the highest sequence number
5047 if( dev->isYaffs2 &&
5048 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5049 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER)
5052 blockIndex[nBlocksToScan].seq = sequenceNumber;
5053 blockIndex[nBlocksToScan].block = blk;
5057 if(sequenceNumber >= dev->sequenceNumber)
5059 dev->sequenceNumber = sequenceNumber;
5062 else if(dev->isYaffs2)
5064 // TODO: Nasty sequence number!
5065 T(YAFFS_TRACE_SCAN,(TSTR("Block scanning block %d has bad sequence number %d" TENDSTR),blk,sequenceNumber));
5072 // Dungy old bubble sort for now...
5074 yaffs_BlockIndex temp;
5078 for(i = 0; i < nBlocksToScan; i++)
5079 for(j = i+1; j < nBlocksToScan; j++)
5080 if(blockIndex[i].seq > blockIndex[j].seq)
5082 temp = blockIndex[j];
5083 blockIndex[j] = blockIndex[i];
5084 blockIndex[i] = temp;
5089 // Now scan the blocks looking at the data.
5091 endIterator = nBlocksToScan-1;
5092 T(YAFFS_TRACE_SCAN_DEBUG,(TSTR("%d blocks to be scanned" TENDSTR),nBlocksToScan));
5095 // For each block.... backwards
5096 for(blockIterator = endIterator; blockIterator >= startIterator; blockIterator--)
5099 // get the block to scan in the correct order
5100 blk = blockIndex[blockIterator].block;
5103 bi = yaffs_GetBlockInfo(dev,blk);
5104 state = bi->blockState;
5108 if( 0 && // Disable since this is redundant.
5109 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
5111 // Let's look at the first chunk in the block
5112 chunk = blk * dev->nChunksPerBlock;
5114 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,NULL,&tags);
5116 // Let's have a good look at this chunk...
5120 // An unassigned chunk in the block
5121 // This means that either the block is empty or
5122 // this is the one being allocated from
5124 // We're looking at the first chunk in the block so the block is unused
5125 state = YAFFS_BLOCK_STATE_EMPTY;
5126 dev->nErasedBlocks++;
5127 dev->nFreeChunks += dev->nChunksPerBlock;
5132 // For each chunk in each block that needs scanning....
5133 for(c = dev->nChunksPerBlock-1; c >= 0 &&
5134 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5135 state == YAFFS_BLOCK_STATE_ALLOCATING); c--)
5137 // Scan backwards...
5138 // Read the tags and decide what to do
5139 chunk = blk * dev->nChunksPerBlock + c;
5141 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,NULL,&tags);
5143 // Let's have a good look at this chunk...
5147 // An unassigned chunk in the block
5148 // This means that either the block is empty or
5149 // this is the one being allocated from
5153 // We're looking at the first chunk in the block so the block is unused
5154 state = YAFFS_BLOCK_STATE_EMPTY;
5155 dev->nErasedBlocks++;
5159 // this is the block being allocated from
5160 if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
5162 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
5164 state = YAFFS_BLOCK_STATE_ALLOCATING;
5165 dev->allocationBlock = blk;
5166 dev->allocationPage = c;
5167 dev->allocationBlockFinder = blk; // Set it to here to encourage the allocator to
5168 // go forth from here.
5169 //Yaffs2 sanity check:
5170 // This should be the one with the highest sequence number
5171 if(dev->isYaffs2 && (dev->sequenceNumber != bi->sequenceNumber))
5173 T(YAFFS_TRACE_ALWAYS,
5174 (TSTR("yaffs: Allocation block %d was not highest sequence id: block seq = %d, dev seq = %d" TENDSTR),
5175 blk,bi->sequenceNumber,dev->sequenceNumber));
5179 dev->nFreeChunks ++;
5181 else if(tags.chunkId > 0)
5183 // chunkId > 0 so it is a data chunk...
5184 unsigned int endpos;
5186 __u32 chunkBase = (tags.chunkId - 1)* dev->nBytesPerChunk;
5188 yaffs_SetChunkBit(dev,blk,c);
5191 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
5192 if(in->variantType == YAFFS_OBJECT_TYPE_FILE &&
5193 chunkBase < in->variant.fileVariant.shrinkSize)
5195 // This has not been invalidated by a resize
5196 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,-1);
5199 // File size is calculated by looking at the data chunks if we have not
5200 // seen an object header yet. Stop this practice once we find an object header.
5201 endpos = (tags.chunkId - 1)* dev->nBytesPerChunk + tags.byteCount;
5202 if(!in->valid && // have not got an object header yet
5203 in->variant.fileVariant.scannedFileSize <endpos)
5205 in->variant.fileVariant.scannedFileSize = endpos;
5206 in->variant.fileVariant.fileSize = in->variant.fileVariant.scannedFileSize;
5212 // This chunk has been invalidated by a resize, so delete
5213 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
5217 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
5221 // chunkId == 0, so it is an ObjectHeader.
5222 // Thus, we read in the object header and make the object
5223 yaffs_SetChunkBit(dev,blk,c);
5229 if(tags.extraHeaderInfoAvailable)
5231 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,tags.extraObjectType);
5235 if(!in || !in->valid)
5238 // If we don't have valid info then we need to read the chunk
5239 // TODO In future we can probably defer reading the chunk and
5240 // living with invalid data until needed.
5242 yaffs_ReadChunkWithTagsFromNAND(dev,chunk,chunkData,NULL);
5244 oh = (yaffs_ObjectHeader *)chunkData;
5247 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
5253 // TODO Hoosterman we have a problem!
5254 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: Could not make object for object %d at chunk %d during scan" TENDSTR),tags.objectId,chunk));
5260 // We have already filled this one. We have a duplicate that will be discarded, but
5261 // we first have to suck out resize info if it is a file.
5263 if( (in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5264 ((oh && oh->type == YAFFS_OBJECT_TYPE_FILE) ||
5265 (tags.extraHeaderInfoAvailable && tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5268 __u32 thisSize = (oh) ? oh->fileSize : tags.extraFileLength;
5269 __u32 parentObjectId = (oh) ? oh->parentObjectId : tags.extraParentObjectId;
5270 unsigned isShrink = (oh) ? oh->isShrink : tags.extraIsShrinkHeader;
5272 // If it is deleted (unlinked at start also means deleted)
5273 // we treat the file size as being zeroed at this point.
5274 if(parentObjectId == YAFFS_OBJECTID_DELETED ||
5275 parentObjectId == YAFFS_OBJECTID_UNLINKED)
5281 if(in->variant.fileVariant.shrinkSize > thisSize)
5283 in->variant.fileVariant.shrinkSize = thisSize;
5288 bi->hasShrinkHeader = 1;
5292 // Use existing - destroy this one.
5293 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
5298 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5299 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5301 // We only load some info, don't fiddle with directory structure
5303 in->variantType = oh->type;
5305 in->yst_mode = oh->yst_mode;
5306 #ifdef CONFIG_YAFFS_WINCE
5307 in->win_atime[0] = oh->win_atime[0];
5308 in->win_ctime[0] = oh->win_ctime[0];
5309 in->win_mtime[0] = oh->win_mtime[0];
5310 in->win_atime[1] = oh->win_atime[1];
5311 in->win_ctime[1] = oh->win_ctime[1];
5312 in->win_mtime[1] = oh->win_mtime[1];
5314 in->yst_uid = oh->yst_uid;
5315 in->yst_gid = oh->yst_gid;
5316 in->yst_atime = oh->yst_atime;
5317 in->yst_mtime = oh->yst_mtime;
5318 in->yst_ctime = oh->yst_ctime;
5319 in->yst_rdev = oh->yst_rdev;
5321 in->chunkId = chunk;
5326 // we need to load this info
5329 in->variantType = oh->type;
5331 in->yst_mode = oh->yst_mode;
5332 #ifdef CONFIG_YAFFS_WINCE
5333 in->win_atime[0] = oh->win_atime[0];
5334 in->win_ctime[0] = oh->win_ctime[0];
5335 in->win_mtime[0] = oh->win_mtime[0];
5336 in->win_atime[1] = oh->win_atime[1];
5337 in->win_ctime[1] = oh->win_ctime[1];
5338 in->win_mtime[1] = oh->win_mtime[1];
5340 in->yst_uid = oh->yst_uid;
5341 in->yst_gid = oh->yst_gid;
5342 in->yst_atime = oh->yst_atime;
5343 in->yst_mtime = oh->yst_mtime;
5344 in->yst_ctime = oh->yst_ctime;
5345 in->yst_rdev = oh->yst_rdev;
5347 in->chunkId = chunk;
5349 if(oh->shadowsObject > 0)
5351 yaffs_HandleShadowedObject(dev,oh->shadowsObject,0);
5355 yaffs_SetObjectName(in,oh->name);
5358 // directory stuff...
5359 // hook up to parent
5361 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
5362 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
5364 // Set up as a directory
5365 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
5366 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
5368 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5370 // Hoosterman, another problem....
5371 // We're trying to use a non-directory as a directory
5373 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found." TENDSTR)));
5374 parent = dev->lostNFoundDir;
5377 yaffs_AddObjectToDirectory(parent,in);
5379 if((parent == dev->deletedDir ||
5380 parent == dev->unlinkedDir))
5382 in->deleted = 1; // If it is unlinked at start up then it wants deleting
5387 // Mark the block as having a shrinkHeader
5388 bi->hasShrinkHeader = 1;
5392 // Note re hardlinks.
5393 // Since we might scan a hardlink before its equivalent object is scanned
5394 // we put them all in a list.
5395 // After scanning is complete, we should have all the objects, so we run through this
5396 // list and fix up all the chains.
5398 switch(in->variantType)
5400 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
5402 case YAFFS_OBJECT_TYPE_FILE:
5405 if(in->variant.fileVariant.scannedFileSize < oh->fileSize)
5407 in->variant.fileVariant.fileSize = oh->fileSize;
5408 in->variant.fileVariant.scannedFileSize = in->variant.fileVariant.fileSize;
5413 if(in->variant.fileVariant.shrinkSize > oh->fileSize)
5415 in->variant.fileVariant.shrinkSize = oh->fileSize;
5420 case YAFFS_OBJECT_TYPE_HARDLINK:
5421 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
5422 in->hardLinks.next = (struct list_head *)hardList;
5425 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
5427 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
5429 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
5430 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
5435 if(parent == dev->deletedDir)
5437 yaffs_DestroyObject(in);
5438 bi->hasShrinkHeader = 1;
5441 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
5446 if(state == YAFFS_BLOCK_STATE_NEEDS_SCANNING)
5448 // If we got this far while scanning, then the block is fully allocated.
5449 state = YAFFS_BLOCK_STATE_FULL;
5452 bi->blockState = state;
5454 // Now let's see if it was dirty
5455 if( bi->pagesInUse == 0 &&
5456 !bi->hasShrinkHeader &&
5457 bi->blockState == YAFFS_BLOCK_STATE_FULL)
5459 yaffs_BlockBecameDirty(dev,blk);
5469 // Ok, we've done all the scanning.
5471 // Fix up the hard link chains.
5472 // We should now have scanned all the objects, now it's time to add these
5477 hardList = (yaffs_Object *)(hardList->hardLinks.next);
5479 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
5483 // Add the hardlink pointers
5484 hl->variant.hardLinkVariant.equivalentObject=in;
5485 list_add(&hl->hardLinks,&in->hardLinks);
5489 //Todo Need to report/handle this better.
5490 // Got a problem... hardlink to a non-existant object
5491 hl->variant.hardLinkVariant.equivalentObject=NULL;
5492 INIT_LIST_HEAD(&hl->hardLinks);
5499 struct list_head *i;
5500 struct list_head *n;
5504 // Soft delete all the unlinked files
5505 list_for_each_safe(i,n,&dev->unlinkedDir->variant.directoryVariant.children)
5509 l = list_entry(i, yaffs_Object,siblings);
5510 yaffs_DestroyObject(l);
5514 // Soft delete all the deletedDir files
5515 list_for_each_safe(i,n,&dev->deletedDir->variant.directoryVariant.children)
5519 l = list_entry(i, yaffs_Object,siblings);
5520 yaffs_DestroyObject(l);
5526 yaffs_ReleaseTempBuffer(dev,chunkData,__LINE__);
5528 T(YAFFS_TRACE_SCAN,(TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5535 ////////////////////////// Directory Functions /////////////////////////
5538 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
5543 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: Trying to add an object to a null pointer directory" TENDSTR)));
5546 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5548 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: Trying to add an object to a non-directory" TENDSTR)));
5552 if(obj->siblings.prev == NULL)
5555 INIT_LIST_HEAD(&obj->siblings);
5558 else if(!list_empty(&obj->siblings))
5560 // If it is holed up somewhere else, un hook it
5561 list_del_init(&obj->siblings);
5564 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
5565 obj->parent = directory;
5567 if(directory == obj->myDev->unlinkedDir || directory == obj->myDev->deletedDir)
5570 obj->myDev->nUnlinkedFiles++;
5571 obj->renameAllowed = 0;
5575 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
5577 list_del_init(&obj->siblings);
5581 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const YCHAR *name)
5585 struct list_head *i;
5586 YCHAR buffer[YAFFS_MAX_NAME_LENGTH+1];
5597 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: yaffs_FindObjectByName: null pointer directory"TENDSTR)));
5600 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5602 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: yaffs_FindObjectByName: non-directory"TENDSTR)));
5606 sum = yaffs_CalcNameSum(name);
5608 list_for_each(i,&directory->variant.directoryVariant.children)
5612 l = list_entry(i, yaffs_Object,siblings);
5614 // Special case for lost-n-found
5615 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
5617 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
5622 else if(yaffs_SumCompare(l->sum, sum)||
5623 l->chunkId <= 0) //LostnFound cunk called Objxxx
5626 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
5627 if(yaffs_strcmp(name,buffer) == 0)
5640 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
5642 struct list_head *i;
5648 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: yaffs_FindObjectByName: null pointer directory"TENDSTR)));
5651 if(theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5653 T(YAFFS_TRACE_ALWAYS,(TSTR("tragedy: yaffs_FindObjectByName: non-directory"TENDSTR)));
5657 list_for_each(i,&theDir->variant.directoryVariant.children)
5661 l = list_entry(i, yaffs_Object,siblings);
5674 // GetEquivalentObject dereferences any hard links to get to the
5677 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
5679 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
5681 // We want the object id of the equivalent object, not this one
5682 obj = obj->variant.hardLinkVariant.equivalentObject;
5688 int yaffs_GetObjectName(yaffs_Object *obj,YCHAR *name,int buffSize)
5690 memset(name,0,buffSize * sizeof(YCHAR));
5692 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
5694 yaffs_strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
5696 else if(obj->chunkId <= 0)
5700 yaffs_sprintf(locName,_Y("%s%d"),YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
5701 yaffs_strncpy(name,locName,buffSize - 1);
5704 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5705 else if(obj->shortName[0])
5707 yaffs_strcpy(name,obj->shortName);
5712 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev,__LINE__);
5714 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
5716 memset(buffer,0,obj->myDev->nBytesPerChunk);
5718 if(obj->chunkId >= 0)
5720 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
5722 yaffs_strncpy(name,oh->name,buffSize - 1);
5724 yaffs_ReleaseTempBuffer(obj->myDev,buffer,__LINE__);
5727 return yaffs_strlen(name);
5730 int yaffs_GetObjectFileLength(yaffs_Object *obj)
5733 // Dereference any hard linking
5734 obj = yaffs_GetEquivalentObject(obj);
5736 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
5738 return obj->variant.fileVariant.fileSize;
5740 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5742 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5746 // Only a directory should drop through to here
5747 return obj->myDev->nBytesPerChunk;
5751 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
5754 struct list_head *i;
5758 count++; // the object itself
5760 list_for_each(i,&obj->hardLinks)
5762 count++; // add the hard links;
5769 int yaffs_GetObjectInode(yaffs_Object *obj)
5771 obj = yaffs_GetEquivalentObject(obj);
5773 return obj->objectId;
5776 unsigned yaffs_GetObjectType(yaffs_Object *obj)
5778 obj = yaffs_GetEquivalentObject(obj);
5780 switch(obj->variantType)
5782 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
5783 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
5784 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
5785 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
5786 case YAFFS_OBJECT_TYPE_SPECIAL:
5787 if(S_ISFIFO(obj->yst_mode)) return DT_FIFO;
5788 if(S_ISCHR(obj->yst_mode)) return DT_CHR;
5789 if(S_ISBLK(obj->yst_mode)) return DT_BLK;
5790 if(S_ISSOCK(obj->yst_mode)) return DT_SOCK;
5791 default: return DT_REG; break;
5795 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
5797 obj = yaffs_GetEquivalentObject(obj);
5798 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5800 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5804 return yaffs_CloneString(_Y(""));
5808 #ifndef CONFIG_YAFFS_WINCE
5810 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
5812 unsigned int valid = attr->ia_valid;
5814 if(valid & ATTR_MODE) obj->yst_mode = attr->ia_mode;
5815 if(valid & ATTR_UID) obj->yst_uid = attr->ia_uid;
5816 if(valid & ATTR_GID) obj->yst_gid = attr->ia_gid;
5818 if(valid & ATTR_ATIME) obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5819 if(valid & ATTR_CTIME) obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5820 if(valid & ATTR_MTIME) obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5822 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
5824 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5829 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
5831 unsigned int valid = 0;
5833 attr->ia_mode = obj->yst_mode; valid |= ATTR_MODE;
5834 attr->ia_uid = obj->yst_uid; valid |= ATTR_UID;
5835 attr->ia_gid = obj->yst_gid; valid |= ATTR_GID;
5837 Y_TIME_CONVERT(attr->ia_atime)= obj->yst_atime; valid |= ATTR_ATIME;
5838 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime; valid |= ATTR_CTIME;
5839 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime; valid |= ATTR_MTIME;
5841 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
5843 attr->ia_valid = valid;
5851 int yaffs_DumpObject(yaffs_Object *obj)
5853 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
5855 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
5857 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
5859 // if(obj->chunkId >= 0)
5861 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
5864 yaffs_GetObjectName(obj,name,256);
5866 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),
5867 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
5868 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5871 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
5872 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
5873 obj->sum, obj->chunkId));
5874 switch(obj->variantType)
5876 case YAFFS_OBJECT_TYPE_FILE:
5877 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
5879 case YAFFS_OBJECT_TYPE_DIRECTORY:
5880 YPRINTF((" DIRECTORY\n"));
5882 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
5883 case YAFFS_OBJECT_TYPE_SYMLINK:
5884 case YAFFS_OBJECT_TYPE_UNKNOWN:
5893 ///////////////////////// Initialisation code ///////////////////////////
5896 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
5899 // Common functions, gotta have
5900 if(!dev->eraseBlockInNAND ||
5901 !dev->initialiseNAND) return 0;
5903 #ifdef CONFIG_YAFFS_YAFFS2
5905 // Can use the "with tags" style interface for yaffs1 or yaffs2
5906 if(dev->writeChunkWithTagsToNAND &&
5907 dev->readChunkWithTagsFromNAND &&
5908 !dev->writeChunkToNAND &&
5909 !dev->readChunkFromNAND &&
5910 dev->markNANDBlockBad &&
5911 dev->queryNANDBlock) return 1;
5914 // Can use the "spare" style interface for yaffs1
5915 if(!dev->isYaffs2 &&
5916 !dev->writeChunkWithTagsToNAND &&
5917 !dev->readChunkWithTagsFromNAND &&
5918 dev->writeChunkToNAND &&
5919 dev->readChunkFromNAND &&
5920 !dev->markNANDBlockBad &&
5921 !dev->queryNANDBlock) return 1;
5927 int yaffs_GutsInitialise(yaffs_Device *dev)
5934 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5935 // Check stuff that must be set
5939 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Need a device" TENDSTR)));
5943 dev->internalStartBlock = dev->startBlock;
5944 dev->internalEndBlock = dev->endBlock;
5945 dev->blockOffset = 0;
5946 dev->chunkOffset = 0;
5947 dev->nFreeChunks = 0;
5949 if(dev->startBlock == 0)
5951 dev->internalStartBlock = dev->startBlock + 1;
5952 dev->internalEndBlock = dev->endBlock + 1;
5953 dev->blockOffset = 1;
5954 dev->chunkOffset = dev->nChunksPerBlock;
5957 // Check geometry parameters.
5959 if( (dev->isYaffs2 && dev->nBytesPerChunk <1024) ||
5960 (!dev->isYaffs2 && dev->nBytesPerChunk !=512) ||
5961 dev->nChunksPerBlock < 2 ||
5962 dev->nReservedBlocks < 2 ||
5963 dev->internalStartBlock <= 0 ||
5964 dev->internalEndBlock <= 0 ||
5965 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
5968 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s " TENDSTR),
5969 dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
5973 if(yaffs_InitialiseNAND(dev) != YAFFS_OK)
5975 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5979 // Got the right mix of functions?
5981 if(!yaffs_CheckDevFunctions(dev))
5984 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5989 // This is really a compilation check.
5990 if(!yaffs_CheckStructures())
5992 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5998 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: device already mounted\n" TENDSTR)));
6004 // Finished with most checks. One or two more checks happen later on too.
6010 nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6014 // OK now calculate a few things for the device
6015 // Calculate chunkGroupBits.
6016 // We need to find the next power of 2 > than internalEndBlock
6018 x = dev->nChunksPerBlock * (dev->internalEndBlock+1);
6020 for(bits = extraBits = 0; x > 1; bits++)
6022 if(x & 1) extraBits++;
6026 if(extraBits > 0) bits++;
6029 // Level0 Tnodes are 16 bits, so if the bitwidth of the
6030 // chunk range we're using is greater than 16 we need
6031 // to figure out chunk shift and chunkGroupSize
6034 dev->chunkGroupBits = 0;
6038 dev->chunkGroupBits = bits - 16;
6041 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6043 if(dev->nChunksPerBlock < dev->chunkGroupSize)
6045 // We have a problem because the soft delete won't work if
6046 // the chunk group size > chunks per block.
6047 // This can be remedied by using larger "virtual blocks".
6048 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: chunk group too large\n" TENDSTR)));
6054 // OK, we've finished verifying the device, lets continue with initialisation
6056 // More device initialisation
6057 dev->garbageCollections = 0;
6058 dev->passiveGarbageCollections = 0;
6059 dev->currentDirtyChecker = 0;
6060 dev->bufferedBlock = -1;
6061 dev->doingBufferedBlockRewrite = 0;
6062 dev->nDeletedFiles = 0;
6063 dev->nBackgroundDeletions=0;
6064 dev->nUnlinkedFiles = 0;
6067 dev->tagsEccFixed=0;
6068 dev->tagsEccUnfixed=0;
6069 dev->nErasureFailures = 0;
6070 dev->nErasedBlocks = 0;
6073 //dev->localBuffer = YMALLOC(dev->nBytesPerChunk);
6074 // Initialise temporary buffers
6077 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
6079 dev->tempBuffer[i].line = 0; // not in use
6080 dev->tempBuffer[i].buffer = YMALLOC(dev->nBytesPerChunk);
6086 yaffs_InitialiseBlocks(dev,nBlocks);
6088 yaffs_InitialiseTnodes(dev);
6090 yaffs_InitialiseObjects(dev);
6092 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6094 if(dev->nShortOpCaches > 0)
6098 if(dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
6100 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6103 dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6105 for(i=0; i < dev->nShortOpCaches; i++)
6107 dev->srCache[i].object = NULL;
6108 dev->srCache[i].lastUse = 0;
6109 dev->srCache[i].dirty = 0;
6110 dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
6118 // Initialise the unlinked, root and lost and found directories
6119 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = dev->deletedDir = NULL;
6121 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6122 dev->deletedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_DELETED, S_IFDIR);
6124 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
6125 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6126 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
6130 dev->useHeaderFileSize = 1;
6133 // Now scan the flash.
6136 yaffs_ScanBackwards(dev);
6141 dev->nPageReads = 0;
6142 dev->nPageWrites = 0;
6143 dev->nBlockErasures = 0;
6145 dev->nRetriedWrites = 0;
6147 dev->nRetiredBlocks = 0;
6149 yaffs_VerifyFreeChunks(dev);
6151 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6156 void yaffs_Deinitialise(yaffs_Device *dev)
6162 yaffs_DeinitialiseBlocks(dev);
6163 yaffs_DeinitialiseTnodes(dev);
6164 yaffs_DeinitialiseObjects(dev);
6165 if(dev->nShortOpCaches > 0)
6168 for(i=0; i < dev->nShortOpCaches; i++)
6170 YFREE(dev->srCache[i].data);
6173 YFREE(dev->srCache);
6176 YFREE(dev->gcCleanupList);
6178 for(i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
6180 YFREE(dev->tempBuffer[i].buffer);
6190 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
6192 int nFree = dev->nFreeChunks - (dev->nChunksPerBlock * YAFFS_RESERVED_BLOCKS);
6194 struct list_head *i;
6198 // To the free chunks add the chunks that are in the deleted unlinked files.
6199 list_for_each(i,&dev->deletedDir->variant.directoryVariant.children)
6201 l = list_entry(i, yaffs_Object,siblings);
6205 nFree += l->nDataChunks;
6210 // printf("___________ nFreeChunks is %d nFree is %d\n",dev->nFreeChunks,nFree);
6212 if(nFree < 0) nFree = 0;
6220 static int yaffs_CountFreeChunks(yaffs_Device *dev)
6225 yaffs_BlockInfo *blk;
6228 for(nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock; b++)
6230 blk = yaffs_GetBlockInfo(dev,b);
6232 switch(blk->blockState)
6234 case YAFFS_BLOCK_STATE_EMPTY:
6235 case YAFFS_BLOCK_STATE_ALLOCATING:
6236 case YAFFS_BLOCK_STATE_COLLECTING:
6237 case YAFFS_BLOCK_STATE_FULL: nFree += (dev->nChunksPerBlock - blk->pagesInUse + blk->softDeletions); break;
6248 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
6250 // This is what we report to the outside world
6253 int nDirtyCacheChunks;
6256 nFree = dev->nFreeChunks;
6258 nFree = yaffs_CountFreeChunks(dev);
6261 // Now count the number of dirty chunks in the cache and subtract those
6265 for( nDirtyCacheChunks = 0,i = 0; i < dev->nShortOpCaches; i++)
6267 if(dev->srCache[i].dirty) nDirtyCacheChunks++;
6271 nFree -= nDirtyCacheChunks;
6273 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6275 if(nFree < 0) nFree = 0;
6281 static int yaffs_freeVerificationFailures;
6283 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
6285 int counted = yaffs_CountFreeChunks(dev);
6287 int difference = dev->nFreeChunks - counted;
6291 T(YAFFS_TRACE_ALWAYS,(TSTR("Freechunks verification failure %d %d %d" TENDSTR),dev->nFreeChunks,counted,difference));
6292 yaffs_freeVerificationFailures++;
6296 /////////////////// YAFFS test code //////////////////////////////////
6298 #define yaffs_CheckStruct(structure,syze, name) \
6299 if(sizeof(structure) != syze) \
6301 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
6302 return YAFFS_FAIL; \
6306 static int yaffs_CheckStructures(void)
6308 // yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
6309 // yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
6310 // yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
6311 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6312 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
6314 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
6321 void yaffs_GutsTest(yaffs_Device *dev)
6324 if(yaffs_CheckStructures() != YAFFS_OK)
6326 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
6330 yaffs_TnodeTest(dev);
6331 yaffs_ObjectTest(dev);