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.
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
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_countBits[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
60 //static yaffs_Device *yaffs_device;
61 //yaffs_Object *yaffs_rootDir;
62 //yaffs_Object *yaffs_lostNFound;
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_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);
75 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId);
76 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
77 static int yaffs_CheckStructures(void);
79 loff_t yaffs_GetFileSize(yaffs_Object *obj);
82 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
85 static int yaffs_CheckFileSanity(yaffs_Object *in);
87 #define yaffs_CheckFileSanity(in)
90 static int __inline__ yaffs_HashFunction(int n)
92 return (n % YAFFS_NOBJECT_BUCKETS);
96 yaffs_Object *yaffs_Root(yaffs_Device *dev)
101 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
103 return dev->lostNFoundDir;
107 static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
109 return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
112 int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, __u8 *data, yaffs_Spare *spare)
116 yaffs_Spare localSpare;
120 // If we don't have a real spare, then we use a local one.
121 // Need this for the calculation of the ecc
125 retVal = dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
129 //Todo handle any errors
130 nand_calculate_ecc(data,calcEcc);
131 nand_correct_data (data,spare->ecc1, calcEcc);
132 nand_calculate_ecc(&data[256],calcEcc);
133 nand_correct_data (&data[256],spare->ecc2, calcEcc);
138 #ifdef YAFFS_PARANOID
140 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,int chunkInNAND)
143 static __u8 cmpbuf[YAFFS_BYTES_PER_CHUNK];
144 static __u8 data[YAFFS_BYTES_PER_CHUNK];
145 static __u8 spare[16];
151 dev->readChunkFromNAND(dev,chunkInNAND,data,(yaffs_Spare *)spare);
157 memset(cmpbuf,0xff,YAFFS_BYTES_PER_CHUNK);
161 if(memcmp(cmpbuf,data,YAFFS_BYTES_PER_CHUNK)) retVal = YAFFS_FAIL;
162 if(memcmp(cmpbuf,spare,16)) retVal = YAFFS_FAIL;
171 int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
173 return dev->eraseBlockInNAND(dev,blockInNAND);
176 int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
178 return dev->initialiseNAND(dev);
181 static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
187 unsigned char rbData[YAFFS_BYTES_PER_CHUNK];
191 chunk = yaffs_AllocateChunk(dev,useReserve);
195 writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
199 // If verify fails, then delete this chunk and try again
200 // To verify we compare everything except the block and
201 // page status bytes.
202 yaffs_ReadChunkFromNAND(dev,chunk,rbData,&rbSpare);
204 if(memcmp(data,rbData,YAFFS_BYTES_PER_CHUNK) != 0 ||
205 spare->tagByte0 != rbSpare.tagByte0 ||
206 spare->tagByte1 != rbSpare.tagByte1 ||
207 spare->tagByte2 != rbSpare.tagByte2 ||
208 spare->tagByte3 != rbSpare.tagByte3 ||
209 spare->tagByte4 != rbSpare.tagByte4 ||
210 spare->tagByte5 != rbSpare.tagByte5 ||
211 spare->tagByte6 != rbSpare.tagByte6 ||
212 spare->tagByte7 != rbSpare.tagByte7 ||
213 spare->ecc1[0] != rbSpare.ecc1[0] ||
214 spare->ecc1[1] != rbSpare.ecc1[1] ||
215 spare->ecc1[2] != rbSpare.ecc1[2] ||
216 spare->ecc2[0] != rbSpare.ecc2[0] ||
217 spare->ecc2[1] != rbSpare.ecc2[1] ||
218 spare->ecc2[2] != rbSpare.ecc2[2] )
221 yaffs_DeleteChunk(dev,chunk);
227 } while(chunk >= 0 && ! writeOk);
235 ///////////////////////// Object management //////////////////
236 // List of spare objects
237 // The list is hooked together using the first pointer
240 // static yaffs_Object *yaffs_freeObjects = NULL;
242 // static int yaffs_nFreeObjects;
244 // static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
246 // static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
249 static __u16 yaffs_CalcNameSum(const char *name)
254 __u8 *bname = (__u8 *)name;
266 void yaffs_CalcECC(const __u8 *data, yaffs_Spare *spare)
268 nand_calculate_ecc (data , spare->ecc1);
269 nand_calculate_ecc (&data[256] , spare->ecc2);
272 void yaffs_CalcTagsECC(yaffs_Tags *tags)
274 // Todo don't do anything yet. Need to calculate ecc
275 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
282 for(i = 0; i < 8; i++)
284 for(j = 1; j &0x7f; j<<=1)
299 void yaffs_CheckECCOnTags(yaffs_Tags *tags)
301 unsigned ecc = tags->ecc;
303 yaffs_CalcTagsECC(tags);
310 unsigned char *b = ((yaffs_TagsUnion *)tags)->asBytes;
314 b[ecc / 8] ^= (1 << (ecc & 7));
316 // Now recvalc the ecc
317 yaffs_CalcTagsECC(tags);
322 ///////////////////////// TNODES ///////////////////////
324 // List of spare tnodes
325 // The list is hooked together using the first pointer
328 //static yaffs_Tnode *yaffs_freeTnodes = NULL;
330 // static int yaffs_nFreeTnodes;
332 //static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
336 // yaffs_CreateTnodes creates a bunch more tnodes and
337 // adds them to the tnode free list.
338 // Don't use this function directly
340 static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
343 yaffs_Tnode *newTnodes;
344 yaffs_TnodeList *tnl;
346 if(nTnodes < 1) return YAFFS_OK;
350 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
354 YALERT("Could not malloc tnodes");
358 // Hook them into the free list
359 for(i = 0; i < nTnodes - 1; i++)
361 newTnodes[i].internal[0] = &newTnodes[i+1];
364 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
365 dev->freeTnodes = newTnodes;
366 dev->nFreeTnodes+= nTnodes;
367 dev->nTnodesCreated += nTnodes;
369 // Now add this bunch of tnodes to a list for freeing up.
371 tnl = YMALLOC(sizeof(yaffs_TnodeList));
374 YALERT("Could not add tnodes to management list");
378 tnl->tnodes = newTnodes;
379 tnl->next = dev->allocatedTnodeList;
380 dev->allocatedTnodeList = tnl;
384 YINFO("Tnodes created");
391 // GetTnode gets us a clean tnode. Tries to make allocate more if we run out
392 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
394 yaffs_Tnode *tn = NULL;
396 // If there are none left make more
399 yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
404 tn = dev->freeTnodes;
405 dev->freeTnodes = dev->freeTnodes->internal[0];
408 memset(tn,0,sizeof(yaffs_Tnode));
416 // FreeTnode frees up a tnode and puts it back on the free list
417 static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
419 tn->internal[0] = dev->freeTnodes;
420 dev->freeTnodes = tn;
425 static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
427 // Free the list of allocated tnodes
429 while(dev->allocatedTnodeList)
431 YFREE(dev->allocatedTnodeList->tnodes);
432 dev->allocatedTnodeList = dev->allocatedTnodeList->next;
435 dev->freeTnodes = NULL;
436 dev->nFreeTnodes = 0;
439 static void yaffs_InitialiseTnodes(yaffs_Device*dev)
441 dev->allocatedTnodeList = NULL;
442 dev->freeTnodes = NULL;
443 dev->nFreeTnodes = 0;
444 dev->nTnodesCreated = 0;
448 void yaffs_TnodeTest(yaffs_Device *dev)
453 yaffs_Tnode *tn[1000];
455 YINFO("Testing TNodes");
457 for(j = 0; j < 50; j++)
459 for(i = 0; i < 1000; i++)
461 tn[i] = yaffs_GetTnode(dev);
464 YALERT("Getting tnode failed");
467 for(i = 0; i < 1000; i+=3)
469 yaffs_FreeTnode(dev,tn[i]);
476 ////////////////// END OF TNODE MANIPULATION ///////////////////////////
478 /////////////// Functions to manipulate the look-up tree (made up of tnodes)
479 // The look up tree is represented by the top tnode and the number of topLevel
480 // in the tree. 0 means only the level 0 tnode is in the tree.
483 // FindLevel0Tnode finds the level 0 tnode, if one exists.
484 // Used when reading.....
485 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
488 yaffs_Tnode *tn = fStruct->top;
490 int requiredTallness;
491 int level = fStruct->topLevel;
493 // Check sane level and chunk Id
494 if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
497 sprintf(str,"Bad level %d",level);
501 if(chunkId > YAFFS_MAX_CHUNK_ID)
504 sprintf(str,"Bad chunkId %d",chunkId);
509 // First check we're tall enough (ie enough topLevel)
511 i = chunkId >> (dev->chunkGroupBits + YAFFS_TNODES_LEVEL0_BITS);
512 requiredTallness = 0;
515 i >>= YAFFS_TNODES_INTERNAL_BITS;
520 if(requiredTallness > fStruct->topLevel)
522 // Not tall enough, so we can't find it, return NULL.
527 // Traverse down to level 0
528 while (level > 0 && tn)
530 tn = tn->internal[(chunkId >>(dev->chunkGroupBits + YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
531 YAFFS_TNODES_INTERNAL_MASK];
539 // AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
540 // This happens in two steps:
541 // 1. If the tree isn't tall enough, then make it taller.
542 // 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
544 // Used when modifying the tree.
546 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
551 int requiredTallness;
557 T(("AddOrFind topLevel=%d, chunk=%d",fStruct->topLevel,chunkId));
559 // Check sane level and page Id
560 if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
563 sprintf(str,"Bad level %d",fStruct->topLevel);
568 if(chunkId > YAFFS_MAX_CHUNK_ID)
571 sprintf(str,"Bad chunkId %d",chunkId);
576 // First check we're tall enough (ie enough topLevel)
578 i = chunkId >> (dev->chunkGroupBits + YAFFS_TNODES_LEVEL0_BITS);
579 requiredTallness = 0;
582 i >>= YAFFS_TNODES_INTERNAL_BITS;
586 T((" required=%d",requiredTallness));
589 if(requiredTallness > fStruct->topLevel)
591 // Not tall enough,gotta make the tree taller
592 for(i = fStruct->topLevel; i < requiredTallness; i++)
596 tn = yaffs_GetTnode(dev);
600 tn->internal[0] = fStruct->top;
605 YALERT("No more tnodes");
609 fStruct->topLevel = requiredTallness;
613 // Traverse down to level 0, adding anything we need
615 l = fStruct->topLevel;
619 i = (chunkId >> (dev->chunkGroupBits +YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
620 YAFFS_TNODES_INTERNAL_MASK;
628 tn->internal[i] = yaffs_GetTnode(dev);
631 tn = tn->internal[i];
642 // Pruning removes any part of the file structure tree that is beyond the
643 // bounds of the file.
644 // A file should only get pruned when its size is reduced.
646 // Before pruning, the chunks must be pulled from the tree and the
647 // level 0 tnode entries must be zeroed out.
648 // Could also use this for file deletion, but that's probably better handled
649 // by a special case.
651 // yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
653 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
662 for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
664 if(tn->internal[i] && level > 0)
666 tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
675 if(hasData == 0 && del0)
677 // Free and return NULL
679 yaffs_FreeTnode(dev,tn);
689 static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
696 if(fStruct->topLevel > 0)
698 fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
700 // Now we have a tree with all the non-zero branches NULL but the height
701 // is the same as it was.
702 // Let's see if we can trim internal tnodes to shorten the tree.
703 // We can do this if only the 0th element in the tnode is in use
704 // (ie all the non-zero are NULL)
706 while(fStruct->topLevel && !done)
711 for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
721 fStruct->top = tn->internal[0];
723 yaffs_FreeTnode(dev,tn);
738 /////////////////////// End of File Structure functions. /////////////////
740 // yaffs_CreateFreeObjects creates a bunch more objects and
741 // adds them to the object free list.
742 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
745 yaffs_Object *newObjects;
746 yaffs_ObjectList *list;
748 if(nObjects < 1) return YAFFS_OK;
752 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
756 YALERT("Could not allocate more objects");
760 // Hook them into the free list
761 for(i = 0; i < nObjects - 1; i++)
763 (yaffs_Object *)newObjects[i].siblings.next = &newObjects[i+1];
766 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
767 dev->freeObjects = newObjects;
768 dev->nFreeObjects+= nObjects;
769 dev->nObjectsCreated+= nObjects;
771 // Now add this bunch of Objects to a list for freeing up.
773 list = YMALLOC(sizeof(yaffs_ObjectList));
776 YALERT("Could not add Objects to management list");
780 list->objects = newObjects;
781 list->next = dev->allocatedObjectList;
782 dev->allocatedObjectList = list;
786 YINFO("Objects created");
793 // AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
794 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
796 yaffs_Object *tn = NULL;
798 // If there are none left make more
799 if(!dev->freeObjects)
801 yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
806 tn = dev->freeObjects;
807 dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
810 // Now sweeten it up...
812 memset(tn,0,sizeof(yaffs_Object));
814 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
815 INIT_LIST_HEAD(&(tn->hardLinks));
816 INIT_LIST_HEAD(&(tn->hashLink));
817 INIT_LIST_HEAD(&tn->siblings);
819 // Add it to the lost and found directory.
820 // NB Can't put root or lostNFound in lostNFound so
821 // check if lostNFound exists first
822 if(dev->lostNFoundDir)
824 yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
832 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
835 yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
838 obj->fake = 1; // it is fake so it has no NAND presence...
839 obj->renameAllowed= 0; // ... and we're not allowed to rename it...
840 obj->unlinkAllowed= 0; // ... or unlink it
843 obj->chunkId = 0; // Not a valid chunk.
851 static void yaffs_UnhashObject(yaffs_Object *tn)
854 yaffs_Device *dev = tn->myDev;
857 // If it is still linked into the bucket list, free from the list
858 if(!list_empty(&tn->hashLink))
860 list_del_init(&tn->hashLink);
861 bucket = yaffs_HashFunction(tn->objectId);
862 dev->objectBucket[bucket].count--;
868 // FreeObject frees up a Object and puts it back on the free list
869 static void yaffs_FreeObject(yaffs_Object *tn)
872 yaffs_Device *dev = tn->myDev;
874 yaffs_UnhashObject(tn);
876 // Link into the free list.
877 (yaffs_Object *)(tn->siblings.next) = dev->freeObjects;
878 dev->freeObjects = tn;
885 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
887 // Free the list of allocated Objects
889 while( dev->allocatedObjectList)
891 YFREE(dev->allocatedObjectList->objects);
892 dev->allocatedObjectList = dev->allocatedObjectList->next;
895 dev->freeObjects = NULL;
896 dev->nFreeObjects = 0;
899 static void yaffs_InitialiseObjects(yaffs_Device *dev)
903 dev->allocatedObjectList = NULL;
904 dev->freeObjects = NULL;
905 dev->nFreeObjects = 0;
907 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
909 INIT_LIST_HEAD(&dev->objectBucket[i].list);
910 dev->objectBucket[i].count = 0;
920 int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
928 // First let's see if we can find one that's empty.
930 for(i = 0; i < 10 && lowest > 0; i++)
933 x %= YAFFS_NOBJECT_BUCKETS;
934 if(dev->objectBucket[x].count < lowest)
936 lowest = dev->objectBucket[x].count;
942 // If we didn't find an empty list, then try
943 // looking a bit further for a short one
945 for(i = 0; i < 10 && lowest > 3; i++)
948 x %= YAFFS_NOBJECT_BUCKETS;
949 if(dev->objectBucket[x].count < lowest)
951 lowest = dev->objectBucket[x].count;
960 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
962 int bucket = yaffs_FindNiceObjectBucket(dev);
964 // Now find an object value that has not already been taken
965 // by scanning the list.
972 //yaffs_CheckObjectHashSanity();
977 n += YAFFS_NOBJECT_BUCKETS;
978 if(1 ||dev->objectBucket[bucket].count > 0)
980 list_for_each(i,&dev->objectBucket[bucket].list)
982 // If there is already one in the list
983 if(list_entry(i, yaffs_Object,hashLink)->objectId == n)
991 //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
996 void yaffs_HashObject(yaffs_Object *in)
998 int bucket = yaffs_HashFunction(in->objectId);
999 yaffs_Device *dev = in->myDev;
1001 if(!list_empty(&in->hashLink))
1007 list_add(&in->hashLink,&dev->objectBucket[bucket].list);
1008 dev->objectBucket[bucket].count++;
1012 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,int number)
1014 int bucket = yaffs_HashFunction(number);
1015 struct list_head *i;
1018 list_for_each(i,&dev->objectBucket[bucket].list)
1020 // Lookm if it is in the list
1021 in = list_entry(i, yaffs_Object,hashLink);
1022 if(in->objectId == number)
1033 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
1036 yaffs_Object *theObject;
1040 number = yaffs_CreateNewObjectNumber(dev);
1043 theObject = yaffs_AllocateEmptyObject(dev);
1047 theObject->fake = 0;
1048 theObject->renameAllowed = 1;
1049 theObject->unlinkAllowed = 1;
1050 theObject->objectId = number;
1051 theObject->myDev = dev;
1052 yaffs_HashObject(theObject);
1053 theObject->variantType = type;
1054 theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
1058 case YAFFS_OBJECT_TYPE_FILE:
1059 theObject->variant.fileVariant.fileSize = 0;
1060 theObject->variant.fileVariant.topLevel = 0;
1061 theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
1063 case YAFFS_OBJECT_TYPE_DIRECTORY:
1064 INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
1066 case YAFFS_OBJECT_TYPE_SYMLINK:
1067 // No action required
1069 case YAFFS_OBJECT_TYPE_HARDLINK:
1070 // No action required
1072 case YAFFS_OBJECT_TYPE_UNKNOWN:
1073 // todo this should not happen
1080 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
1082 yaffs_Object *theObject = NULL;
1086 theObject = yaffs_FindObjectByNumber(dev,number);
1091 theObject = yaffs_CreateNewObject(dev,number,type);
1098 char *yaffs_CloneString(const char *str)
1100 char *newStr = NULL;
1104 newStr = YMALLOC(strlen(str) + 1);
1113 // Mknod (create) a new object.
1114 // equivalentObject only has meaning for a hard link;
1115 // aliasString only has meaning for a sumlink.
1116 yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
1117 yaffs_Object *parent,
1122 yaffs_Object *equivalentObject,
1123 const char *aliasString)
1127 yaffs_Device *dev = parent->myDev;
1129 // Check if the entry exists. If it does then fail the call since we don't want a dup.
1130 if(yaffs_FindObjectByName(parent,name))
1135 in = yaffs_CreateNewObject(dev,-1,type);
1141 in->variantType = type;
1146 in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
1148 in->sum = yaffs_CalcNameSum(name);
1151 yaffs_AddObjectToDirectory(parent,in);
1153 in->myDev = parent->myDev;
1158 case YAFFS_OBJECT_TYPE_SYMLINK:
1159 in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
1161 case YAFFS_OBJECT_TYPE_HARDLINK:
1162 in->variant.hardLinkVariant.equivalentObject = equivalentObject;
1163 in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
1164 list_add(&in->hardLinks,&equivalentObject->hardLinks);
1166 case YAFFS_OBJECT_TYPE_FILE: // do nothing
1167 case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
1168 case YAFFS_OBJECT_TYPE_UNKNOWN:
1171 yaffs_UpdateObjectHeader(in,name);
1178 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1180 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL);
1183 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
1185 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL);
1188 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
1190 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias);
1193 // NB yaffs_Link returns the object id of the equivalent object.
1194 yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
1196 // Get the real object in case we were fed a hard link as an equivalent object
1197 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1199 if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL))
1201 return equivalentObject;
1211 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName)
1213 //yaffs_Device *dev = obj->myDev;
1217 newDir = obj->parent; // use the old directory
1220 // Only proceed if the new name does not exist and
1221 // if we're putting it into a directory.
1222 if(!yaffs_FindObjectByName(newDir,newName) &&
1223 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1225 obj->sum = yaffs_CalcNameSum(newName);
1227 yaffs_AddObjectToDirectory(newDir,obj);
1229 if(yaffs_UpdateObjectHeader(obj,newName) >= 0)
1238 int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
1242 obj = yaffs_FindObjectByName(oldDir,oldName);
1243 if(obj && obj->renameAllowed)
1245 return yaffs_ChangeObjectName(obj,newDir,newName);
1252 static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
1254 // Scan the buckets and check that the lists
1255 // have as many members as the count says there are
1258 struct list_head *j;
1261 for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
1265 list_for_each(j,&dev->objectBucket[bucket].list)
1270 if(countEm != dev->objectBucket[bucket].count)
1272 YALERT("Inode hash inconsistency");
1280 void yaffs_ObjectTest(yaffs_Device *dev)
1282 yaffs_Object *in[1000];
1284 yaffs_Object *inold[1000];
1288 memset(in,0,1000*sizeof(yaffs_Object *));
1289 memset(inold,0,1000*sizeof(yaffs_Object *));
1291 yaffs_CheckObjectHashSanity(dev);
1293 for(j = 0; j < 10; j++)
1297 for(i = 0; i < 1000; i++)
1299 in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
1302 YINFO("No more inodes");
1306 inNo[i] = in[i]->objectId;
1310 for(i = 0; i < 1000; i++)
1312 if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
1314 T(("Differnce in look up test\n"));
1318 // T(("Look up ok\n"));
1322 yaffs_CheckObjectHashSanity(dev);
1324 for(i = 0; i < 1000; i+=3)
1326 yaffs_FreeObject(in[i]);
1331 yaffs_CheckObjectHashSanity(dev);
1338 /////////////////////////// Block Management and Page Allocation ///////////////////
1341 static void yaffs_InitialiseBlocks(yaffs_Device *dev)
1343 dev->blockInfo = YMALLOC(dev->nBlocks * sizeof(yaffs_BlockInfo));
1344 memset(dev->blockInfo,0,dev->nBlocks * sizeof(yaffs_BlockInfo));
1345 dev->allocationBlock = -1; // force it to get a new one
1348 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1350 YFREE(dev->blockInfo);
1353 // FindDiretiestBlock is used to select the dirtiest block (or close enough)
1354 // for garbage collection.
1356 static int yaffs_FindDirtiestBlock(yaffs_Device *dev)
1359 int b = dev->currentDirtyChecker;
1363 int pagesInUse = 100; // silly big number
1365 for(i = dev->startBlock; i <= dev->endBlock && pagesInUse > 2 ; i++)
1368 if (b > dev->endBlock)
1370 b = dev->startBlock;
1373 if(dev->blockInfo[b].blockState == YAFFS_BLOCK_STATE_FULL &&
1374 (dev->blockInfo)[b].pagesInUse < pagesInUse)
1377 pagesInUse = (dev->blockInfo)[b].pagesInUse;
1381 dev->currentDirtyChecker = b;
1387 static int yaffs_FindBlockForAllocation(yaffs_Device *dev,int useReserve)
1391 if(useReserve && dev->nErasedBlocks < 1)
1393 // Hoosterman we've got a problem.
1394 // Can't get space to gc
1397 else if(!useReserve && dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
1399 // We are not in GC, so we hold some in reserve so we can get
1403 // Find an empty block.
1405 for(i = dev->startBlock; i <= dev->endBlock; i++)
1408 if(dev->blockInfo[i].blockState == YAFFS_BLOCK_STATE_EMPTY)
1410 dev->blockInfo[i].blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1411 dev->nErasedBlocks--;
1412 if(dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
1414 dev->garbageCollectionRequired = 1;
1425 static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
1427 yaffs_BlockInfo *bi = &dev->blockInfo[blockNo];
1429 // Mark as dirty, erase it and mark as clean.
1430 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1431 yaffs_EraseBlockInNAND(dev,blockNo);
1432 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1433 dev->nErasedBlocks++;
1437 T(("Erased block %d\n",blockNo));
1441 static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
1445 if(dev->allocationBlock < 0)
1447 // Get next block to allocate off
1448 dev->allocationBlock = yaffs_FindBlockForAllocation(dev,useReserve);
1449 dev->allocationPage = 0;
1452 // Next page please....
1453 if(dev->allocationBlock >= 0)
1455 retVal = (dev->allocationBlock * YAFFS_CHUNKS_PER_BLOCK) +
1456 dev->allocationPage;
1457 dev->blockInfo[dev->allocationBlock].pagesInUse++;
1458 dev->blockInfo[dev->allocationBlock].pageBits |=
1459 (1 << (dev->allocationPage));
1461 dev->allocationPage++;
1465 // If the block is full set the state to full
1466 if(dev->allocationPage >= YAFFS_CHUNKS_PER_BLOCK)
1468 dev->blockInfo[dev->allocationBlock].blockState = YAFFS_BLOCK_STATE_FULL;
1469 dev->allocationBlock = -1;
1472 #ifdef YAFFS_PARANOID
1473 if(yaffs_CheckChunkErased(dev,retVal) == YAFFS_FAIL)
1475 T(("..................Trying to allocate non-erased page %d\n",retVal));
1481 T(("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!\n"));
1487 int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
1496 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
1498 yaffs_BlockInfo *bi = &dev->blockInfo[block];
1500 yaffs_Object *object;
1502 T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
1504 for(mask = 1,oldChunk = block * YAFFS_CHUNKS_PER_BLOCK;
1505 mask && bi->pageBits;
1506 mask <<= 1, oldChunk++ )
1508 if(bi->pageBits & mask)
1511 // This page is in use and needs to be copied off
1513 T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
1515 yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare);
1517 yaffs_GetTagsFromSpare(&spare,&tags);
1518 tags.serialNumber++;
1519 yaffs_LoadTagsIntoSpare(&spare,&tags);
1522 newChunk = yaffs_AllocatePage(dev,1);
1528 yaffs_WriteChunkToNAND(dev,newChunk, buffer, &spare);
1531 newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
1538 object = yaffs_FindObjectByNumber(dev,tags.objectId);
1540 // Ok, now fix up the Tnodes etc.
1542 if(tags.chunkId == 0)
1545 object->chunkId = newChunk;
1549 // It's a data chunk
1550 yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk,0);
1554 yaffs_DeleteChunk(dev,oldChunk);
1562 int yaffs_CheckGarbageCollection(yaffs_Device *dev)
1566 if(dev->garbageCollectionRequired)
1568 dev->garbageCollectionRequired = 0;
1569 block = yaffs_FindDirtiestBlock(dev);
1572 return yaffs_GarbageCollectBlock(dev,block);
1584 //////////////////////////// TAGS ///////////////////////////////////////
1586 static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
1588 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
1590 yaffs_CalcTagsECC(tagsPtr);
1592 sparePtr->tagByte0 = tu->asBytes[0];
1593 sparePtr->tagByte1 = tu->asBytes[1];
1594 sparePtr->tagByte2 = tu->asBytes[2];
1595 sparePtr->tagByte3 = tu->asBytes[3];
1596 sparePtr->tagByte4 = tu->asBytes[4];
1597 sparePtr->tagByte5 = tu->asBytes[5];
1598 sparePtr->tagByte6 = tu->asBytes[6];
1599 sparePtr->tagByte7 = tu->asBytes[7];
1602 static void yaffs_GetTagsFromSpare(yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
1604 yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
1606 tu->asBytes[0]= sparePtr->tagByte0;
1607 tu->asBytes[1]= sparePtr->tagByte1;
1608 tu->asBytes[2]= sparePtr->tagByte2;
1609 tu->asBytes[3]= sparePtr->tagByte3;
1610 tu->asBytes[4]= sparePtr->tagByte4;
1611 tu->asBytes[5]= sparePtr->tagByte5;
1612 tu->asBytes[6]= sparePtr->tagByte6;
1613 tu->asBytes[7]= sparePtr->tagByte7;
1615 yaffs_CheckECCOnTags(tagsPtr);
1618 static void yaffs_SpareInitialise(yaffs_Spare *spare)
1620 memset(spare,0xFF,sizeof(yaffs_Spare));
1623 static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags)
1628 if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare) == YAFFS_OK)
1630 yaffs_GetTagsFromSpare(&spare,tags);
1643 static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
1645 // NB There must be tags, data is optional
1646 // If there is data, then an ECC is calculated on it.
1655 yaffs_SpareInitialise(&spare);
1660 yaffs_CalcECC(buffer,&spare);
1663 yaffs_LoadTagsIntoSpare(&spare,tags);
1665 return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
1671 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
1673 // NB There must be tags, data is optional
1674 // If there is data, then an ECC is calculated on it.
1683 yaffs_SpareInitialise(&spare);
1688 yaffs_CalcECC(buffer,&spare);
1691 yaffs_LoadTagsIntoSpare(&spare,tags);
1693 return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
1700 int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
1702 //Get the Tnode, then get the level 0 offset chunk offset
1705 yaffs_Tags localTags;
1708 yaffs_Device *dev = in->myDev;
1713 // Passed a NULL, so use our own tags space
1717 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
1721 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
1723 // Now we need to do the shifting etc and search for it
1724 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
1726 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags);
1727 if(tags->chunkId == chunkInInode &&
1728 tags->objectId == in->objectId)
1739 return found ? theChunk : -1;
1742 int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
1744 //Get the Tnode, then get the level 0 offset chunk offset
1747 yaffs_Tags localTags;
1750 yaffs_Device *dev = in->myDev;
1754 // Passed a NULL, so use our own tags space
1758 tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
1763 theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
1765 // Now we need to do the shifting etc and search for it
1766 for(i = 0,found = 0; theChunk && i < dev->chunkGroupSize && !found; i++)
1768 yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags);
1769 if(tags->chunkId == chunkInInode &&
1770 tags->objectId == in->objectId)
1781 // Delete the entry in the filestructure
1784 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
1789 T(("No level 0 found for %d\n", chunkInInode));
1794 T(("Could not find %d to delete\n",chunkInInode));
1796 return found ? theChunk : -1;
1802 static int yaffs_CheckFileSanity(yaffs_Object *in)
1810 yaffs_Tags localTags;
1811 yaffs_Tags *tags = &localTags;
1815 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
1817 T(("Object not a file\n"));
1821 objId = in->objectId;
1822 fSize = in->variant.fileVariant.fileSize;
1823 nChunks = (fSize + YAFFS_BYTES_PER_CHUNK -1)/YAFFS_BYTES_PER_CHUNK;
1825 for(chunk = 1; chunk <= nChunks; chunk++)
1827 tn = yaffs_FindLevel0Tnode(in->myDev,&in->variant.fileVariant, chunk);
1832 theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->myDev->chunkGroupBits;
1835 yaffs_ReadChunkTagsFromNAND(in->myDev,theChunk,tags);
1836 if(tags->chunkId == chunk &&
1837 tags->objectId == in->objectId)
1844 //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
1845 // objId,chunk,theChunk,tags->chunkId,tags->objectId);
1854 T(("No level 0 found for %d\n", chunk));
1858 return failed ? YAFFS_FAIL : YAFFS_OK;
1863 static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND, int inScan)
1866 yaffs_Device *dev = in->myDev;
1868 yaffs_Tags existingTags;
1870 unsigned existingSerial, newSerial;
1873 tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
1877 // If we're scanning then we need to test for duplicates
1878 // NB This does not need to be efficient since it should only ever
1879 // happen when the power fails during a write, then only one
1880 // chunk should ever be affected.
1882 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
1884 if(existingChunk != 0)
1886 // We have a duplicate now we need to decide which one to use
1887 // To do this we get both sets of tags and compare serial numbers.
1888 yaffs_ReadChunkTagsFromNAND(dev,chunkInInode, &newTags);
1889 yaffs_ReadChunkTagsFromNAND(dev,existingChunk, &existingTags);
1890 newSerial = newTags.serialNumber;
1891 existingSerial = existingTags.serialNumber;
1892 if(((existingSerial+1) & 3) == newSerial)
1895 // Delete the old one and drop through to update the tnode
1896 yaffs_DeleteChunk(dev,existingChunk);
1901 // Delete the new one and return early so that the tnode isn't changed
1902 yaffs_DeleteChunk(dev,chunkInInode);
1908 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = chunkInNAND;
1915 int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
1917 int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
1919 if(chunkInNAND >= 0)
1921 return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL);
1931 static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId)
1933 int block = chunkId / YAFFS_CHUNKS_PER_BLOCK;
1934 int page = chunkId % YAFFS_CHUNKS_PER_BLOCK;
1937 yaffs_SpareInitialise(&spare);
1939 spare.pageStatus = 0; // To mark it as deleted.
1942 yaffs_WriteChunkToNAND(dev,chunkId,NULL,&spare);
1945 // Pull out of the management area.
1946 // If the whole block became dirty, this will kick off an erasure.
1947 if( dev->blockInfo[block].blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
1948 dev->blockInfo[block].blockState == YAFFS_BLOCK_STATE_FULL)
1952 dev->blockInfo[block].pageBits &= ~(1 << page);
1953 dev->blockInfo[block].pagesInUse--;
1955 if( dev->blockInfo[block].pagesInUse == 0 &&
1956 dev->blockInfo[block].blockState == YAFFS_BLOCK_STATE_FULL)
1958 yaffs_BlockBecameDirty(dev,block);
1964 T(("Bad news deleting chunk %d\n",chunkId));
1972 int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
1974 // Find old chunk Need to do this to get serial number
1975 // Write new one and patch into tree.
1976 // Invalidate old tags.
1979 yaffs_Tags prevTags;
1984 yaffs_Device *dev = in->myDev;
1986 yaffs_CheckGarbageCollection(dev);
1988 // Get the previous chunk at this location in the file if it exists
1989 prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
1992 newTags.chunkId = chunkInInode;
1993 newTags.objectId = in->objectId;
1994 newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
1995 newTags.byteCount = nBytes;
1996 newTags.unusedStuff = 0xFFFFFFFF;
1998 yaffs_CalcTagsECC(&newTags);
2002 // Create new chunk in NAND
2003 newChunkId = yaffs_AllocatePage(dev,useReserve);
2010 yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,buffer,&newTags);
2012 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId);
2015 if(prevChunkId >= 0)
2017 yaffs_DeleteChunk(dev,prevChunkId);
2021 yaffs_CheckFileSanity(in);
2030 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
2033 yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId,0);
2036 if(prevChunkId >= 0)
2038 yaffs_DeleteChunk(dev,prevChunkId);
2042 yaffs_CheckFileSanity(in);
2053 // UpdateObjectHeader updates the header on NAND for an object.
2054 // If name is not NULL, then that new name is used.
2056 int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name)
2059 yaffs_Device *dev = in->myDev;
2065 __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
2066 __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
2068 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
2069 yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
2074 yaffs_CheckGarbageCollection(dev);
2076 memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
2078 prevChunkId = in->chunkId;
2080 if(prevChunkId >= 0)
2082 yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL);
2086 oh->type = in->variantType;
2088 oh->st_mode = in->st_mode;
2089 oh->st_uid = in->st_uid;
2090 oh->st_gid = in->st_gid;
2091 oh->st_atime = in->st_atime;
2092 oh->st_mtime = in->st_mtime;
2093 oh->st_ctime = in->st_ctime;
2095 oh->parentObjectId = in->parent->objectId;
2099 memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
2100 strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
2104 memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
2107 switch(in->variantType)
2109 case YAFFS_OBJECT_TYPE_UNKNOWN:
2110 // Should not happen
2112 case YAFFS_OBJECT_TYPE_FILE:
2113 oh->fileSize = in->variant.fileVariant.fileSize;
2115 case YAFFS_OBJECT_TYPE_HARDLINK:
2116 oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
2118 case YAFFS_OBJECT_TYPE_DIRECTORY:
2121 case YAFFS_OBJECT_TYPE_SYMLINK:
2122 strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
2123 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2129 newTags.chunkId = 0;
2130 newTags.objectId = in->objectId;
2131 newTags.serialNumber = in->serial;
2132 newTags.byteCount = 0xFFFFFFFF;
2133 newTags.unusedStuff = 0xFFFFFFFF;
2135 yaffs_CalcTagsECC(&newTags);
2140 // Create new chunk in NAND
2141 newChunkId = yaffs_AllocatePage(dev,1);
2146 yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,bufferNew,&newTags);
2148 in->chunkId = newChunkId;
2150 if(prevChunkId >= 0)
2152 yaffs_DeleteChunk(dev,prevChunkId);
2161 // Create new chunk in NAND
2162 newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags,1);
2167 in->chunkId = newChunkId;
2169 if(prevChunkId >= 0)
2171 yaffs_DeleteChunk(dev,prevChunkId);
2186 ///////////////////////// File read/write ///////////////////////////////
2187 // Read and write have very similar structures.
2188 // In general the read/write has three parts to it
2189 // * An incomplete chunk to start with (if the read/write is not chunk-aligned)
2190 // * Some complete chunks
2191 // * An incomplete chunk to end off with
2193 // Curve-balls: the first chunk might also be the last chunk.
2195 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
2198 // yaffs_Device *dev = in->myDev;
2200 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2210 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
2211 start = offset % YAFFS_BYTES_PER_CHUNK;
2213 // OK now check for the curveball where the start and end are in
2215 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
2221 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
2224 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
2226 // An incomplete start or end chunk (or maybe both start and end chunk)
2227 // Read into the local buffer then copy...
2229 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2230 memcpy(buffer,&localBuffer[start],nToCopy);
2234 // A full chunk. Read directly into the supplied buffer.
2235 yaffs_ReadChunkDataFromObject(in,chunk,buffer);
2249 int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
2251 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2259 int endOfWrite = offset+nBytes;
2260 int chunkWritten = 0;
2262 while(n > 0 && chunkWritten >= 0)
2264 chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
2265 start = offset % YAFFS_BYTES_PER_CHUNK;
2268 // OK now check for the curveball where the start and end are in
2270 if( (start + n) < YAFFS_BYTES_PER_CHUNK)
2273 nToWriteBack = (start + n);
2277 nToCopy = YAFFS_BYTES_PER_CHUNK - start;
2278 nToWriteBack = YAFFS_BYTES_PER_CHUNK;
2281 if(nToCopy != YAFFS_BYTES_PER_CHUNK)
2283 // An incomplete start or end chunk (or maybe both start and end chunk)
2284 // Read into the local buffer then copy, then copy over and write back.
2286 yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
2288 memcpy(&localBuffer[start],buffer,nToCopy);
2290 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,nToWriteBack,0);
2292 T(("Write with readback to chunk %d %d\n",chunk,chunkWritten));
2297 // A full chunk. Write directly from the supplied buffer.
2298 chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
2299 T(("Write to chunk %d %d\n",chunk,chunkWritten));
2302 if(chunkWritten >= 0)
2312 // Update file object
2314 if(endOfWrite > in->variant.fileVariant.fileSize)
2316 in->variant.fileVariant.fileSize = endOfWrite;
2320 in->st_mtime = CURRENT_TIME;
2326 int yaffs_ResizeFile(yaffs_Object *in, int newSize)
2330 int oldFileSize = in->variant.fileVariant.fileSize;
2331 int sizeOfLastChunk = newSize % YAFFS_BYTES_PER_CHUNK;
2333 yaffs_Device *dev = in->myDev;
2335 __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
2337 if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
2339 return yaffs_GetFileSize(in);
2342 if(newSize < oldFileSize)
2345 int lastDel = 1 + oldFileSize/YAFFS_BYTES_PER_CHUNK;
2347 int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
2348 YAFFS_BYTES_PER_CHUNK;
2350 for(i = startDel; i <= lastDel; i++)
2352 // NB this could be optimised somewhat,
2353 // eg. could retrieve the tags and write them without
2354 // using yaffs_DeleteChunk
2355 chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
2356 if(chunkId < 0 || chunkId >= (dev->endBlock * 32))
2358 T(("Found daft chunkId %d for %d\n",chunkId,i));
2362 yaffs_DeleteChunk(dev,chunkId);
2367 if(sizeOfLastChunk != 0)
2369 int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
2371 // Got to read and rewrite the last chunk with its new size.
2372 yaffs_ReadChunkDataFromObject(in,lastChunk,localBuffer);
2374 yaffs_WriteChunkDataToObject(in,lastChunk,localBuffer,sizeOfLastChunk,1);
2378 in->variant.fileVariant.fileSize = newSize;
2380 yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
2392 loff_t yaffs_GetFileSize(yaffs_Object *obj)
2394 obj = yaffs_GetEquivalentObject(obj);
2396 switch(obj->variantType)
2398 case YAFFS_OBJECT_TYPE_FILE:
2399 return obj->variant.fileVariant.fileSize;
2400 case YAFFS_OBJECT_TYPE_SYMLINK:
2401 return strlen(obj->variant.symLinkVariant.alias);
2409 // yaffs_FlushFile() updates the file's
2412 int yaffs_FlushFile(yaffs_Object *in)
2417 T(("flushing object header\n"));
2418 retVal = yaffs_UpdateObjectHeader(in,NULL);
2430 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
2432 yaffs_RemoveObjectFromDirectory(in);
2433 yaffs_DeleteChunk(in->myDev,in->chunkId);
2434 yaffs_FreeObject(in);
2439 // yaffs_DeleteFile deletes the whole file data
2440 // and the inode associated with the file.
2441 // It does not delete the links associated with the file.
2442 static int yaffs_DeleteFile(yaffs_Object *in)
2444 // Delete the file data & tnodes
2445 yaffs_ResizeFile(in,0);
2446 yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
2448 return yaffs_DoGenericObjectDeletion(in);
2451 static int yaffs_DeleteDirectory(yaffs_Object *in)
2453 //First check that the directory is empty.
2454 if(list_empty(&in->variant.directoryVariant.children))
2456 return yaffs_DoGenericObjectDeletion(in);
2463 static int yaffs_DeleteSymLink(yaffs_Object *in)
2465 YFREE(in->variant.symLinkVariant.alias);
2467 return yaffs_DoGenericObjectDeletion(in);
2470 static int yaffs_DeleteHardLink(yaffs_Object *in)
2472 // remove this hardlink from the list assocaited with the equivalent
2474 list_del(&in->hardLinks);
2475 return yaffs_DoGenericObjectDeletion(in);
2479 static int yaffs_UnlinkWorker(yaffs_Object *obj)
2483 if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
2485 return yaffs_DeleteHardLink(obj);
2487 else if(!list_empty(&obj->hardLinks))
2490 // Curve ball: We're unlinking an object that has a hardlink.
2491 // Therefore we can't really delete the object.
2492 // Instead, we do the following:
2493 // - Select a hardlink.
2494 // - Re-type a hardlink as the equivalent object and populate the fields, including the
2495 // objectId. Updating the object id is important so that all the hardlinks do not need
2497 // - Update the equivalet object pointers.
2498 // - Delete all object.
2501 struct list_head *i;
2504 yaffs_RemoveObjectFromDirectory(obj);
2508 hl = list_entry(obj->hardLinks.next, yaffs_Object,hardLinks);
2511 hl->st_mode = obj->st_mode;
2512 hl->st_uid = obj->st_uid;
2513 hl->st_gid = obj->st_gid;
2514 hl->st_atime = obj->st_atime;
2515 hl->st_mtime = obj->st_mtime;
2516 hl->st_ctime = obj->st_ctime;
2518 hl->variantType = obj->variantType;
2520 switch(hl->variantType)
2522 case YAFFS_OBJECT_TYPE_FILE:
2523 case YAFFS_OBJECT_TYPE_SYMLINK:
2524 // These types are OK to just copy across.
2525 hl->variant = obj->variant;
2527 case YAFFS_OBJECT_TYPE_DIRECTORY:
2529 list_add(&hl->variant.directoryVariant.children,
2530 &obj->variant.directoryVariant.children);
2531 list_del(&obj->variant.directoryVariant.children);
2533 // Now change all the directory children to point to the new parent.
2534 list_for_each(i,&hl->variant.directoryVariant.children)
2536 list_entry(i,yaffs_Object,siblings)->parent = hl;
2540 case YAFFS_OBJECT_TYPE_HARDLINK:
2541 case YAFFS_OBJECT_TYPE_UNKNOWN:
2542 // Should not be either of these types.
2545 // Now fix up the hardlink chain
2546 list_del(&obj->hardLinks);
2548 list_for_each(i,&hl->hardLinks)
2550 list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObject = hl;
2551 list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObjectId = hl->objectId;
2554 // Now fix up the hash links.
2555 yaffs_UnhashObject(hl);
2556 hl->objectId = obj->objectId;
2557 yaffs_HashObject(hl);
2559 // Update the hardlink which has become an object
2560 yaffs_UpdateObjectHeader(hl,NULL);
2562 // Finally throw away the deleted object
2563 yaffs_DeleteChunk(obj->myDev,obj->chunkId);
2564 yaffs_FreeObject(obj);
2568 // Curve ball: We're unlinking an object that has a hardlink.
2570 // This problem arises because we are not strictly following
2571 // The Linux link/inode model.
2573 // We can't really delete the object.
2574 // Instead, we do the following:
2575 // - Select a hardlink.
2576 // - Unhook it from the hard links
2577 // - Unhook it from its parent directory (so that the rename can work)
2578 // - Rename the object to the hardlink's name.
2579 // - Delete the hardlink
2584 char name[YAFFS_MAX_NAME_LENGTH+1];
2586 hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
2588 list_del_init(&hl->hardLinks);
2589 list_del_init(&hl->siblings);
2591 yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
2593 retVal = yaffs_ChangeObjectName(obj, hl->parent, name);
2595 if(retVal == YAFFS_OK)
2597 retVal = yaffs_DoGenericObjectDeletion(hl);
2607 switch(obj->variantType)
2609 case YAFFS_OBJECT_TYPE_FILE:
2610 return yaffs_DeleteFile(obj);
2612 case YAFFS_OBJECT_TYPE_DIRECTORY:
2613 return yaffs_DeleteDirectory(obj);
2615 case YAFFS_OBJECT_TYPE_SYMLINK:
2616 return yaffs_DeleteSymLink(obj);
2618 case YAFFS_OBJECT_TYPE_HARDLINK:
2619 case YAFFS_OBJECT_TYPE_UNKNOWN:
2626 int yaffs_Unlink(yaffs_Object *dir, const char *name)
2630 obj = yaffs_FindObjectByName(dir,name);
2632 if(obj && obj->unlinkAllowed)
2634 return yaffs_UnlinkWorker(obj);
2641 //////////////// Initialisation Scanning /////////////////
2644 static int yaffs_Scan(yaffs_Device *dev)
2652 yaffs_BlockState state;
2653 yaffs_Object *hardList = NULL;
2659 yaffs_ObjectHeader *oh;
2661 yaffs_Object *parent;
2663 __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
2666 // Scan all the blocks...
2668 for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
2671 dev->blockInfo[blk].pageBits = 0;
2672 dev->blockInfo[blk].pagesInUse = 0;
2673 state = YAFFS_BLOCK_STATE_SCANNING;
2675 // Read each chunk in the block.
2677 for(c = 0; c < YAFFS_CHUNKS_PER_BLOCK &&
2678 state == YAFFS_BLOCK_STATE_SCANNING; c++)
2680 // Read the spare area and decide what to do
2681 chunk = blk * YAFFS_CHUNKS_PER_BLOCK + c;
2683 yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare);
2686 // Is this a valid block?
2687 if(yaffs_countBits[spare.blockStatus] >= 7)
2689 // This block looks ok, now what's in this chunk?
2690 yaffs_GetTagsFromSpare(&spare,&tags);
2692 if(yaffs_countBits[spare.pageStatus] < 6)
2696 dev->nFreeChunks ++;
2697 T((" %d %d deleted\n",blk,c));
2699 else if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
2701 // An unassigned chunk in the block
2702 // This means that either the block is empty or
2703 // this is the one being allocated from
2707 // the block is unused
2708 state = YAFFS_BLOCK_STATE_EMPTY;
2709 dev->nErasedBlocks++;
2713 // this is the block being allocated from
2714 T((" allocating %d %d\n",blk,c));
2715 state = YAFFS_BLOCK_STATE_ALLOCATING;
2716 dev->allocationBlock = blk;
2717 dev->allocationPage = c;
2720 dev->nFreeChunks += (YAFFS_CHUNKS_PER_BLOCK - c);
2722 else if(tags.chunkId > 0)
2725 dev->blockInfo[blk].pageBits |= (1 << c);
2726 dev->blockInfo[blk].pagesInUse++;
2728 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
2729 // PutChunkIntoFIle checks for a clash (two data chunks with
2730 // the same chunkId).
2731 yaffs_PutChunkIntoFile(in,tags.chunkId,chunk,1);
2732 T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
2736 // chunkId == 0, so it is an ObjectHeader.
2737 // Thus, we read in the object header and make the object
2738 dev->blockInfo[blk].pageBits |= (1 << c);
2739 dev->blockInfo[blk].pagesInUse++;
2741 yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL);
2743 oh = (yaffs_ObjectHeader *)chunkData;
2745 in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
2749 // We have already filled this one. We have a duplicate and need to resolve it.
2751 unsigned existingSerial = in->serial;
2752 unsigned newSerial = tags.serialNumber;
2754 if(((existingSerial+1) & 3) == newSerial)
2756 // Use new one - destroy the exisiting one
2757 yaffs_DeleteChunk(dev,in->chunkId);
2762 // Use existing - destroy this one.
2763 yaffs_DeleteChunk(dev,chunk);
2769 // we need to load this info
2772 in->variantType = oh->type;
2774 in->st_mode = oh->st_mode;
2775 in->st_uid = oh->st_uid;
2776 in->st_gid = oh->st_gid;
2777 in->st_atime = oh->st_atime;
2778 in->st_mtime = oh->st_mtime;
2779 in->st_ctime = oh->st_ctime;
2780 in->chunkId = chunk;
2785 // directory stuff...
2786 // hook up to parent
2788 parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
2789 if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
2791 // Set up as a directory
2792 parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
2793 INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
2795 else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2797 // Hoosterman, another problem....
2798 // We're trying to use a non-directory as a directory
2802 yaffs_AddObjectToDirectory(parent,in);
2804 // Note re hardlinks.
2805 // Since we might scan a hardlink before its equivalent object is scanned
2806 // we put them all in a list.
2807 // After scanning is complete, we should have all the objects, so we run through this
2808 // list and fix up all the chains.
2810 switch(in->variantType)
2812 case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
2814 case YAFFS_OBJECT_TYPE_FILE:
2815 in->variant.fileVariant.fileSize = oh->fileSize;
2817 case YAFFS_OBJECT_TYPE_HARDLINK:
2818 in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
2819 (yaffs_Object *)(in->hardLinks.next) = hardList;
2822 case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
2824 case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
2825 in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
2828 T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
2835 state = YAFFS_BLOCK_STATE_DEAD;
2839 if(state == YAFFS_BLOCK_STATE_SCANNING)
2841 // If we got this far while scanning, then the block is fully allocated.
2842 state = YAFFS_BLOCK_STATE_FULL;
2845 dev->blockInfo[blk].blockState = state;
2847 // Now let's see if it was dirty
2848 if( dev->blockInfo[blk].pagesInUse == 0 &&
2849 dev->blockInfo[blk].blockState == YAFFS_BLOCK_STATE_FULL)
2851 yaffs_BlockBecameDirty(dev,blk);
2856 // Fix up the hard link chains.
2857 // We should now have scanned all the objects, now it's time to add these
2862 hardList = (yaffs_Object *)(hardList->hardLinks.next);
2864 in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
2868 // Add the hardlink pointers
2869 hl->variant.hardLinkVariant.equivalentObject=in;
2870 list_add(&hl->hardLinks,&in->hardLinks);
2874 //Todo Need to report/handle this better.
2875 // Got a problem... hardlink to a non-existant object
2876 hl->variant.hardLinkVariant.equivalentObject=NULL;
2877 INIT_LIST_HEAD(&hl->hardLinks);
2889 ////////////////////////// Directory Functions /////////////////////////
2892 static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
2895 if(obj->siblings.prev == NULL)
2898 INIT_LIST_HEAD(&obj->siblings);
2901 else if(!list_empty(&obj->siblings))
2903 // If it is holed up somewhere else, un hook it
2904 list_del_init(&obj->siblings);
2907 list_add(&obj->siblings,&directory->variant.directoryVariant.children);
2908 obj->parent = directory;
2911 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
2913 list_del_init(&obj->siblings);
2917 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
2921 struct list_head *i;
2922 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
2923 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
2927 sum = yaffs_CalcNameSum(name);
2929 list_for_each(i,&directory->variant.directoryVariant.children)
2931 l = list_entry(i, yaffs_Object,siblings);
2933 // Special case for lost-n-found
2934 if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
2936 if(strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
2941 else if(l->sum == sum)
2944 yaffs_ReadChunkFromNAND(l->myDev,l->chunkId,buffer,NULL);
2945 if(strcmp(name,oh->name) == 0)
2958 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
2960 struct list_head *i;
2964 list_for_each(i,&theDir->variant.directoryVariant.children)
2966 l = list_entry(i, yaffs_Object,siblings);
2978 // GetEquivalentObject dereferences any hard links to get to the
2981 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
2983 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
2985 // We want the object id of the equivalent object, not this one
2986 obj = obj->variant.hardLinkVariant.equivalentObject;
2992 int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
2994 memset(name,0,buffSize);
2996 if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
2998 strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
3002 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
3003 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
3005 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
3007 if(obj->chunkId >= 0)
3009 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
3011 strncpy(name,oh->name,buffSize - 1);
3014 return strlen(name);
3017 int yaffs_GetObjectFileLength(yaffs_Object *obj)
3020 // Dereference any hard linking
3021 obj = yaffs_GetEquivalentObject(obj);
3023 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3025 return obj->variant.fileVariant.fileSize;
3027 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
3029 return strlen(obj->variant.symLinkVariant.alias);
3033 // Only a directory should drop through to here
3034 return YAFFS_BYTES_PER_CHUNK;
3038 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
3040 int count = 1; // the object itself
3041 struct list_head *i;
3043 list_for_each(i,&obj->hardLinks)
3052 int yaffs_GetObjectInode(yaffs_Object *obj)
3054 obj = yaffs_GetEquivalentObject(obj);
3056 return obj->objectId;
3059 unsigned yaffs_GetObjectType(yaffs_Object *obj)
3061 obj = yaffs_GetEquivalentObject(obj);
3063 switch(obj->variantType)
3065 case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
3066 case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
3067 case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
3068 case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
3069 default: return DT_REG; break;
3073 char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
3075 obj = yaffs_GetEquivalentObject(obj);
3076 if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
3078 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
3082 return yaffs_CloneString("");
3087 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
3089 unsigned int valid = attr->ia_valid;
3091 if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
3092 if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
3093 if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
3095 if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
3096 if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
3097 if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
3099 if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
3101 yaffs_UpdateObjectHeader(obj,NULL);
3106 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
3108 unsigned int valid = 0;
3110 attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
3111 attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
3112 attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
3114 attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
3115 attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
3116 attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
3118 attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
3120 attr->ia_valid = valid;
3128 int yaffs_DumpObject(yaffs_Object *obj)
3130 __u8 buffer[YAFFS_BYTES_PER_CHUNK];
3132 // yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
3134 memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
3136 if(obj->chunkId >= 0)
3138 yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
3141 yaffs_GetObjectName(obj,name,256);
3143 YPRINTF(("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d type %d size %d\n",
3144 obj->objectId,yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
3145 obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
3148 YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
3149 obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
3150 obj->sum, obj->chunkId));
3151 switch(obj->variantType)
3153 case YAFFS_OBJECT_TYPE_FILE:
3154 YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
3156 case YAFFS_OBJECT_TYPE_DIRECTORY:
3157 YPRINTF((" DIRECTORY\n"));
3159 case YAFFS_OBJECT_TYPE_HARDLINK: //todo
3160 case YAFFS_OBJECT_TYPE_SYMLINK:
3161 case YAFFS_OBJECT_TYPE_UNKNOWN:
3170 ///////////////////////// Initialisation code ///////////////////////////
3174 int yaffs_GutsInitialise(yaffs_Device *dev)
3182 if(!yaffs_CheckStructures())
3188 // OK now calculate a few things for the device
3189 // Calculate chunkGroupBits.
3190 // If there are 64k or less chunks then this is 1
3191 // Else it is log2(nChunks) - 16
3193 x = nChunks = YAFFS_CHUNKS_PER_BLOCK * dev->nBlocks;
3195 for(bits = 0, x = nChunks; (x & 1) == 0; bits++)
3203 YPRINTF(("nBlocks should be a power of 2 but is %u\n",
3210 dev->chunkGroupBits = 0;
3211 dev->chunkGroupSize = 1;
3215 dev->chunkGroupBits = bits - 16;
3216 dev->chunkGroupSize = nChunks/0x10000;
3219 // More device initialisation
3220 dev->garbageCollectionRequired = 0;
3221 dev->currentDirtyChecker = 0;
3223 yaffs_InitialiseBlocks(dev);
3225 yaffs_InitialiseTnodes(dev);
3227 yaffs_InitialiseObjects(dev);
3230 // Initialise the root and lost and found directories
3231 dev->lostNFoundDir = dev->rootDir = NULL;
3232 dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
3233 dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_ROOT_MODE | S_IFDIR);
3234 yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
3236 // Now scan the flash.
3244 void yaffs_Deinitialise(yaffs_Device *dev)
3246 yaffs_DeinitialiseBlocks(dev);
3247 yaffs_DeinitialiseTnodes(dev);
3248 yaffs_DeinitialiseObjects(dev);
3252 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
3254 int nFree = dev->nFreeChunks - (YAFFS_CHUNKS_PER_BLOCK * YAFFS_RESERVED_BLOCKS);
3256 return (nFree < 0) ? 0 : nFree;
3261 /////////////////// YAFFS test code //////////////////////////////////
3263 #define yaffs_CheckStruct(structure,syze, name) \
3264 if(sizeof(structure) != syze) \
3265 { YPRINTF(("%s should be %d but is %d\n",name,syze,sizeof(structure))); \
3266 return YAFFS_FAIL; \
3270 static int yaffs_CheckStructures(void)
3272 yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
3273 yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
3274 yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
3275 yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
3276 yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
3282 void yaffs_GutsTest(yaffs_Device *dev)
3285 if(yaffs_CheckStructures() != YAFFS_OK)
3287 YPRINTF(("One or more structures malformed-- aborting\n"));
3291 YPRINTF(("Structures OK\n"));
3294 yaffs_TnodeTest(dev);
3295 yaffs_ObjectTest(dev);