2 * YAFFS: Yet another FFS. A NAND-flash specific file system.
3 * yaffs_guts.c The main guts of YAFFS
5 * Copyright (C) 2002 Aleph One Ltd.
6 * for Toby Churchill Ltd and Brightstar Engineering
8 * Created by Charles Manning <charles@aleph1.co.uk>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2 as
12 * published by the Free Software Foundation.
17 const char *yaffs_guts_c_version="$Id: yaffs_guts.c,v 1.14 2002-12-04 19:12:43 charles Exp $";
21 #include "yaffsinterface.h"
22 #include "yaffs_guts.h"
25 #define YAFFS_GARBAGE_COLLECT_LOW_WATER 2
29 // External functions for ECC on data
30 void nand_calculate_ecc (const u_char *dat, u_char *ecc_code);
31 int nand_correct_data (u_char *dat, u_char *read_ecc, u_char *calc_ecc);
34 // countBits is a quick way of counting the number of bits in a byte.
35 // ie. countBits[n] holds the number of 1 bits in a byte with the value n.
37 static const char yaffs_countBitsTable[256] =
39 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
40 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
41 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
42 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
43 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
44 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
45 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
46 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
47 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
48 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
49 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
50 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
51 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
52 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
53 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
54 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
57 static int yaffs_CountBits(__u8 x)
60 retVal = yaffs_countBitsTable[x];
67 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
68 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
69 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
70 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan);
72 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
73 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
74 static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force);
75 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId);
76 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
77 static int yaffs_CheckStructures(void);
78 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev,int blockNo);
84 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND);
85 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND);
86 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND);
87 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare);
88 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare);
90 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND);
92 static int yaffs_UnlinkWorker(yaffs_Object *obj);
95 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1);
99 loff_t yaffs_GetFileSize(yaffs_Object *obj);
101 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted);
102 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted);
105 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
107 #ifdef YAFFS_PARANOID
108 static int yaffs_CheckFileSanity(yaffs_Object *in);
110 #define yaffs_CheckFileSanity(in)
113 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
114 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
117 static __inline__ yaffs_BlockInfo* yaffs_GetBlockInfo(yaffs_Device *dev, int blk)
119 if(blk < dev->startBlock || blk > dev->endBlock)
121 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs: block %d is not valid" TENDSTR),blk));
124 return &dev->blockInfo[blk - dev->startBlock];
128 static __inline__ int yaffs_HashFunction(int n)
130 return (n % YAFFS_NOBJECT_BUCKETS);
134 yaffs_Object *yaffs_Root(yaffs_Device *dev)
139 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
141 return dev->lostNFoundDir;
145 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
147 if(chunkInNAND < dev->startBlock * YAFFS_CHUNKS_PER_BLOCK)
149 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d is not valid" TENDSTR),chunkInNAND));
154 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
163 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,
167 int doErrorCorrection)
170 yaffs_Spare localSpare;
172 #ifndef CONFIG_YAFFS_USE_NANDECC
174 int eccResult1,eccResult2;
176 struct nandspare nspare;
186 // If we don't have a real spare, then we use a local one.
187 // Need this for the calculation of the ecc
192 #ifndef CONFIG_YAFFS_USE_NANDECC
193 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
194 if(data && doErrorCorrection)
196 // Hoosterman, we had a data problem on this page
197 yaffs_HandleReadDataError(dev,chunkInNAND);
200 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare*)&nspare);
201 memcpy (spare, &nspare, sizeof(yaffs_Spare));
202 if(data && doErrorCorrection)
206 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:0" TENDSTR),chunkInNAND));
208 else if(nspare.eccres1<0)
210 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:0" TENDSTR),chunkInNAND));
215 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error fix performed on chunk %d:1" TENDSTR),chunkInNAND));
217 else if(nspare.eccres2<0)
219 T(YAFFS_TRACE_ERROR,(TSTR("**>>ecc error unfixed on chunk %d:1" TENDSTR),chunkInNAND));
222 if(nspare.eccres2 || nspare.eccres2)
224 // Hoosterman, we had a data problem on this page
225 yaffs_HandleReadDataError(dev,chunkInNAND);
234 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
238 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
239 static __u8 data[YAFFS_BYTES_PER_CHUNK];
240 static __u8 spare[16];
243 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
249 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
253 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) return YAFFS_FAIL;
254 if(memcmp(cmpbuf,spare,16)) return YAFFS_FAIL;
263 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
265 dev->nBlockErasures++;
266 return dev->eraseBlockInNAND(dev,blockInNAND);
269 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
271 return dev->initialiseNAND(dev);
274 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
281 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
285 chunk = yaffs_AllocateChunk(dev,useReserve);
290 // First check this chunk is erased...
291 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
292 writeOk = yaffs_CheckChunkErased(dev,chunk);
296 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs chunk %d was not erased" TENDSTR),chunk));
300 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
306 // If verify fails, then delete this chunk and try again
307 // To verify we compare everything except the block and
308 // page status bytes.
309 // NB We check a raw read without ECC correction applied
310 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare,0);
312 #ifndef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
313 if(!yaffs_VerifyCompare(data,rbData,spare,&rbSpare))
316 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write verify failed on chunk %d" TENDSTR), chunk));
325 // Copy the data into the write buffer.
326 // NB We do this at the end to prevent duplicates in the case of a write error.
328 yaffs_HandleWriteChunkOk(dev,chunk,data,spare);
332 yaffs_HandleWriteChunkError(dev,chunk);
336 } while(chunk >= 0 && ! writeOk);
340 T(YAFFS_TRACE_ERROR,(TSTR("**>> yaffs write required %d attempts" TENDSTR),attempts));
341 dev->nRetriedWrites+= (attempts - 1);
348 // Functions for robustisizing
352 static void yaffs_RetireBlock(yaffs_Device *dev,int blockInNAND)
354 // Ding the blockStatus in the first two pages of the block.
358 memset(&spare, 0xff,sizeof(yaffs_Spare));
360 spare.blockStatus = 0;
362 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK, NULL , &spare);
363 yaffs_WriteChunkToNAND(dev, blockInNAND * YAFFS_CHUNKS_PER_BLOCK + 1, NULL , &spare);
365 yaffs_GetBlockInfo(dev,blockInNAND)->blockState = YAFFS_BLOCK_STATE_DEAD;
366 dev->nRetiredBlocks++;
371 static int yaffs_RewriteBufferedBlock(yaffs_Device *dev)
373 dev->doingBufferedBlockRewrite = 1;
375 // Remove erased chunks
376 // Rewrite existing chunks to a new block
377 // Set current write block to the new block
379 dev->doingBufferedBlockRewrite = 0;
385 static void yaffs_HandleReadDataError(yaffs_Device *dev,int chunkInNAND)
387 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
389 // Mark the block for retirement
390 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
391 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>>Block %d marked for retirement" TENDSTR),blockInNAND));
395 // Just do a garbage collection on the affected block then retire the block
400 static void yaffs_CheckWrittenBlock(yaffs_Device *dev,int chunkInNAND)
404 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev,int chunkInNAND,const __u8 *data, const yaffs_Spare *spare)
408 static void yaffs_HandleUpdateChunk(yaffs_Device *dev,int chunkInNAND, const yaffs_Spare *spare)
412 static void yaffs_HandleWriteChunkError(yaffs_Device *dev,int chunkInNAND)
414 int blockInNAND = chunkInNAND/YAFFS_CHUNKS_PER_BLOCK;
416 // Mark the block for retirement
417 yaffs_GetBlockInfo(dev,blockInNAND)->needsRetiring = 1;
419 yaffs_DeleteChunk(dev,chunkInNAND);
425 static int yaffs_VerifyCompare(const __u8 *d0, const __u8 * d1, const yaffs_Spare *s0, const yaffs_Spare *s1)
429 if( memcmp(d0,d1,YAFFS_BYTES_PER_CHUNK) != 0 ||
430 s0->tagByte0 != s1->tagByte0 ||
431 s0->tagByte1 != s1->tagByte1 ||
432 s0->tagByte2 != s1->tagByte2 ||
433 s0->tagByte3 != s1->tagByte3 ||
434 s0->tagByte4 != s1->tagByte4 ||
435 s0->tagByte5 != s1->tagByte5 ||
436 s0->tagByte6 != s1->tagByte6 ||
437 s0->tagByte7 != s1->tagByte7 ||
438 s0->ecc1[0] != s1->ecc1[0] ||
439 s0->ecc1[1] != s1->ecc1[1] ||
440 s0->ecc1[2] != s1->ecc1[2] ||
441 s0->ecc2[0] != s1->ecc2[0] ||
442 s0->ecc2[1] != s1->ecc2[1] ||
443 s0->ecc2[2] != s1->ecc2[2] )
452 ///////////////////////// Object management //////////////////
453 // List of spare objects
454 // The list is hooked together using the first pointer
457 // static yaffs_Object *yaffs_freeObjects = NULL;
459 // static int yaffs_nFreeObjects;
461 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
463 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
466 static __u16 yaffs_CalcNameSum(const char *name)
471 __u8 *bname = (__u8 *)name;
474 while ((*bname) && (i <=YAFFS_MAX_NAME_LENGTH))
476 #ifdef CONFIG_YAFFS_WINCE
477 sum += toupper(*bname) * i;
488 void yaffs_SetObjectName(yaffs_Object *obj, const char *name)
490 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
491 if(name && strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
493 strcpy(obj->shortName,name);
497 obj->shortName[0]='\0';
500 obj->sum = yaffs_CalcNameSum(name);
503 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
505 nand_calculate_ecc (data , spare->ecc1);
506 nand_calculate_ecc (&data[256] , spare->ecc2);
509 void yaffs_CalcTagsECC(yaffs_Tags *tags)
513 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
520 for(i = 0; i < 8; i++)
522 for(j = 1; j &0xff; j<<=1)
537 int yaffs_CheckECCOnTags(yaffs_Tags *tags)
539 unsigned ecc = tags->ecc;
541 yaffs_CalcTagsECC(tags);
547 // TODO: Handle the failure better. Retire?
548 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
552 b[ecc / 8] ^= (1 << (ecc & 7));
554 // Now recvalc the ecc
555 yaffs_CalcTagsECC(tags);
557 return 1; // recovered error
561 // Wierd ecc failure value
562 // TODO Need to do somethiong here
563 return -1; //unrecovered error
570 ///////////////////////// TNODES ///////////////////////
572 // List of spare tnodes
573 // The list is hooked together using the first pointer
576 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
578 // static int yaffs_nFreeTnodes;
580 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
584 // yaffs_CreateTnodes creates a bunch more tnodes and
585 // adds them to the tnode free list.
586 // Don't use this function directly
588 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
591 yaffs_Tnode *newTnodes;
592 yaffs_TnodeList *tnl;
594 if(nTnodes < 1) return YAFFS_OK;
598 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
602 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not allocate Tnodes"TENDSTR)));
606 // Hook them into the free list
607 for(i = 0; i < nTnodes - 1; i++)
609 newTnodes[i].internal[0] = &newTnodes[i+1];
612 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
613 dev->freeTnodes = newTnodes;
614 dev->nFreeTnodes+= nTnodes;
615 dev->nTnodesCreated += nTnodes;
617 // Now add this bunch of tnodes to a list for freeing up.
618 // NB If we can't add this to the management list it isn't fatal
619 // but it just means we can't free this bunch of tnodes later.
620 tnl = YMALLOC(sizeof(yaffs_TnodeList));
623 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: Could not add tnodes to management list" TENDSTR)));
628 tnl->tnodes = newTnodes;
629 tnl->next = dev->allocatedTnodeList;
630 dev->allocatedTnodeList = tnl;
634 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Tnodes added" TENDSTR)));
641 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
642 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
644 yaffs_Tnode *tn = NULL;
646 // If there are none left make more
649 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
654 tn = dev->freeTnodes;
655 dev->freeTnodes = dev->freeTnodes->internal[0];
658 memset(tn,0,sizeof(yaffs_Tnode));
666 // FreeTnode frees up a tnode and puts it back on the free list
667 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
669 tn->internal[0] = dev->freeTnodes;
670 dev->freeTnodes = tn;
675 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
677 // Free the list of allocated tnodes
679 while(dev->allocatedTnodeList)
681 YFREE(dev->allocatedTnodeList->tnodes);
682 dev->allocatedTnodeList = dev->allocatedTnodeList->next;
685 dev->freeTnodes = NULL;
686 dev->nFreeTnodes = 0;
689 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
691 dev->allocatedTnodeList = NULL;
692 dev->freeTnodes = NULL;
693 dev->nFreeTnodes = 0;
694 dev->nTnodesCreated = 0;
699 void yaffs_TnodeTest(yaffs_Device *dev)
704 yaffs_Tnode *tn[1000];
706 YINFO("Testing TNodes");
708 for(j = 0; j < 50; j++)
710 for(i = 0; i < 1000; i++)
712 tn[i] = yaffs_GetTnode(dev);
715 YALERT("Getting tnode failed");
718 for(i = 0; i < 1000; i+=3)
720 yaffs_FreeTnode(dev,tn[i]);
729 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
731 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
732 // The look up tree is represented by the top tnode and the number of topLevel
733 // in the tree. 0 means only the level 0 tnode is in the tree.
736 // FindLevel0Tnode finds the level 0 tnode, if one exists.
737 // Used when reading.....
738 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
741 yaffs_Tnode *tn = fStruct->top;
743 int requiredTallness;
744 int level = fStruct->topLevel;
746 // Check sane level and chunk Id
747 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
750 // sprintf(str,"Bad level %d",level);
755 if(chunkId > YAFFS_MAX_CHUNK_ID)
758 // sprintf(str,"Bad chunkId %d",chunkId);
763 // First check we're tall enough (ie enough topLevel)
765 i = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
766 requiredTallness = 0;
769 i >>= YAFFS_TNODES_INTERNAL_BITS;
774 if(requiredTallness > fStruct->topLevel)
776 // Not tall enough, so we can't find it, return NULL.
781 // Traverse down to level 0
782 while (level > 0 && tn)
784 tn = tn->internal[(chunkId >>(/* dev->chunkGroupBits + */ YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
785 YAFFS_TNODES_INTERNAL_MASK];
793 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
794 // This happens in two steps:
795 // 1. If the tree isn't tall enough, then make it taller.
796 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
798 // Used when modifying the tree.
800 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
805 int requiredTallness;
812 //T((TSTR("AddOrFind topLevel=%d, chunk=%d"),fStruct->topLevel,chunkId));
814 // Check sane level and page Id
815 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
818 // sprintf(str,"Bad level %d",fStruct->topLevel);
823 if(chunkId > YAFFS_MAX_CHUNK_ID)
826 // sprintf(str,"Bad chunkId %d",chunkId);
831 // First check we're tall enough (ie enough topLevel)
833 x = chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS);
834 requiredTallness = 0;
837 x >>= YAFFS_TNODES_INTERNAL_BITS;
841 //T((TSTR(" required=%d"),requiredTallness));
844 if(requiredTallness > fStruct->topLevel)
846 // Not tall enough,gotta make the tree taller
847 for(i = fStruct->topLevel; i < requiredTallness; i++)
849 //T((TSTR(" add new top")));
851 tn = yaffs_GetTnode(dev);
855 tn->internal[0] = fStruct->top;
860 T(YAFFS_TRACE_ERROR,(TSTR("yaffs: no more tnodes" TENDSTR)));
864 fStruct->topLevel = requiredTallness;
868 // Traverse down to level 0, adding anything we need
870 l = fStruct->topLevel;
874 x = (chunkId >> (/*dev->chunkGroupBits + */YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
875 YAFFS_TNODES_INTERNAL_MASK;
877 //T((TSTR(" [%d:%d]"),l,i));
881 //T((TSTR(" added")));
883 tn->internal[x] = yaffs_GetTnode(dev);
886 tn = tn->internal[x];
896 // DeleteWorker scans backwards through the tnode tree and deletes all the
897 // chunks and tnodes in the file
898 // Returns 1 if the tree was deleted. Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
900 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level, int chunkOffset,int *limit)
916 for(i = YAFFS_NTNODES_INTERNAL -1; allDone && i >= 0; i--)
920 if(limit && (*limit) < 0)
926 allDone = yaffs_DeleteWorker(in,tn->internal[i],level - 1,
927 (chunkOffset << YAFFS_TNODES_INTERNAL_BITS ) + i ,limit);
931 yaffs_FreeTnode(in->myDev,tn->internal[i]);
932 tn->internal[i] = NULL;
937 return (allDone) ? 1 : 0;
941 for(i = YAFFS_NTNODES_LEVEL0 -1; i >= 0; i--) //NB Don't apply the limit here, always delete a whole level0
947 chunkInInode = (chunkOffset << YAFFS_TNODES_LEVEL0_BITS ) + i;
949 theChunk = tn->level0[i] << in->myDev->chunkGroupBits;
951 // Now we need to search for it
952 for(j = 0,found = 0; theChunk && j < in->myDev->chunkGroupSize && !found; j++)
954 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,&tags,&chunkDeleted);
955 if(yaffs_TagsMatch(&tags,in->objectId,chunkInInode,chunkDeleted))
969 yaffs_DeleteChunk(in->myDev,theChunk);
996 // Pruning removes any part of the file structure tree that is beyond the
997 // bounds of the file (ie that does not point to chunks).
999 // A file should only get pruned when its size is reduced.
1001 // Before pruning, the chunks must be pulled from the tree and the
1002 // level 0 tnode entries must be zeroed out.
1003 // Could also use this for file deletion, but that's probably better handled
1004 // by a special case.
1006 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
1008 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
1017 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
1019 if(tn->internal[i] && level > 0)
1021 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
1030 if(hasData == 0 && del0)
1032 // Free and return NULL
1034 yaffs_FreeTnode(dev,tn);
1044 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
1051 if(fStruct->topLevel > 0)
1053 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
1055 // Now we have a tree with all the non-zero branches NULL but the height
1056 // is the same as it was.
1057 // Let's see if we can trim internal tnodes to shorten the tree.
1058 // We can do this if only the 0th element in the tnode is in use
1059 // (ie all the non-zero are NULL)
1061 while(fStruct->topLevel && !done)
1066 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
1076 fStruct->top = tn->internal[0];
1077 fStruct->topLevel--;
1078 yaffs_FreeTnode(dev,tn);
1094 /////////////////////// End of File Structure functions. /////////////////
1096 // yaffs_CreateFreeObjects creates a bunch more objects and
1097 // adds them to the object free list.
1098 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1101 yaffs_Object *newObjects;
1102 yaffs_ObjectList *list;
1104 if(nObjects < 1) return YAFFS_OK;
1106 // make these things
1108 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1112 T(YAFFS_TRACE_ALLOCATE,(TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1116 // Hook them into the free list
1117 for(i = 0; i < nObjects - 1; i++)
1119 (yaffs_Object *)newObjects[i].siblings.next = &newObjects[i+1];
1122 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1123 dev->freeObjects = newObjects;
1124 dev->nFreeObjects+= nObjects;
1125 dev->nObjectsCreated+= nObjects;
1127 // Now add this bunch of Objects to a list for freeing up.
1129 list = YMALLOC(sizeof(yaffs_ObjectList));
1132 T(YAFFS_TRACE_ALLOCATE,(TSTR("Could not add objects to management list" TENDSTR)));
1136 list->objects = newObjects;
1137 list->next = dev->allocatedObjectList;
1138 dev->allocatedObjectList = list;
1147 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
1148 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1150 yaffs_Object *tn = NULL;
1152 // If there are none left make more
1153 if(!dev->freeObjects)
1155 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
1158 if(dev->freeObjects)
1160 tn = dev->freeObjects;
1161 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
1162 dev->nFreeObjects--;
1164 // Now sweeten it up...
1166 memset(tn,0,sizeof(yaffs_Object));
1169 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1170 INIT_LIST_HEAD(&(tn->hardLinks));
1171 INIT_LIST_HEAD(&(tn->hashLink));
1172 INIT_LIST_HEAD(&tn->siblings);
1174 // Add it to the lost and found directory.
1175 // NB Can't put root or lostNFound in lostNFound so
1176 // check if lostNFound exists first
1177 if(dev->lostNFoundDir)
1179 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
1187 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
1190 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
1193 obj->fake = 1; // it is fake so it has no NAND presence...
1194 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
1195 obj->unlinkAllowed= 0; // ... or unlink it
1198 obj->st_mode = mode;
1200 obj->chunkId = 0; // Not a valid chunk.
1208 static void yaffs_UnhashObject(yaffs_Object *tn)
1211 yaffs_Device *dev = tn->myDev;
1214 // If it is still linked into the bucket list, free from the list
1215 if(!list_empty(&tn->hashLink))
1217 list_del_init(&tn->hashLink);
1218 bucket = yaffs_HashFunction(tn->objectId);
1219 dev->objectBucket[bucket].count--;
1225 // FreeObject frees up a Object and puts it back on the free list
1226 static void yaffs_FreeObject(yaffs_Object *tn)
1229 yaffs_Device *dev = tn->myDev;
1231 yaffs_UnhashObject(tn);
1233 // Link into the free list.
1234 (yaffs_Object *)(tn->siblings.next) = dev->freeObjects;
1235 dev->freeObjects = tn;
1236 dev->nFreeObjects++;
1242 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
1244 // Free the list of allocated Objects
1246 while( dev->allocatedObjectList)
1248 YFREE(dev->allocatedObjectList->objects);
1249 dev->allocatedObjectList = dev->allocatedObjectList->next;
1252 dev->freeObjects = NULL;
1253 dev->nFreeObjects = 0;
1256 static void yaffs_InitialiseObjects(yaffs_Device *dev)
1260 dev->allocatedObjectList = NULL;
1261 dev->freeObjects = NULL;
1262 dev->nFreeObjects = 0;
1264 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
1266 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1267 dev->objectBucket[i].count = 0;
1277 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1282 int lowest = 999999;
1285 // First let's see if we can find one that's empty.
1287 for(i = 0; i < 10 && lowest > 0; i++)
1290 x %= YAFFS_NOBJECT_BUCKETS;
1291 if(dev->objectBucket[x].count < lowest)
1293 lowest = dev->objectBucket[x].count;
1299 // If we didn't find an empty list, then try
1300 // looking a bit further for a short one
1302 for(i = 0; i < 10 && lowest > 3; i++)
1305 x %= YAFFS_NOBJECT_BUCKETS;
1306 if(dev->objectBucket[x].count < lowest)
1308 lowest = dev->objectBucket[x].count;
1317 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1319 int bucket = yaffs_FindNiceObjectBucket(dev);
1321 // Now find an object value that has not already been taken
1322 // by scanning the list.
1325 struct list_head *i;
1327 __u32 n = (__u32)bucket;
1329 //yaffs_CheckObjectHashSanity();
1334 n += YAFFS_NOBJECT_BUCKETS;
1335 if(1 ||dev->objectBucket[bucket].count > 0)
1337 list_for_each(i,&dev->objectBucket[bucket].list)
1339 // If there is already one in the list
1340 if(list_entry(i, yaffs_Object,hashLink)->objectId == n)
1348 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
1353 void yaffs_HashObject(yaffs_Object *in)
1355 int bucket = yaffs_HashFunction(in->objectId);
1356 yaffs_Device *dev = in->myDev;
1358 if(!list_empty(&in->hashLink))
1364 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1365 dev->objectBucket[bucket].count++;
1369 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,__u32 number)
1371 int bucket = yaffs_HashFunction(number);
1372 struct list_head *i;
1375 list_for_each(i,&dev->objectBucket[bucket].list)
1377 // Look if it is in the list
1378 in = list_entry(i, yaffs_Object,hashLink);
1379 if(in->objectId == number)
1390 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1393 yaffs_Object *theObject;
1397 number = yaffs_CreateNewObjectNumber(dev);
1400 theObject = yaffs_AllocateEmptyObject(dev);
1404 theObject->fake = 0;
1405 theObject->renameAllowed = 1;
1406 theObject->unlinkAllowed = 1;
1407 theObject->objectId = number;
1408 yaffs_HashObject(theObject);
1409 theObject->variantType = type;
1410 #ifdef CONFIG_YAFFS_WINCE
1411 yfsd_WinFileTimeNow(theObject->win_atime);
1412 theObject->win_ctime[0] = theObject->win_mtime[0] = theObject->win_atime[0];
1413 theObject->win_ctime[1] = theObject->win_mtime[1] = theObject->win_atime[1];
1416 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1420 case YAFFS_OBJECT_TYPE_FILE:
1421 theObject->variant.fileVariant.fileSize = 0;
1422 theObject->variant.fileVariant.scannedFileSize = 0;
1423 theObject->variant.fileVariant.topLevel = 0;
1424 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1426 case YAFFS_OBJECT_TYPE_DIRECTORY:
1427 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1429 case YAFFS_OBJECT_TYPE_SYMLINK:
1430 // No action required
1432 case YAFFS_OBJECT_TYPE_HARDLINK:
1433 // No action required
1435 case YAFFS_OBJECT_TYPE_SPECIAL:
1436 // No action required
1438 case YAFFS_OBJECT_TYPE_UNKNOWN:
1439 // todo this should not happen
1447 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1449 yaffs_Object *theObject = NULL;
1453 theObject = yaffs_FindObjectByNumber(dev,number);
1458 theObject = yaffs_CreateNewObject(dev,number,type);
1465 char *yaffs_CloneString(const char *str)
1467 char *newStr = NULL;
1471 newStr = YMALLOC(strlen(str) + 1);
1480 // Mknod (create) a new object.
1481 // equivalentObject only has meaning for a hard link;
1482 // aliasString only has meaning for a sumlink.
1483 // rdev only has meaning for devices (a subset of special objects)
1484 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1485 yaffs_Object *parent,
1490 yaffs_Object *equivalentObject,
1491 const char *aliasString,
1496 yaffs_Device *dev = parent->myDev;
1498 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1499 if(yaffs_FindObjectByName(parent,name))
1504 in = yaffs_CreateNewObject(dev,-1,type);
1510 in->variantType = type;
1514 #ifdef CONFIG_YAFFS_WINCE
1515 yfsd_WinFileTimeNow(in->win_atime);
1516 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1517 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[0];
1520 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1525 in->nDataChunks = 0;
1527 yaffs_SetObjectName(in,name);
1530 yaffs_AddObjectToDirectory(parent,in);
1532 in->myDev = parent->myDev;
1537 case YAFFS_OBJECT_TYPE_SYMLINK:
1538 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1540 case YAFFS_OBJECT_TYPE_HARDLINK:
1541 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1542 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1543 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1545 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1546 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1547 case YAFFS_OBJECT_TYPE_SPECIAL: // do nothing
1548 case YAFFS_OBJECT_TYPE_UNKNOWN:
1552 if(yaffs_GetNumberOfFreeChunks(dev) <= 0 ||
1553 yaffs_UpdateObjectHeader(in,name,0) < 0)
1555 // Could not create the object header, fail the creation
1556 yaffs_UnlinkWorker(in);
1565 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1567 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL,0);
1570 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1572 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,0);
1575 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1577 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL,rdev);
1580 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1582 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias,0);
1585 // NB yaffs_Link returns the object id of the equivalent object.
1586 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1588 // Get the real object in case we were fed a hard link as an equivalent object
1589 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1591 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL,0))
1593 return equivalentObject;
1603 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName,int force)
1609 newDir = obj->parent; // use the old directory
1612 unlinkOp = (newDir == obj->myDev->unlinkedDir && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1614 // If the object is a file going into the unlinked directory, then it is OK to just stuff it in since
1615 // duplicate names are allowed.
1616 // Otherwise only proceed if the new name does not exist and if we're putting it into a directory.
1619 !yaffs_FindObjectByName(newDir,newName)) &&
1620 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1622 yaffs_SetObjectName(obj,newName);
1625 yaffs_AddObjectToDirectory(newDir,obj);
1627 if(unlinkOp) obj->unlinked = 1;
1630 if(yaffs_UpdateObjectHeader(obj,newName,0) >= 0)
1641 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1646 #ifdef CONFIG_YAFFS_WINCE
1647 // Special case for WinCE.
1648 // While look-up is case insensitive, the name isn't.
1649 // THerefore we might want to change x.txt to X.txt
1650 if(oldDir == newDir && _stricmp(oldName,newName) == 0)
1656 obj = yaffs_FindObjectByName(oldDir,oldName);
1657 if(obj && obj->renameAllowed)
1659 return yaffs_ChangeObjectName(obj,newDir,newName,force);
1666 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1668 // Scan the buckets and check that the lists
1669 // have as many members as the count says there are
1672 struct list_head *j;
1675 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1679 list_for_each(j,&dev->objectBucket[bucket].list)
1684 if(countEm != dev->objectBucket[bucket].count)
1686 T(YAFFS_TRACE_ERROR,(TSTR("Inode hash inconsistency" TENDSTR)));
1695 void yaffs_ObjectTest(yaffs_Device *dev)
1697 yaffs_Object *in[1000];
1699 yaffs_Object *inold[1000];
1703 memset(in,0,1000*sizeof(yaffs_Object *));
1704 memset(inold,0,1000*sizeof(yaffs_Object *));
1706 yaffs_CheckObjectHashSanity(dev);
1708 for(j = 0; j < 10; j++)
1712 for(i = 0; i < 1000; i++)
1714 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1717 YINFO("No more inodes");
1721 inNo[i] = in[i]->objectId;
1725 for(i = 0; i < 1000; i++)
1727 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1729 //T(("Differnce in look up test\n"));
1733 // T(("Look up ok\n"));
1737 yaffs_CheckObjectHashSanity(dev);
1739 for(i = 0; i < 1000; i+=3)
1741 yaffs_FreeObject(in[i]);
1746 yaffs_CheckObjectHashSanity(dev);
1753 /////////////////////////// Block Management and Page Allocation ///////////////////
1756 static int yaffs_InitialiseBlocks(yaffs_Device *dev,int nBlocks)
1758 dev->allocationBlock = -1; // force it to get a new one
1759 //Todo we're assuming the malloc will pass.
1760 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1763 memset(dev->blockInfo,0,nBlocks * sizeof(yaffs_BlockInfo));
1770 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1772 YFREE(dev->blockInfo);
1775 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1776 // for garbage collection.
1778 static int yaffs_FindDirtiestBlock(yaffs_Device *dev)
1781 int b = dev->currentDirtyChecker;
1785 int pagesInUse = 100; // silly big number
1786 yaffs_BlockInfo *bi;
1788 for(i = dev->startBlock; i <= dev->endBlock && pagesInUse > 2 ; i++)
1791 if ( b < dev->startBlock || b > dev->endBlock)
1793 b = dev->startBlock;
1796 if(b < dev->startBlock || b > dev->endBlock)
1798 T(YAFFS_TRACE_ERROR,(TSTR("**>> Block %d is not valid" TENDSTR),b));
1802 bi = yaffs_GetBlockInfo(dev,b);
1804 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1805 bi->pagesInUse < pagesInUse)
1808 pagesInUse = bi->pagesInUse;
1812 dev->currentDirtyChecker = b;
1818 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
1820 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,blockNo);
1824 // If the block is still healthy erase it and mark as clean.
1825 // If the block has had a data failure, then retire it.
1826 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1828 if(!bi->needsRetiring)
1830 erasedOk = yaffs_EraseBlockInNAND(dev,blockNo);
1833 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Erasure failed %d" TENDSTR),blockNo));
1839 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1840 dev->nErasedBlocks++;
1844 T(YAFFS_TRACE_ERASE,(TSTR("Erased block %d" TENDSTR),blockNo));
1848 yaffs_RetireBlock(dev,blockNo);
1849 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,(TSTR("**>> Block %d retired" TENDSTR),blockNo));
1854 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
1857 yaffs_BlockInfo *bi;
1859 if(dev->nErasedBlocks < 1)
1861 // Hoosterman we've got a problem.
1862 // Can't get space to gc
1863 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tradgedy: no space during gc" TENDSTR)));
1868 // Find an empty block.
1870 for(i = dev->startBlock; i <= dev->endBlock; i++)
1872 bi = yaffs_GetBlockInfo(dev,i);
1873 if(bi->blockState == YAFFS_BLOCK_STATE_EMPTY)
1875 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1876 dev->nErasedBlocks--;
1886 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
1889 yaffs_BlockInfo *bi;
1891 if(dev->allocationBlock < 0)
1893 // Get next block to allocate off
1894 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
1895 dev->allocationPage = 0;
1898 if(!useReserve && dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
1900 // Not enough space to allocate unless we're allowed to use the reserve.
1904 // Next page please....
1905 if(dev->allocationBlock >= 0)
1907 bi = yaffs_GetBlockInfo(dev,dev->allocationBlock);
1909 retVal = (dev->allocationBlock * YAFFS_CHUNKS_PER_BLOCK) +
1910 dev->allocationPage;
1912 bi->pageBits |= (1 << (dev->allocationPage));
1914 dev->allocationPage++;
1918 // If the block is full set the state to full
1919 if(dev->allocationPage >= YAFFS_CHUNKS_PER_BLOCK)
1921 bi->blockState = YAFFS_BLOCK_STATE_FULL;
1922 dev->allocationBlock = -1;
1929 T(YAFFS_TRACE_ERROR,(TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
1934 // To determine if we have enough space we just look at the
1935 // number of erased blocks.
1936 // The cache is allowed to use reserved blocks.
1938 int yaffs_CheckSpaceForChunkCache(yaffs_Device *dev)
1940 return (dev->nErasedBlocks >= YAFFS_RESERVED_BLOCKS);
1944 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
1953 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
1955 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,block);
1957 yaffs_Object *object;
1959 //T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
1961 for(mask = 1,oldChunk = block * YAFFS_CHUNKS_PER_BLOCK;
1962 mask && bi->pageBits;
1963 mask <<= 1, oldChunk++ )
1965 if(bi->pageBits & mask)
1968 // This page is in use and needs to be copied off
1972 //T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
1974 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare,1);
1976 yaffs_GetTagsFromSpare(dev,&spare,&tags);
1978 object = yaffs_FindObjectByNumber(dev,tags.objectId);
1980 if(object && object->deleted && tags.chunkId != 0)
1982 // Data chunk in a deleted file, throw it away
1983 // It's a deleted data chunk,
1984 // No need to copy this, just forget about it and fix up the
1987 yaffs_PutChunkIntoFile(object, tags.chunkId, 0,0);
1988 object->nDataChunks--;
1990 else if( 0 /* Todo object && object->deleted && object->nDataChunks == 0 */)
1992 // Deleted object header with no data chunks.
1994 object->chunkId = 0;
1995 //Todo some clean up
2000 // It's either a data chunk in a live file or
2001 // an ObjectHeader, so we're interested in it.
2002 // NB Need to keep the ObjectHeaders of deleted files
2003 // until the whole file has been deleted off
2004 tags.serialNumber++;
2005 yaffs_LoadTagsIntoSpare(&spare,&tags);
2008 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
2015 // Ok, now fix up the Tnodes etc.
2017 if(tags.chunkId == 0)
2020 object->chunkId = newChunk;
2024 // It's a data chunk
2025 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
2029 yaffs_DeleteChunk(dev,oldChunk);
2038 static yaffs_Object *yaffs_FindDeletedUnlinkedFile(yaffs_Device *dev)
2040 // todo find a file to delete
2041 struct list_head *i;
2045 // To the free chunks add the chunks that are in the deleted unlinked files.
2046 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
2048 l = list_entry(i, yaffs_Object,siblings);
2057 static void yaffs_DoUnlinkedFileDeletion(yaffs_Device *dev)
2059 // This does background deletion on unlinked files.. only deleted ones.
2060 // If we don't have a file we're working on then find one
2061 if(!dev->unlinkedDeletion && dev->nDeletedFiles > 0)
2063 dev->unlinkedDeletion = yaffs_FindDeletedUnlinkedFile(dev);
2066 // OK, we're working on a file...
2067 if(dev->unlinkedDeletion)
2069 yaffs_Object *obj = dev->unlinkedDeletion;
2071 int limit; // Number of chunks to delete in a file.
2072 // NB this can be exceeded, but not by much.
2076 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2078 limit = 50; // Doing GC soon, so dig deeper
2086 delresult = yaffs_DeleteWorker(obj, obj->variant.fileVariant.top, obj->variant.fileVariant.topLevel, 0,&limit);
2088 if(obj->nDataChunks == 0)
2090 // Done all the deleting of data chunks.
2091 // Now dump the header and clean up
2092 yaffs_FreeTnode(dev,obj->variant.fileVariant.top);
2093 yaffs_DoGenericObjectDeletion(obj);
2094 dev->nDeletedFiles--;
2095 dev->nUnlinkedFiles--;
2096 dev->nBackgroundDeletions++;
2097 dev->unlinkedDeletion = NULL;
2104 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
2108 yaffs_DoUnlinkedFileDeletion(dev);
2110 if(dev->nErasedBlocks <= (YAFFS_RESERVED_BLOCKS + YAFFS_GARBAGE_COLLECT_LOW_WATER))
2112 dev->garbageCollectionRequired = 1;
2115 if(dev->garbageCollectionRequired)
2117 dev->garbageCollections++;
2118 dev->garbageCollectionRequired = 0;
2119 if(dev->blockSelectedForGC >= 0)
2121 block = dev->blockSelectedForGC;
2125 block = yaffs_FindDirtiestBlock(dev);
2130 return yaffs_GarbageCollectBlock(dev,block);
2142 //////////////////////////// TAGS ///////////////////////////////////////
2144 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
2146 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2148 yaffs_CalcTagsECC(tagsPtr);
2150 sparePtr->tagByte0 = tu->asBytes[0];
2151 sparePtr->tagByte1 = tu->asBytes[1];
2152 sparePtr->tagByte2 = tu->asBytes[2];
2153 sparePtr->tagByte3 = tu->asBytes[3];
2154 sparePtr->tagByte4 = tu->asBytes[4];
2155 sparePtr->tagByte5 = tu->asBytes[5];
2156 sparePtr->tagByte6 = tu->asBytes[6];
2157 sparePtr->tagByte7 = tu->asBytes[7];
2160 static void yaffs_GetTagsFromSpare(yaffs_Device *dev, yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
2162 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
2165 tu->asBytes[0]= sparePtr->tagByte0;
2166 tu->asBytes[1]= sparePtr->tagByte1;
2167 tu->asBytes[2]= sparePtr->tagByte2;
2168 tu->asBytes[3]= sparePtr->tagByte3;
2169 tu->asBytes[4]= sparePtr->tagByte4;
2170 tu->asBytes[5]= sparePtr->tagByte5;
2171 tu->asBytes[6]= sparePtr->tagByte6;
2172 tu->asBytes[7]= sparePtr->tagByte7;
2174 result = yaffs_CheckECCOnTags(tagsPtr);
2177 dev->tagsEccFixed++;
2181 dev->tagsEccUnfixed++;
2185 static void yaffs_SpareInitialise(yaffs_Spare *spare)
2187 memset(spare,0xFF,sizeof(yaffs_Spare));
2190 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags, int *chunkDeleted)
2195 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare,1) == YAFFS_OK)
2197 *chunkDeleted = (yaffs_CountBits(spare.pageStatus) < 7) ? 1 : 0;
2198 yaffs_GetTagsFromSpare(dev,&spare,tags);
2211 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
2213 // NB There must be tags, data is optional
2214 // If there is data, then an ECC is calculated on it.
2223 yaffs_SpareInitialise(&spare);
2225 #ifndef CONFIG_YAFFS_USE_NANDECC
2228 yaffs_CalcECC(buffer,&spare);
2232 yaffs_LoadTagsIntoSpare(&spare,tags);
2234 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
2240 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
2242 // NB There must be tags, data is optional
2243 // If there is data, then an ECC is calculated on it.
2252 yaffs_SpareInitialise(&spare);
2254 #ifndef CONFIG_YAFFS_USE_NANDECC
2258 yaffs_CalcECC(buffer,&spare);
2262 yaffs_LoadTagsIntoSpare(&spare,tags);
2264 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
2268 static int yaffs_TagsMatch(const yaffs_Tags *tags, int objectId, int chunkInObject, int chunkDeleted)
2270 return ( tags->chunkId == chunkInObject &&
2271 tags->objectId == objectId &&
2272 !chunkDeleted) ? 1 : 0;
2278 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2280 //Get the Tnode, then get the level 0 offset chunk offset
2283 yaffs_Tags localTags;
2288 yaffs_Device *dev = in->myDev;
2293 // Passed a NULL, so use our own tags space
2297 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2301 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2303 // Now we need to do the shifting etc and search for it
2304 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2306 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2307 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2318 return found ? theChunk : -1;
2321 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
2323 //Get the Tnode, then get the level 0 offset chunk offset
2326 yaffs_Tags localTags;
2329 yaffs_Device *dev = in->myDev;
2334 // Passed a NULL, so use our own tags space
2338 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2343 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
2345 // Now we need to do the shifting etc and search for it
2346 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
2348 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags,&chunkDeleted);
2349 if(yaffs_TagsMatch(tags,in->objectId,chunkInInode,chunkDeleted))
2360 // Delete the entry in the filestructure
2363 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2368 //T(("No level 0 found for %d\n", chunkInInode));
2373 //T(("Could not find %d to delete\n",chunkInInode));
2375 return found ? theChunk : -1;
2379 #ifdef YAFFS_PARANOID
2381 static int yaffs_CheckFileSanity(yaffs_Object *in)
2389 yaffs_Tags localTags;
2390 yaffs_Tags *tags = &localTags;
2395 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2397 //T(("Object not a file\n"));
2401 objId = in->objectId;
2402 fSize = in->variant.fileVariant.fileSize;
2403 nChunks = (fSize + YAFFS_BYTES_PER_CHUNK -1)/YAFFS_BYTES_PER_CHUNK;
2405 for(chunk = 1; chunk <= nChunks; chunk++)
2407 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
2412 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
2415 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags,&chunkDeleted);
2416 if(yaffs_TagsMatch(tags,in->objectId,chunk,chunkDeleted))
2423 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
2424 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
2433 //T(("No level 0 found for %d\n", chunk));
2437 return failed ? YAFFS_FAIL : YAFFS_OK;
2442 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
2445 yaffs_Device *dev = in->myDev;
2447 yaffs_Tags existingTags;
2449 unsigned existingSerial, newSerial;
2451 int newChunkDeleted;
2454 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
2460 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2464 // If we're scanning then we need to test for duplicates
2465 // NB This does not need to be efficient since it should only ever
2466 // happen when the power fails during a write, then only one
2467 // chunk should ever be affected.
2470 if(existingChunk != 0)
2472 // NB Right now existing chunk will not be real chunkId if the device >= 32MB
2473 // thus we have to do a FindChunkInFile to get the real chunk id.
2475 // We have a duplicate now we need to decide which one to use
2476 // To do this we get both sets of tags and compare serial numbers.
2477 yaffs_ReadChunkTagsFromNAND(dev,chunkInNAND, &newTags,&newChunkDeleted);
2481 existingChunk = yaffs_FindChunkInFile(in,chunkInInode, &existingTags);
2483 if(existingChunk <=0)
2485 //Hoosterman - how did this happen?
2487 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tradgedy: existing chunk < 0 in scan" TENDSTR)));
2492 // NB The deleted flags should be false, otherwise the chunks will
2493 // not be loaded during a scan
2495 newSerial = newTags.serialNumber;
2496 existingSerial = existingTags.serialNumber;
2498 if( existingChunk <= 0 ||
2499 ((existingSerial+1) & 3) == newSerial)
2502 // Delete the old one and drop through to update the tnode
2503 yaffs_DeleteChunk(dev,existingChunk);
2508 // Delete the new one and return early so that the tnode isn't changed
2509 yaffs_DeleteChunk(dev,chunkInNAND);
2516 if(existingChunk == 0)
2521 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = (chunkInNAND >> dev->chunkGroupBits);
2528 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
2530 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
2532 if(chunkInNAND >= 0)
2534 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL,1);
2544 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId)
2549 yaffs_BlockInfo *bi;
2551 if(chunkId <= 0) return;
2553 block = chunkId / YAFFS_CHUNKS_PER_BLOCK;
2554 page = chunkId % YAFFS_CHUNKS_PER_BLOCK;
2555 yaffs_SpareInitialise(&spare);
2557 spare.pageStatus = 0; // To mark it as deleted.
2560 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
2561 yaffs_HandleUpdateChunk(dev,chunkId,&spare);
2562 bi = yaffs_GetBlockInfo(dev,block);
2565 // Pull out of the management area.
2566 // If the whole block became dirty, this will kick off an erasure.
2567 if( bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2568 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2572 bi->pageBits &= ~(1 << page);
2575 if(bi->pagesInUse == 0 &&
2576 bi->blockState == YAFFS_BLOCK_STATE_FULL)
2578 yaffs_BlockBecameDirty(dev,block);
2584 // T(("Bad news deleting chunk %d\n",chunkId));
2592 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
2594 // Find old chunk Need to do this to get serial number
2595 // Write new one and patch into tree.
2596 // Invalidate old tags.
2599 yaffs_Tags prevTags;
2604 yaffs_Device *dev = in->myDev;
2606 yaffs_CheckGarbageCollection(dev);
2608 // Get the previous chunk at this location in the file if it exists
2609 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
2612 newTags.chunkId = chunkInInode;
2613 newTags.objectId = in->objectId;
2614 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2615 newTags.byteCount = nBytes;
2616 newTags.unusedStuff = 0xFFFFFFFF;
2618 yaffs_CalcTagsECC(&newTags);
2620 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2623 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2626 if(prevChunkId >= 0)
2628 yaffs_DeleteChunk(dev,prevChunkId);
2632 yaffs_CheckFileSanity(in);
2643 // UpdateObjectHeader updates the header on NAND for an object.
2644 // If name is not NULL, then that new name is used.
2646 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name, int force)
2649 yaffs_Device *dev = in->myDev;
2655 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2656 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2658 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2659 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2662 if(!in->fake || force)
2665 yaffs_CheckGarbageCollection(dev);
2667 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2669 prevChunkId = in->chunkId;
2671 if(prevChunkId >= 0)
2673 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL,1);
2677 oh->type = in->variantType;
2679 oh->st_mode = in->st_mode;
2681 #ifdef CONFIG_YAFFS_WINCE
2682 oh->win_atime[0] = in->win_atime[0];
2683 oh->win_ctime[0] = in->win_ctime[0];
2684 oh->win_mtime[0] = in->win_mtime[0];
2685 oh->win_atime[1] = in->win_atime[1];
2686 oh->win_ctime[1] = in->win_ctime[1];
2687 oh->win_mtime[1] = in->win_mtime[1];
2689 oh->st_uid = in->st_uid;
2690 oh->st_gid = in->st_gid;
2691 oh->st_atime = in->st_atime;
2692 oh->st_mtime = in->st_mtime;
2693 oh->st_ctime = in->st_ctime;
2694 oh->st_rdev = in->st_rdev;
2698 oh->parentObjectId = in->parent->objectId;
2702 oh->parentObjectId = 0;
2705 //oh->sum = in->sum;
2708 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2709 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
2711 else if(prevChunkId)
2713 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
2717 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2720 switch(in->variantType)
2722 case YAFFS_OBJECT_TYPE_UNKNOWN:
2723 // Should not happen
2725 case YAFFS_OBJECT_TYPE_FILE:
2726 oh->fileSize = in->variant.fileVariant.fileSize;
2728 case YAFFS_OBJECT_TYPE_HARDLINK:
2729 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
2731 case YAFFS_OBJECT_TYPE_SPECIAL:
2734 case YAFFS_OBJECT_TYPE_DIRECTORY:
2737 case YAFFS_OBJECT_TYPE_SYMLINK:
2738 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
2739 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2745 newTags.chunkId = 0;
2746 newTags.objectId = in->objectId;
2747 newTags.serialNumber = in->serial;
2748 newTags.byteCount = 0xFFFFFFFF;
2749 newTags.unusedStuff = 0xFFFFFFFF;
2751 yaffs_CalcTagsECC(&newTags);
2754 // Create new chunk in NAND
2755 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags,1);
2760 in->chunkId = newChunkId;
2762 if(prevChunkId >= 0)
2764 yaffs_DeleteChunk(dev,prevChunkId);
2777 /////////////////////// Short Operations Cache ////////////////////////////////
2778 // In many siturations where there is no high level buffering (eg WinCE) a lot of
2779 // reads might be short sequential reads, and a lot of writes may be short
2780 // sequential writes. eg. scanning/writing a jpeg file.
2781 // In these cases, a short read/write cache can provide a huge perfomance benefit
2782 // with dumb-as-a-rock code.
2783 // There are a limited number (~10) of cache chunks per device so that we don't
2784 // need a very intelligent search.
2787 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
2790 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
2792 yaffs_Device *dev = obj->myDev;
2795 yaffs_ChunkCache *cache;
2802 // Find the dirty cache for this object with the lowest chunk id.
2803 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2805 if(dev->srCache[i].object == obj &&
2806 dev->srCache[i].dirty)
2808 if(!cache || dev->srCache[i].chunkId < lowest)
2810 cache = &dev->srCache[i];
2811 lowest = cache->chunkId;
2820 nBytes = cache->object->variant.fileVariant.fileSize - ((cache->chunkId -1) * YAFFS_BYTES_PER_CHUNK);
2822 if(nBytes > YAFFS_BYTES_PER_CHUNK)
2824 nBytes= YAFFS_BYTES_PER_CHUNK;
2827 chunkWritten = yaffs_WriteChunkDataToObject(cache->object,
2835 } while(cache && chunkWritten > 0);
2839 //Hoosterman, disk full while writing cache out.
2840 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tradgedy: no space during caceh write" TENDSTR)));
2847 // Grab us a chunk for use.
2848 // First look for an empty one.
2849 // Then look for the least recently used non-dirty one.
2850 // Then look for the least recently used dirty one...., flush and look again.
2851 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
2857 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2859 if(!dev->srCache[i].object)
2861 //T(("Grabbing empty %d\n",i));
2863 return &dev->srCache[i];
2868 usage = 0; // just to stop the compiler grizzling
2870 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2872 if(!dev->srCache[i].dirty &&
2873 ((dev->srCache[i].lastUse < usage && theOne >= 0)||
2876 usage = dev->srCache[i].lastUse;
2881 //T(("Grabbing non-empty %d\n",theOne));
2882 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
2887 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
2889 yaffs_ChunkCache *cache;
2890 yaffs_Object *theObj;
2894 // Try find a non-dirty one...
2896 cache = yaffs_GrabChunkCacheWorker(dev);
2900 // They were all dirty, find the last recently used object and flush
2901 // its cache, then find again.
2902 // NB what's here is not very accurate, we actually flush the object
2903 // the last recently used page.
2905 theObj = dev->srCache[0].object;
2906 usage = dev->srCache[0].lastUse;
2908 for(i = 1; i < YAFFS_N_CACHE_CHUNKS; i++)
2910 if( dev->srCache[i].object &&
2911 dev->srCache[i].lastUse < usage)
2913 usage = dev->srCache[i].lastUse;
2914 theObj = dev->srCache[i].object;
2918 yaffs_FlushFilesChunkCache(theObj);
2921 cache = yaffs_GrabChunkCacheWorker(dev);
2929 // Find a cached chunk
2930 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj, int chunkId)
2932 yaffs_Device *dev = obj->myDev;
2935 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2937 if(dev->srCache[i].object == obj &&
2938 dev->srCache[i].chunkId == chunkId)
2942 return &dev->srCache[i];
2949 // Mark the chunk for the least recently used algorithym
2950 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache, int isAWrite)
2952 if( dev->srLastUse < 0 ||
2953 dev->srLastUse > 100000000)
2955 // Reset the cache usages
2957 for(i = 1; i < YAFFS_N_CACHE_CHUNKS; i++)
2959 dev->srCache[i].lastUse = 0;
2966 cache->lastUse = dev->srLastUse;
2974 // Invalidate a single cache page.
2975 // Do this when a whole page gets written,
2976 // ie the short cache for this page is no longer valid.
2977 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
2979 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object,chunkId);
2983 cache->object = NULL;
2988 // Invalidate all the cache pages associated with this object
2989 // Do this whenever ther file is deleted or resized.
2990 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
2993 yaffs_Device *dev = in->myDev;
2995 // Now invalidate it.
2996 for(i = 0; i < YAFFS_N_CACHE_CHUNKS; i++)
2998 if(dev->srCache[i].object == in)
3000 dev->srCache[i].object = NULL;
3007 // Stubs for disabling short op caching
3009 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3012 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3018 static yaffs_ChunkCache *yaffs_FindChunkCache(yaffs_Device *dev, int objectId, int chunkId)
3023 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache)
3027 static void yaffs_InvalidateChunkCache(yaffs_Object *obj, int chunkId)
3031 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3041 ///////////////////////// File read/write ///////////////////////////////
3042 // Read and write have very similar structures.
3043 // In general the read/write has three parts to it
3044 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3045 // * Some complete chunks
3046 // * An incomplete chunk to end off with
3048 // Curve-balls: the first chunk might also be the last chunk.
3050 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
3066 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
3067 start = offset % YAFFS_BYTES_PER_CHUNK;
3069 // OK now check for the curveball where the start and end are in
3071 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3077 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3080 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3082 // An incomplete start or end chunk (or maybe both start and end chunk)
3083 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
3084 yaffs_ChunkCache *cache;
3085 // If we can't find the data in the cache, then load it up.
3086 cache = yaffs_FindChunkCache(in,chunk);
3089 cache = yaffs_GrabChunkCache(in->myDev);
3091 cache->chunkId = chunk;
3093 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3096 yaffs_UseChunkCache(dev,cache,0);
3098 memcpy(buffer,&cache->data[start],nToCopy);
3100 // Read into the local buffer then copy...
3101 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3102 memcpy(buffer,&dev->localBuffer[start],nToCopy);
3107 #ifdef CONFIG_YAFFS_WINCE
3109 // Under WinCE can't do direct transfer. Need to use a local buffer.
3110 // This is because we otherwise screw up WinCE's memory mapper
3111 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3112 memcpy(buffer,dev->localBuffer,YAFFS_BYTES_PER_CHUNK);
3114 // A full chunk. Read directly into the supplied buffer.
3115 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
3131 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
3140 int startOfWrite = offset;
3141 int chunkWritten = 0;
3149 while(n > 0 && chunkWritten >= 0)
3151 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
3152 start = offset % YAFFS_BYTES_PER_CHUNK;
3155 // OK now check for the curveball where the start and end are in
3158 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
3162 // Now folks, to calculate how many bytes to write back....
3163 // If we're overwriting and not writing to then end of file then
3164 // we need to write back as much as was there before.
3166 nBytesRead = in->variant.fileVariant.fileSize - ((chunk -1) * YAFFS_BYTES_PER_CHUNK);
3168 if(nBytesRead > YAFFS_BYTES_PER_CHUNK)
3170 nBytesRead = YAFFS_BYTES_PER_CHUNK;
3173 nToWriteBack = (nBytesRead > (start + n)) ? nBytesRead : (start +n);
3178 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
3179 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
3182 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
3184 // An incomplete start or end chunk (or maybe both start and end chunk)
3185 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
3186 yaffs_ChunkCache *cache;
3187 // If we can't find the data in the cache, then load it up.
3188 cache = yaffs_FindChunkCache(in,chunk);
3189 if(!cache && yaffs_CheckSpaceForChunkCache(in->myDev))
3191 cache = yaffs_GrabChunkCache(in->myDev);
3193 cache->chunkId = chunk;
3195 yaffs_ReadChunkDataFromObject(in,chunk,cache->data);
3200 yaffs_UseChunkCache(dev,cache,1);
3201 memcpy(&cache->data[start],buffer,nToCopy);
3205 chunkWritten = -1; // fail the write
3210 // An incomplete start or end chunk (or maybe both start and end chunk)
3211 // Read into the local buffer then copy, then copy over and write back.
3213 yaffs_ReadChunkDataFromObject(in,chunk,dev->localBuffer);
3215 memcpy(&dev->localBuffer[start],buffer,nToCopy);
3217 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,nToWriteBack,0);
3219 //T(("Write with readback to chunk %d %d start %d copied %d wrote back %d\n",chunk,chunkWritten,start, nToCopy, nToWriteBack));
3226 #ifdef CONFIG_YAFFS_WINCE
3227 // Under WinCE can't do direct transfer. Need to use a local buffer.
3228 // This is because we otherwise screw up WinCE's memory mapper
3229 memcpy(dev->localBuffer,buffer,YAFFS_BYTES_PER_CHUNK);
3230 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,dev->localBuffer,YAFFS_BYTES_PER_CHUNK,0);
3232 // A full chunk. Write directly from the supplied buffer.
3233 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
3235 // Since we've overwritten the cached data, we better invalidate it.
3236 yaffs_InvalidateChunkCache(in,chunk);
3237 //T(("Write to chunk %d %d\n",chunk,chunkWritten));
3240 if(chunkWritten >= 0)
3250 // Update file object
3252 if((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3254 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3263 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
3267 int oldFileSize = in->variant.fileVariant.fileSize;
3268 int sizeOfPartialChunk = newSize % YAFFS_BYTES_PER_CHUNK;
3270 yaffs_Device *dev = in->myDev;
3273 yaffs_FlushFilesChunkCache(in);
3274 yaffs_InvalidateWholeChunkCache(in);
3276 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
3278 return yaffs_GetFileSize(in);
3281 if(newSize < oldFileSize)
3284 int lastDel = 1 + (oldFileSize-1)/YAFFS_BYTES_PER_CHUNK;
3286 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
3287 YAFFS_BYTES_PER_CHUNK;
3289 // Delete backwards so that we don't end up with holes if
3290 // power is lost part-way through the operation.
3291 for(i = lastDel; i >= startDel; i--)
3293 // NB this could be optimised somewhat,
3294 // eg. could retrieve the tags and write them without
3295 // using yaffs_DeleteChunk
3297 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
3298 if(chunkId <= 0 || chunkId >= (dev->endBlock * 32))
3300 //T(("Found daft chunkId %d for %d\n",chunkId,i));
3305 yaffs_DeleteChunk(dev,chunkId);
3310 if(sizeOfPartialChunk != 0)
3312 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
3314 // Got to read and rewrite the last chunk with its new size.
3315 yaffs_ReadChunkDataFromObject(in,lastChunk,dev->localBuffer);
3317 yaffs_WriteChunkDataToObject(in,lastChunk,dev->localBuffer,sizeOfPartialChunk,1);
3321 in->variant.fileVariant.fileSize = newSize;
3323 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
3335 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3337 obj = yaffs_GetEquivalentObject(obj);
3339 switch(obj->variantType)
3341 case YAFFS_OBJECT_TYPE_FILE:
3342 return obj->variant.fileVariant.fileSize;
3343 case YAFFS_OBJECT_TYPE_SYMLINK:
3344 return strlen(obj->variant.symLinkVariant.alias);
3352 // yaffs_FlushFile() updates the file's
3355 int yaffs_FlushFile(yaffs_Object *in)
3360 //T(("flushing object header\n"));
3362 yaffs_FlushFilesChunkCache(in);
3364 #ifdef CONFIG_YAFFS_WINCE
3365 yfsd_WinFileTimeNow(in->win_mtime);
3367 in->st_mtime = CURRENT_TIME;
3370 retVal = yaffs_UpdateObjectHeader(in,NULL,0);
3382 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3385 // First off, invalidate the file's data in the cache, without flushing.
3386 yaffs_InvalidateWholeChunkCache(in);
3388 yaffs_RemoveObjectFromDirectory(in);
3389 yaffs_DeleteChunk(in->myDev,in->chunkId);
3393 in->myInode->u.generic_ip = NULL;
3397 yaffs_FreeObject(in);
3402 // yaffs_DeleteFile deletes the whole file data
3403 // and the inode associated with the file.
3404 // It does not delete the links associated with the file.
3405 static int yaffs_UnlinkFile(yaffs_Object *in)
3408 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND_DELETION
3409 // Delete the file data & tnodes
3411 yaffs_DeleteWorker(in, in->variant.fileVariant.top, in->variant.fileVariant.topLevel, 0,NULL);
3414 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
3416 return yaffs_DoGenericObjectDeletion(in);
3419 int immediateDeletion=0;
3420 retVal = yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,NULL,0);
3421 if(retVal == YAFFS_OK)
3424 //in->myDev->nUnlinkedFiles++;
3425 //in->renameAllowed = 0;
3429 immediateDeletion = 1;
3433 #ifdef CONFIG_YAFFS_WINCE
3436 immediateDeletion = 1;
3441 if(immediateDeletion)
3443 T(YAFFS_TRACE_TRACING,(TSTR("yaffs: immediate deletion of file %d" TENDSTR),in->objectId));
3445 in->myDev->nDeletedFiles++;
3455 int yaffs_DeleteFile(yaffs_Object *in)
3457 int retVal = YAFFS_OK;
3460 retVal = yaffs_UnlinkFile(in);
3462 if(retVal == YAFFS_OK &&
3467 in->myDev->nDeletedFiles++;
3469 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3472 static int yaffs_DeleteDirectory(yaffs_Object *in)
3474 //First check that the directory is empty.
3475 if(list_empty(&in->variant.directoryVariant.children))
3477 return yaffs_DoGenericObjectDeletion(in);
3484 static int yaffs_DeleteSymLink(yaffs_Object *in)
3486 YFREE(in->variant.symLinkVariant.alias);
3488 return yaffs_DoGenericObjectDeletion(in);
3491 static int yaffs_DeleteHardLink(yaffs_Object *in)
3493 // remove this hardlink from the list assocaited with the equivalent
3495 list_del(&in->hardLinks);
3496 return yaffs_DoGenericObjectDeletion(in);
3500 static int yaffs_UnlinkWorker(yaffs_Object *obj)
3504 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3506 return yaffs_DeleteHardLink(obj);
3508 else if(!list_empty(&obj->hardLinks))
3510 // Curve ball: We're unlinking an object that has a hardlink.
3512 // This problem arises because we are not strictly following
3513 // The Linux link/inode model.
3515 // We can't really delete the object.
3516 // Instead, we do the following:
3517 // - Select a hardlink.
3518 // - Unhook it from the hard links
3519 // - Unhook it from its parent directory (so that the rename can work)
3520 // - Rename the object to the hardlink's name.
3521 // - Delete the hardlink
3526 char name[YAFFS_MAX_NAME_LENGTH+1];
3528 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
3530 list_del_init(&hl->hardLinks);
3531 list_del_init(&hl->siblings);
3533 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
3535 retVal = yaffs_ChangeObjectName(obj, hl->parent, name,0);
3537 if(retVal == YAFFS_OK)
3539 retVal = yaffs_DoGenericObjectDeletion(hl);
3546 switch(obj->variantType)
3548 case YAFFS_OBJECT_TYPE_FILE:
3549 return yaffs_UnlinkFile(obj);
3551 case YAFFS_OBJECT_TYPE_DIRECTORY:
3552 return yaffs_DeleteDirectory(obj);
3554 case YAFFS_OBJECT_TYPE_SYMLINK:
3555 return yaffs_DeleteSymLink(obj);
3557 case YAFFS_OBJECT_TYPE_HARDLINK:
3558 case YAFFS_OBJECT_TYPE_UNKNOWN:
3565 int yaffs_Unlink(yaffs_Object *dir, const char *name)
3569 obj = yaffs_FindObjectByName(dir,name);
3571 if(obj && obj->unlinkAllowed)
3573 return yaffs_UnlinkWorker(obj);
3580 //////////////// Initialisation Scanning /////////////////
3584 // For now we use the SmartMedia check.
3585 // We look at the blockStatus byte in the first two chunks
3586 // These must be 0xFF to pass as OK.
3587 // todo: this function needs to be modifyable foir different NAND types
3588 // and different chunk sizes. Suggest make this into a per-device configurable
3590 static int yaffs_IsBlockBad(yaffs_Device *dev, int blk)
3594 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK,NULL,&spare,1);
3596 if(yaffs_CountBits(spare.blockStatus) < 7)
3601 if(spare.blockStatus != 0xFF)
3606 yaffs_ReadChunkFromNAND(dev,blk * YAFFS_CHUNKS_PER_BLOCK + 1,NULL,&spare,1);
3609 if(yaffs_CountBits(spare.blockStatus) < 7)
3614 if(spare.blockStatus != 0xFF)
3624 static int yaffs_Scan(yaffs_Device *dev)
3632 yaffs_BlockState state;
3633 yaffs_Object *hardList = NULL;
3635 yaffs_BlockInfo *bi;
3638 yaffs_ObjectHeader *oh;
3640 yaffs_Object *parent;
3642 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
3645 // Scan all the blocks...
3647 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
3650 bi = yaffs_GetBlockInfo(dev,blk);
3653 state = YAFFS_BLOCK_STATE_SCANNING;
3656 if(yaffs_IsBlockBad(dev,blk))
3658 state = YAFFS_BLOCK_STATE_DEAD;
3659 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("block %d is bad" TENDSTR),blk));
3662 // Read each chunk in the block.
3664 for(c = 0; c < YAFFS_CHUNKS_PER_BLOCK &&
3665 state == YAFFS_BLOCK_STATE_SCANNING; c++)
3667 // Read the spare area and decide what to do
3668 chunk = blk * YAFFS_CHUNKS_PER_BLOCK + c;
3670 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare,1);
3673 // This block looks ok, now what's in this chunk?
3674 yaffs_GetTagsFromSpare(dev,&spare,&tags);
3676 if(yaffs_CountBits(spare.pageStatus) < 6)
3680 dev->nFreeChunks ++;
3681 //T((" %d %d deleted\n",blk,c));
3683 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
3685 // An unassigned chunk in the block
3686 // This means that either the block is empty or
3687 // this is the one being allocated from
3691 // the block is unused
3692 state = YAFFS_BLOCK_STATE_EMPTY;
3693 dev->nErasedBlocks++;
3697 // this is the block being allocated from
3698 T(YAFFS_TRACE_SCAN,(TSTR(" Allocating from %d %d" TENDSTR),blk,c));
3699 state = YAFFS_BLOCK_STATE_ALLOCATING;
3700 dev->allocationBlock = blk;
3701 dev->allocationPage = c;
3704 dev->nFreeChunks += (YAFFS_CHUNKS_PER_BLOCK - c);
3706 else if(tags.chunkId > 0)
3710 bi->pageBits |= (1 << c);
3713 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
3714 // PutChunkIntoFIle checks for a clash (two data chunks with
3715 // the same chunkId).
3716 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
3717 endpos = (tags.chunkId - 1)* YAFFS_BYTES_PER_CHUNK + tags.byteCount;
3718 if(in->variant.fileVariant.scannedFileSize <endpos)
3720 in->variant.fileVariant.scannedFileSize = endpos;
3721 #ifndef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3722 in->variant.fileVariant.fileSize =
3723 in->variant.fileVariant.scannedFileSize;
3727 //T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
3731 // chunkId == 0, so it is an ObjectHeader.
3732 // Thus, we read in the object header and make the object
3733 bi->pageBits |= (1 << c);
3736 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL,1);
3738 oh = (yaffs_ObjectHeader *)chunkData;
3740 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
3744 // We have already filled this one. We have a duplicate and need to resolve it.
3746 unsigned existingSerial = in->serial;
3747 unsigned newSerial = tags.serialNumber;
3749 if(((existingSerial+1) & 3) == newSerial)
3751 // Use new one - destroy the exisiting one
3752 yaffs_DeleteChunk(dev,in->chunkId);
3757 // Use existing - destroy this one.
3758 yaffs_DeleteChunk(dev,chunk);
3763 (tags.objectId == YAFFS_OBJECTID_ROOT ||
3764 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
3766 // We only load some info, don't fiddle with directory structure
3768 in->variantType = oh->type;
3770 in->st_mode = oh->st_mode;
3771 #ifdef CONFIG_YAFFS_WINCE
3772 in->win_atime[0] = oh->win_atime[0];
3773 in->win_ctime[0] = oh->win_ctime[0];
3774 in->win_mtime[0] = oh->win_mtime[0];
3775 in->win_atime[1] = oh->win_atime[1];
3776 in->win_ctime[1] = oh->win_ctime[1];
3777 in->win_mtime[1] = oh->win_mtime[1];
3779 in->st_uid = oh->st_uid;
3780 in->st_gid = oh->st_gid;
3781 in->st_atime = oh->st_atime;
3782 in->st_mtime = oh->st_mtime;
3783 in->st_ctime = oh->st_ctime;
3784 in->st_rdev = oh->st_rdev;
3786 in->chunkId = chunk;
3791 // we need to load this info
3794 in->variantType = oh->type;
3796 in->st_mode = oh->st_mode;
3797 #ifdef CONFIG_YAFFS_WINCE
3798 in->win_atime[0] = oh->win_atime[0];
3799 in->win_ctime[0] = oh->win_ctime[0];
3800 in->win_mtime[0] = oh->win_mtime[0];
3801 in->win_atime[1] = oh->win_atime[1];
3802 in->win_ctime[1] = oh->win_ctime[1];
3803 in->win_mtime[1] = oh->win_mtime[1];
3805 in->st_uid = oh->st_uid;
3806 in->st_gid = oh->st_gid;
3807 in->st_atime = oh->st_atime;
3808 in->st_mtime = oh->st_mtime;
3809 in->st_ctime = oh->st_ctime;
3810 in->st_rdev = oh->st_rdev;
3812 in->chunkId = chunk;
3814 yaffs_SetObjectName(in,oh->name);
3817 // directory stuff...
3818 // hook up to parent
3820 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
3821 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
3823 // Set up as a directory
3824 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
3825 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
3827 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
3829 // Hoosterman, another problem....
3830 // We're trying to use a non-directory as a directory
3832 T(YAFFS_TRACE_ERROR, (TSTR("yaffs tradgedy: attempting to use non-directory as a directory in scan" TENDSTR)));
3836 yaffs_AddObjectToDirectory(parent,in);
3837 if(parent == dev->unlinkedDir)
3839 in->deleted = 1; // If it is unlinked at start up then it wants deleting
3840 dev->nDeletedFiles++;
3843 // Note re hardlinks.
3844 // Since we might scan a hardlink before its equivalent object is scanned
3845 // we put them all in a list.
3846 // After scanning is complete, we should have all the objects, so we run through this
3847 // list and fix up all the chains.
3849 switch(in->variantType)
3851 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
3853 case YAFFS_OBJECT_TYPE_FILE:
3854 #ifdef CONFIG_YAFFS_USE_HEADER_FILE_SIZE
3855 in->variant.fileVariant.fileSize = oh->fileSize;
3858 case YAFFS_OBJECT_TYPE_HARDLINK:
3859 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
3860 (yaffs_Object *)(in->hardLinks.next) = hardList;
3863 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
3865 case YAFFS_OBJECT_TYPE_SPECIAL: // Do nothing
3867 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
3868 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
3871 //T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
3876 if(state == YAFFS_BLOCK_STATE_SCANNING)
3878 // If we got this far while scanning, then the block is fully allocated.
3879 state = YAFFS_BLOCK_STATE_FULL;
3882 bi->blockState = state;
3884 // Now let's see if it was dirty
3885 if( bi->pagesInUse == 0 &&
3886 bi->blockState == YAFFS_BLOCK_STATE_FULL)
3888 yaffs_BlockBecameDirty(dev,blk);
3893 // Fix up the hard link chains.
3894 // We should now have scanned all the objects, now it's time to add these
3899 hardList = (yaffs_Object *)(hardList->hardLinks.next);
3901 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
3905 // Add the hardlink pointers
3906 hl->variant.hardLinkVariant.equivalentObject=in;
3907 list_add(&hl->hardLinks,&in->hardLinks);
3911 //Todo Need to report/handle this better.
3912 // Got a problem... hardlink to a non-existant object
3913 hl->variant.hardLinkVariant.equivalentObject=NULL;
3914 INIT_LIST_HEAD(&hl->hardLinks);
3926 ////////////////////////// Directory Functions /////////////////////////
3929 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
3932 if(obj->siblings.prev == NULL)
3935 INIT_LIST_HEAD(&obj->siblings);
3938 else if(!list_empty(&obj->siblings))
3940 // If it is holed up somewhere else, un hook it
3941 list_del_init(&obj->siblings);
3944 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
3945 obj->parent = directory;
3947 if(directory == obj->myDev->unlinkedDir)
3950 obj->myDev->nUnlinkedFiles++;
3951 obj->renameAllowed = 0;
3955 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
3957 list_del_init(&obj->siblings);
3961 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
3965 struct list_head *i;
3966 char buffer[YAFFS_MAX_NAME_LENGTH+1];
3970 sum = yaffs_CalcNameSum(name);
3972 list_for_each(i,&directory->variant.directoryVariant.children)
3974 l = list_entry(i, yaffs_Object,siblings);
3976 // Special case for lost-n-found
3977 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
3979 if(yaffs_strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
3984 else if(yaffs_SumCompare(l->sum, sum))
3987 yaffs_GetObjectName(l,buffer,YAFFS_MAX_NAME_LENGTH);
3988 if(yaffs_strcmp(name,buffer) == 0)
4001 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
4003 struct list_head *i;
4007 list_for_each(i,&theDir->variant.directoryVariant.children)
4009 l = list_entry(i, yaffs_Object,siblings);
4021 // GetEquivalentObject dereferences any hard links to get to the
4024 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4026 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4028 // We want the object id of the equivalent object, not this one
4029 obj = obj->variant.hardLinkVariant.equivalentObject;
4035 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
4037 memset(name,0,buffSize);
4039 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
4041 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
4043 else if(obj->chunkId <= 0)
4047 sprintf(locName,"%s%d",YAFFS_LOSTNFOUND_PREFIX,obj->objectId);
4048 strncpy(name,locName,buffSize - 1);
4051 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4052 else if(obj->shortName[0])
4054 strcpy(name,obj->shortName);
4059 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4060 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4062 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4064 if(obj->chunkId >= 0)
4066 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL,1);
4068 strncpy(name,oh->name,buffSize - 1);
4071 return strlen(name);
4074 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4077 // Dereference any hard linking
4078 obj = yaffs_GetEquivalentObject(obj);
4080 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4082 return obj->variant.fileVariant.fileSize;
4084 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4086 return strlen(obj->variant.symLinkVariant.alias);
4090 // Only a directory should drop through to here
4091 return YAFFS_BYTES_PER_CHUNK;
4095 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4098 struct list_head *i;
4102 count++; // the object itself
4104 list_for_each(i,&obj->hardLinks)
4106 count++; // add the hard links;
4113 int yaffs_GetObjectInode(yaffs_Object *obj)
4115 obj = yaffs_GetEquivalentObject(obj);
4117 return obj->objectId;
4120 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4122 obj = yaffs_GetEquivalentObject(obj);
4124 switch(obj->variantType)
4126 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
4127 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
4128 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
4129 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
4130 case YAFFS_OBJECT_TYPE_SPECIAL:
4131 if(S_ISFIFO(obj->st_mode)) return DT_FIFO;
4132 if(S_ISCHR(obj->st_mode)) return DT_CHR;
4133 if(S_ISBLK(obj->st_mode)) return DT_BLK;
4134 if(S_ISSOCK(obj->st_mode)) return DT_SOCK;
4135 default: return DT_REG; break;
4139 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4141 obj = yaffs_GetEquivalentObject(obj);
4142 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4144 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4148 return yaffs_CloneString("");
4152 #ifndef CONFIG_YAFFS_WINCE
4154 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4156 unsigned int valid = attr->ia_valid;
4158 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
4159 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
4160 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
4162 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
4163 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
4164 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
4166 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
4168 yaffs_UpdateObjectHeader(obj,NULL,1);
4173 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4175 unsigned int valid = 0;
4177 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
4178 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
4179 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
4181 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
4182 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
4183 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
4185 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
4187 attr->ia_valid = valid;
4195 int yaffs_DumpObject(yaffs_Object *obj)
4197 // __u8 buffer[YAFFS_BYTES_PER_CHUNK];
4199 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
4201 // memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
4203 // if(obj->chunkId >= 0)
4205 // yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
4208 yaffs_GetObjectName(obj,name,256);
4210 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),
4211 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
4212 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4215 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
4216 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
4217 obj->sum, obj->chunkId));
4218 switch(obj->variantType)
4220 case YAFFS_OBJECT_TYPE_FILE:
4221 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
4223 case YAFFS_OBJECT_TYPE_DIRECTORY:
4224 YPRINTF((" DIRECTORY\n"));
4226 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
4227 case YAFFS_OBJECT_TYPE_SYMLINK:
4228 case YAFFS_OBJECT_TYPE_UNKNOWN:
4237 ///////////////////////// Initialisation code ///////////////////////////
4241 int yaffs_GutsInitialise(yaffs_Device *dev)
4250 if(!yaffs_CheckStructures())
4252 T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
4256 if(dev->startBlock <= 0 ||
4257 (dev->endBlock - dev->startBlock) < 10)
4259 T(YAFFS_TRACE_ALWAYS,(TSTR("startBlock %d or endBlock %d invalid\n" TENDSTR),
4260 dev->startBlock, dev->endBlock));
4264 nBlocks = dev->endBlock - dev->startBlock + 1;
4268 // OK now calculate a few things for the device
4269 // Calculate chunkGroupBits.
4270 // We need to find the next power of 2 > than endBlock
4272 x = YAFFS_CHUNKS_PER_BLOCK * (dev->endBlock+1);
4274 for(bits = extraBits = 0; x > 1; bits++)
4276 if(x & 1) extraBits++;
4280 if(extraBits > 0) bits++;
4283 // Level0 Tnodes are 16 bits, so if the bitwidth of the
4284 // chunk range we're using is greater than 16 we need
4285 // to figure out chunk shift and chunkGroupSize
4288 dev->chunkGroupBits = 0;
4292 dev->chunkGroupBits = bits - 16;
4294 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
4297 // More device initialisation
4298 dev->garbageCollectionRequired = 0;
4299 dev->garbageCollections = 0;
4300 dev->currentDirtyChecker = 0;
4301 dev->bufferedBlock = -1;
4302 dev->doingBufferedBlockRewrite = 0;
4303 dev->blockSelectedForGC = -1;
4304 dev->nDeletedFiles = 0;
4305 dev->nBackgroundDeletions=0;
4306 dev->nUnlinkedFiles = 0;
4309 dev->tagsEccFixed=0;
4310 dev->tagsEccUnfixed=0;
4312 dev->localBuffer = YMALLOC(YAFFS_BYTES_PER_CHUNK);
4314 yaffs_InitialiseBlocks(dev,nBlocks);
4316 yaffs_InitialiseTnodes(dev);
4318 yaffs_InitialiseObjects(dev);
4320 #ifdef CONFIG_YAFFS_SHORT_OP_CACHE
4323 for(i=0; i < YAFFS_N_CACHE_CHUNKS; i++)
4325 dev->srCache[i].object = NULL;
4326 dev->srCache[i].lastUse = 0;
4327 dev->srCache[i].dirty = 0;
4336 // Initialise the unlinked, root and lost and found directories
4337 dev->lostNFoundDir = dev->rootDir = dev->unlinkedDir = NULL;
4339 dev->unlinkedDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4341 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
4342 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4343 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
4346 // Now scan the flash.
4350 dev->nPageReads = 0;
4351 dev->nPageWrites = 0;
4352 dev->nBlockErasures = 0;
4354 dev->nRetriedWrites = 0;
4355 dev->nRetiredBlocks = 0;
4362 void yaffs_Deinitialise(yaffs_Device *dev)
4364 yaffs_DeinitialiseBlocks(dev);
4365 yaffs_DeinitialiseTnodes(dev);
4366 yaffs_DeinitialiseObjects(dev);
4370 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
4372 int nFree = dev->nFreeChunks - (YAFFS_CHUNKS_PER_BLOCK * YAFFS_RESERVED_BLOCKS);
4374 struct list_head *i;
4378 // To the free chunks add the chunks that are in the deleted unlinked files.
4379 list_for_each(i,&dev->unlinkedDir->variant.directoryVariant.children)
4381 l = list_entry(i, yaffs_Object,siblings);
4385 nFree += l->nDataChunks;
4390 return (nFree < 0) ? 0 : nFree;
4395 /////////////////// YAFFS test code //////////////////////////////////
4397 #define yaffs_CheckStruct(structure,syze, name) \
4398 if(sizeof(structure) != syze) \
4400 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),name,syze,sizeof(structure))); \
4401 return YAFFS_FAIL; \
4405 static int yaffs_CheckStructures(void)
4407 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
4408 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
4409 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
4410 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
4411 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
4418 void yaffs_GutsTest(yaffs_Device *dev)
4421 if(yaffs_CheckStructures() != YAFFS_OK)
4423 T(YAFFS_TRACE_ALWAYS,(TSTR("One or more structures malformed-- aborting\n" TENDSTR)));
4427 yaffs_TnodeTest(dev);
4428 yaffs_ObjectTest(dev);