+/*
+ * YAFFS: Yet another FFS. A NAND-flash specific file system.
+ * yaffs_guts.c The main guts of YAFFS
+ *
+ * Copyright (C) 2002 Aleph One Ltd.
+ * for Toby Churchill Ltd and Brightstar Engineering
+ *
+ * Created by Charles Manning <charles@aleph1.co.uk>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ */
+ //yaffs_guts.c
+
+#include "yportenv.h"
+
+#include "yaffsinterface.h"
+#include "yaffs_guts.h"
+
+
+#if 0
+#define T(x) printf x
+#else
+#define T(x)
+#endif
+
+
+// countBits is a quick way of counting the number of bits in a byte.
+// ie. countBits[n] holds the number of 1 bits in a byte with the value n.
+
+static const char yaffs_countBits[256] =
+{
+0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
+1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
+1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
+2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
+1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
+2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
+2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
+3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
+1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
+2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
+2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
+3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
+2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
+3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
+3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
+4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
+};
+
+
+
+// Device info
+//static yaffs_Device *yaffs_device;
+//yaffs_Object *yaffs_rootDir;
+//yaffs_Object *yaffs_lostNFound;
+
+
+
+// Local prototypes
+static int yaffs_CheckObjectHashSanity(yaffs_Device *dev);
+static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr);
+static void yaffs_GetTagsFromSpare(yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr);
+static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND);
+
+static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type);
+static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj);
+static int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name);
+static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId);
+static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
+static int yaffs_CheckStructures(void);
+static yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj);
+
+loff_t yaffs_GetFileSize(yaffs_Object *obj);
+
+
+static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve);
+
+#if YAFFS_PARANOID
+static int yaffs_CheckFileSanity(yaffs_Object *in)
+#else
+#define yaffs_CheckFileSanity(in)
+#endif
+
+static int __inline__ yaffs_HashFunction(int n)
+{
+ return (n % YAFFS_NOBJECT_BUCKETS);
+}
+
+
+yaffs_Object *yaffs_Root(yaffs_Device *dev)
+{
+ return dev->rootDir;
+}
+
+yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
+{
+ return dev->lostNFoundDir;
+}
+
+
+static int yaffs_WriteChunkToNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, const __u8 *data, yaffs_Spare *spare)
+{
+ return dev->writeChunkToNAND(dev,chunkInNAND,data,spare);
+}
+
+int yaffs_ReadChunkFromNAND(struct yaffs_DeviceStruct *dev,int chunkInNAND, __u8 *data, yaffs_Spare *spare)
+{
+ return dev->readChunkFromNAND(dev,chunkInNAND,data,spare);
+}
+
+int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,int blockInNAND)
+{
+ return dev->eraseBlockInNAND(dev,blockInNAND);
+}
+
+int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
+{
+ return dev->initialiseNAND(dev);
+}
+
+static int yaffs_WriteNewChunkToNAND(struct yaffs_DeviceStruct *dev, const __u8 *data, yaffs_Spare *spare,int useReserve)
+{
+ int chunk;
+
+ int writeOk = 0;
+
+ do{
+ chunk = yaffs_AllocateChunk(dev,useReserve);
+
+ if(chunk >= 0)
+ {
+ writeOk = yaffs_WriteChunkToNAND(dev,chunk,data,spare);
+ if(writeOk)
+ {
+ //Todo read-back and verify
+ // If verify fails, then delete this chunk and try again
+ }
+ }
+ } while(chunk >= 0 && ! writeOk);
+
+ return chunk;
+}
+
+
+
+
+///////////////////////// Object management //////////////////
+// List of spare objects
+// The list is hooked together using the first pointer
+// in the object
+
+// static yaffs_Object *yaffs_freeObjects = NULL;
+
+// static int yaffs_nFreeObjects;
+
+// static yaffs_ObjectList *yaffs_allocatedObjectList = NULL;
+
+// static yaffs_ObjectBucket yaffs_objectBucket[YAFFS_NOBJECT_BUCKETS];
+
+
+static __u16 yaffs_CalcNameSum(const char *name)
+{
+ __u16 sum = 0;
+ __u16 i = 1;
+
+ __u8 *bname = (__u8 *)name;
+
+ while (*bname)
+ {
+ sum += (*bname) * i;
+ i++;
+ bname++;
+ }
+ return sum;
+}
+
+
+void yaffs_CalcECC(const __u8 *buffer, yaffs_Spare *spare)
+{
+
+ // Todo do nothing now. Need to put in ecc
+ spare->ecc1[0] = spare->ecc1[1] = spare->ecc1[2] = 0xFF;
+ spare->ecc2[0] = spare->ecc2[1] = spare->ecc2[2] = 0xFF;
+}
+
+void yaffs_CalcTagsECC(yaffs_Tags *tags)
+{
+ // Todo don't do anything yet. Need to calculate ecc
+ tags->ecc = 0xFFFFFFFF;
+}
+
+
+
+///////////////////////// TNODES ///////////////////////
+
+// List of spare tnodes
+// The list is hooked together using the first pointer
+// in the tnode.
+
+//static yaffs_Tnode *yaffs_freeTnodes = NULL;
+
+// static int yaffs_nFreeTnodes;
+
+//static yaffs_TnodeList *yaffs_allocatedTnodeList = NULL;
+
+
+
+// yaffs_CreateTnodes creates a bunch more tnodes and
+// adds them to the tnode free list.
+// Don't use this function directly
+
+static int yaffs_CreateTnodes(yaffs_Device *dev,int nTnodes)
+{
+ int i;
+ yaffs_Tnode *newTnodes;
+ yaffs_TnodeList *tnl;
+
+ if(nTnodes < 1) return YAFFS_OK;
+
+ // make these things
+
+ newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
+
+ if (!newTnodes)
+ {
+ YALERT("Could not malloc tnodes");
+ return YAFFS_FAIL;
+ }
+
+ // Hook them into the free list
+ for(i = 0; i < nTnodes - 1; i++)
+ {
+ newTnodes[i].internal[0] = &newTnodes[i+1];
+ }
+
+ newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
+ dev->freeTnodes = newTnodes;
+ dev->nFreeTnodes+= nTnodes;
+ dev->nTnodesCreated += nTnodes;
+
+ // Now add this bunch of tnodes to a list for freeing up.
+
+ tnl = YMALLOC(sizeof(yaffs_TnodeList));
+ if(!tnl)
+ {
+ YALERT("Could not add tnodes to management list");
+ }
+ else
+ {
+ tnl->tnodes = newTnodes;
+ tnl->next = dev->allocatedTnodeList;
+ dev->allocatedTnodeList = tnl;
+ }
+
+
+ YINFO("Tnodes created");
+
+
+ return YAFFS_OK;
+}
+
+
+// GetTnode gets us a clean tnode. Tries to make allocate more if we run out
+static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
+{
+ yaffs_Tnode *tn = NULL;
+
+ // If there are none left make more
+ if(!dev->freeTnodes)
+ {
+ yaffs_CreateTnodes(dev,YAFFS_ALLOCATION_NTNODES);
+ }
+
+ if(dev->freeTnodes)
+ {
+ tn = dev->freeTnodes;
+ dev->freeTnodes = dev->freeTnodes->internal[0];
+ dev->nFreeTnodes--;
+ // zero out
+ memset(tn,0,sizeof(yaffs_Tnode));
+ }
+
+
+ return tn;
+}
+
+
+// FreeTnode frees up a tnode and puts it back on the free list
+static void yaffs_FreeTnode(yaffs_Device*dev, yaffs_Tnode *tn)
+{
+ tn->internal[0] = dev->freeTnodes;
+ dev->freeTnodes = tn;
+ dev->nFreeTnodes++;
+}
+
+
+static void yaffs_DeinitialiseTnodes(yaffs_Device*dev)
+{
+ // Free the list of allocated tnodes
+
+ while(dev->allocatedTnodeList)
+ {
+ YFREE(dev->allocatedTnodeList->tnodes);
+ dev->allocatedTnodeList = dev->allocatedTnodeList->next;
+ }
+
+ dev->freeTnodes = NULL;
+ dev->nFreeTnodes = 0;
+}
+
+static void yaffs_InitialiseTnodes(yaffs_Device*dev)
+{
+ dev->allocatedTnodeList = NULL;
+ dev->freeTnodes = NULL;
+ dev->nFreeTnodes = 0;
+ dev->nTnodesCreated = 0;
+
+}
+
+void yaffs_TnodeTest(yaffs_Device *dev)
+{
+
+ int i;
+ int j;
+ yaffs_Tnode *tn[1000];
+
+ YINFO("Testing TNodes");
+
+ for(j = 0; j < 50; j++)
+ {
+ for(i = 0; i < 1000; i++)
+ {
+ tn[i] = yaffs_GetTnode(dev);
+ if(!tn[i])
+ {
+ YALERT("Getting tnode failed");
+ }
+ }
+ for(i = 0; i < 1000; i+=3)
+ {
+ yaffs_FreeTnode(dev,tn[i]);
+ tn[i] = NULL;
+ }
+
+ }
+}
+
+////////////////// END OF TNODE MANIPULATION ///////////////////////////
+
+/////////////// Functions to manipulate the look-up tree (made up of tnodes)
+// The look up tree is represented by the top tnode and the number of topLevel
+// in the tree. 0 means only the level 0 tnode is in the tree.
+
+
+// FindLevel0Tnode finds the level 0 tnode, if one exists.
+// Used when reading.....
+static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,yaffs_FileStructure *fStruct, __u32 chunkId)
+{
+
+ yaffs_Tnode *tn = fStruct->top;
+ __u32 i;
+ int requiredTallness;
+ int level = fStruct->topLevel;
+
+ // Check sane level and chunk Id
+ if(level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
+ {
+ char str[50];
+ sprintf(str,"Bad level %d",level);
+ YALERT(str);
+ return NULL;
+ }
+ if(chunkId > YAFFS_MAX_CHUNK_ID)
+ {
+ char str[50];
+ sprintf(str,"Bad chunkId %d",chunkId);
+ YALERT(str);
+ return NULL;
+ }
+
+ // First check we're tall enough (ie enough topLevel)
+
+ i = chunkId >> (dev->chunkGroupBits + YAFFS_TNODES_LEVEL0_BITS);
+ requiredTallness = 0;
+ while(i)
+ {
+ i >>= YAFFS_TNODES_INTERNAL_BITS;
+ requiredTallness++;
+ }
+
+
+ if(requiredTallness > fStruct->topLevel)
+ {
+ // Not tall enough, so we can't find it, return NULL.
+ return NULL;
+ }
+
+
+ // Traverse down to level 0
+ while (level > 0 && tn)
+ {
+ tn = tn->internal[(chunkId >>(dev->chunkGroupBits + YAFFS_TNODES_LEVEL0_BITS + (level-1) * YAFFS_TNODES_INTERNAL_BITS)) &
+ YAFFS_TNODES_INTERNAL_MASK];
+ level--;
+
+ }
+
+ return tn;
+}
+
+// AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
+// This happens in two steps:
+// 1. If the tree isn't tall enough, then make it taller.
+// 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
+//
+// Used when modifying the tree.
+//
+static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev, yaffs_FileStructure *fStruct, __u32 chunkId)
+{
+
+ yaffs_Tnode *tn;
+
+ int requiredTallness;
+
+ __u32 i;
+ __u32 l;
+
+
+ T(("AddOrFind topLevel=%d, chunk=%d",fStruct->topLevel,chunkId));
+
+ // Check sane level and page Id
+ if(fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
+ {
+ char str[50];
+ sprintf(str,"Bad level %d",fStruct->topLevel);
+ YALERT(str);
+ return NULL;
+ }
+
+ if(chunkId > YAFFS_MAX_CHUNK_ID)
+ {
+ char str[50];
+ sprintf(str,"Bad chunkId %d",chunkId);
+ YALERT(str);
+ return NULL;
+ }
+
+ // First check we're tall enough (ie enough topLevel)
+
+ i = chunkId >> (dev->chunkGroupBits + YAFFS_TNODES_LEVEL0_BITS);
+ requiredTallness = 0;
+ while(i)
+ {
+ i >>= YAFFS_TNODES_INTERNAL_BITS;
+ requiredTallness++;
+ }
+
+ T((" required=%d",requiredTallness));
+
+
+ if(requiredTallness > fStruct->topLevel)
+ {
+ // Not tall enough,gotta make the tree taller
+ for(i = fStruct->topLevel; i < requiredTallness; i++)
+ {
+ T((" add new top"));
+
+ tn = yaffs_GetTnode(dev);
+
+ if(tn)
+ {
+ tn->internal[0] = fStruct->top;
+ fStruct->top = tn;
+ }
+ else
+ {
+ YALERT("No more tnodes");
+ }
+ }
+
+ fStruct->topLevel = requiredTallness;
+ }
+
+
+ // Traverse down to level 0, adding anything we need
+
+ l = fStruct->topLevel;
+ tn = fStruct->top;
+ while (l > 0 && tn)
+ {
+ i = (chunkId >> (dev->chunkGroupBits +YAFFS_TNODES_LEVEL0_BITS + (l-1) * YAFFS_TNODES_INTERNAL_BITS)) &
+ YAFFS_TNODES_INTERNAL_MASK;
+
+ T((" [%d:%d]",l,i));
+
+ if(!tn->internal[i])
+ {
+ T((" added"));
+
+ tn->internal[i] = yaffs_GetTnode(dev);
+ }
+
+ tn = tn->internal[i];
+ l--;
+
+ }
+
+ T(("\n"));
+
+ return tn;
+}
+
+
+// Pruning removes any part of the file structure tree that is beyond the
+// bounds of the file.
+// A file should only get pruned when its size is reduced.
+//
+// Before pruning, the chunks must be pulled from the tree and the
+// level 0 tnode entries must be zeroed out.
+// Could also use this for file deletion, but that's probably better handled
+// by a special case.
+
+// yaffs_PruneWorker should only be called by yaffs_PruneFileStructure()
+
+static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn, __u32 level, int del0)
+{
+ int i;
+ int hasData;
+
+ if(tn)
+ {
+ hasData = 0;
+
+ for(i = 0; i < YAFFS_NTNODES_INTERNAL; i++)
+ {
+ if(tn->internal[i] && level > 0)
+ {
+ tn->internal[i] = yaffs_PruneWorker(dev,tn->internal[i],level - 1, ( i == 0) ? del0 : 1);
+ }
+
+ if(tn->internal[i])
+ {
+ hasData++;
+ }
+ }
+
+ if(hasData == 0 && del0)
+ {
+ // Free and return NULL
+
+ yaffs_FreeTnode(dev,tn);
+ tn = NULL;
+ }
+
+ }
+
+ return tn;
+
+}
+
+static int yaffs_PruneFileStructure(yaffs_Device *dev, yaffs_FileStructure *fStruct)
+{
+ int i;
+ int hasData;
+ int done = 0;
+ yaffs_Tnode *tn;
+
+ if(fStruct->topLevel > 0)
+ {
+ fStruct->top = yaffs_PruneWorker(dev,fStruct->top, fStruct->topLevel,0);
+
+ // Now we have a tree with all the non-zero branches NULL but the height
+ // is the same as it was.
+ // Let's see if we can trim internal tnodes to shorten the tree.
+ // We can do this if only the 0th element in the tnode is in use
+ // (ie all the non-zero are NULL)
+
+ while(fStruct->topLevel && !done)
+ {
+ tn = fStruct->top;
+
+ hasData = 0;
+ for(i = 1; i <YAFFS_NTNODES_INTERNAL; i++)
+ {
+ if(tn->internal[i])
+ {
+ hasData++;
+ }
+ }
+
+ if(!hasData)
+ {
+ fStruct->top = tn->internal[0];
+ fStruct->topLevel--;
+ yaffs_FreeTnode(dev,tn);
+ }
+ else
+ {
+ done = 1;
+ }
+ }
+ }
+
+ return YAFFS_OK;
+}
+
+
+
+
+/////////////////////// End of File Structure functions. /////////////////
+
+// yaffs_CreateFreeObjects creates a bunch more objects and
+// adds them to the object free list.
+static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
+{
+ int i;
+ yaffs_Object *newObjects;
+ yaffs_ObjectList *list;
+
+ if(nObjects < 1) return YAFFS_OK;
+
+ // make these things
+
+ newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
+
+ if (!newObjects)
+ {
+ YALERT("Could not allocate more objects");
+ return YAFFS_FAIL;
+ }
+
+ // Hook them into the free list
+ for(i = 0; i < nObjects - 1; i++)
+ {
+ (yaffs_Object *)newObjects[i].siblings.next = &newObjects[i+1];
+ }
+
+ newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
+ dev->freeObjects = newObjects;
+ dev->nFreeObjects+= nObjects;
+ dev->nObjectsCreated+= nObjects;
+
+ // Now add this bunch of Objects to a list for freeing up.
+
+ list = YMALLOC(sizeof(yaffs_ObjectList));
+ if(!list)
+ {
+ YALERT("Could not add Objects to management list");
+ }
+ else
+ {
+ list->objects = newObjects;
+ list->next = dev->allocatedObjectList;
+ dev->allocatedObjectList = list;
+ }
+
+
+ YINFO("Objects created");
+
+
+ return YAFFS_OK;
+}
+
+
+// AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out
+static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
+{
+ yaffs_Object *tn = NULL;
+
+ // If there are none left make more
+ if(!dev->freeObjects)
+ {
+ yaffs_CreateFreeObjects(dev,YAFFS_ALLOCATION_NOBJECTS);
+ }
+
+ if(dev->freeObjects)
+ {
+ tn = dev->freeObjects;
+ dev->freeObjects = (yaffs_Object *)(dev->freeObjects->siblings.next);
+ dev->nFreeObjects--;
+
+ // Now sweeten it up...
+
+ memset(tn,0,sizeof(yaffs_Object));
+ tn->chunkId = -1;
+ tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
+ INIT_LIST_HEAD(&(tn->hardLinks));
+ INIT_LIST_HEAD(&(tn->hashLink));
+ INIT_LIST_HEAD(&tn->siblings);
+
+ // Add it to the lost and found directory.
+ // NB Can't put root or lostNFound in lostNFound so
+ // check if lostNFound exists first
+ if(dev->lostNFoundDir)
+ {
+ yaffs_AddObjectToDirectory(dev->lostNFoundDir,tn);
+ }
+ }
+
+
+ return tn;
+}
+
+static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev,int number,__u32 mode)
+{
+
+ yaffs_Object *obj = yaffs_CreateNewObject(dev,number,YAFFS_OBJECT_TYPE_DIRECTORY);
+ if(obj)
+ {
+ obj->fake = 1; // it is fake so it has no NAND presence...
+ obj->renameAllowed= 0; // ... and we're not allowed to rename it...
+ obj->unlinkAllowed= 0; // ... or unlink it
+ obj->st_mode = mode;
+ obj->myDev = dev;
+ obj->chunkId = 0; // Not a valid chunk.
+ }
+
+ return obj;
+
+}
+
+
+static void yaffs_UnhashObject(yaffs_Object *tn)
+{
+ int bucket;
+ yaffs_Device *dev = tn->myDev;
+
+
+ // If it is still linked into the bucket list, free from the list
+ if(!list_empty(&tn->hashLink))
+ {
+ list_del_init(&tn->hashLink);
+ bucket = yaffs_HashFunction(tn->objectId);
+ dev->objectBucket[bucket].count--;
+ }
+
+}
+
+
+// FreeObject frees up a Object and puts it back on the free list
+static void yaffs_FreeObject(yaffs_Object *tn)
+{
+
+ yaffs_Device *dev = tn->myDev;
+
+ yaffs_UnhashObject(tn);
+
+ // Link into the free list.
+ (yaffs_Object *)(tn->siblings.next) = dev->freeObjects;
+ dev->freeObjects = tn;
+ dev->nFreeObjects++;
+}
+
+
+
+
+static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
+{
+ // Free the list of allocated Objects
+
+ while( dev->allocatedObjectList)
+ {
+ YFREE(dev->allocatedObjectList->objects);
+ dev->allocatedObjectList = dev->allocatedObjectList->next;
+ }
+
+ dev->freeObjects = NULL;
+ dev->nFreeObjects = 0;
+}
+
+static void yaffs_InitialiseObjects(yaffs_Device *dev)
+{
+ int i;
+
+ dev->allocatedObjectList = NULL;
+ dev->freeObjects = NULL;
+ dev->nFreeObjects = 0;
+
+ for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++)
+ {
+ INIT_LIST_HEAD(&dev->objectBucket[i].list);
+ dev->objectBucket[i].count = 0;
+ }
+
+}
+
+
+
+
+
+
+int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
+{
+ static int x = 0;
+ int i;
+ int l = 999;
+ int lowest = 999999;
+
+
+ // First let's see if we can find one that's empty.
+
+ for(i = 0; i < 10 && lowest > 0; i++)
+ {
+ x++;
+ x %= YAFFS_NOBJECT_BUCKETS;
+ if(dev->objectBucket[x].count < lowest)
+ {
+ lowest = dev->objectBucket[x].count;
+ l = x;
+ }
+
+ }
+
+ // If we didn't find an empty list, then try
+ // looking a bit further for a short one
+
+ for(i = 0; i < 10 && lowest > 3; i++)
+ {
+ x++;
+ x %= YAFFS_NOBJECT_BUCKETS;
+ if(dev->objectBucket[x].count < lowest)
+ {
+ lowest = dev->objectBucket[x].count;
+ l = x;
+ }
+
+ }
+
+ return l;
+}
+
+static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
+{
+ int bucket = yaffs_FindNiceObjectBucket(dev);
+
+ // Now find an object value that has not already been taken
+ // by scanning the list.
+
+ int found = 0;
+ struct list_head *i;
+
+ int n = bucket;
+
+ //yaffs_CheckObjectHashSanity();
+
+ while(!found)
+ {
+ found = 1;
+ n += YAFFS_NOBJECT_BUCKETS;
+ if(1 ||dev->objectBucket[bucket].count > 0)
+ {
+ list_for_each(i,&dev->objectBucket[bucket].list)
+ {
+ // If there is already one in the list
+ if(list_entry(i, yaffs_Object,hashLink)->objectId == n)
+ {
+ found = 0;
+ }
+ }
+ }
+ }
+
+ //T(("bucket %d count %d inode %d\n",bucket,yaffs_objectBucket[bucket].count,n);
+
+ return n;
+}
+
+void yaffs_HashObject(yaffs_Object *in)
+{
+ int bucket = yaffs_HashFunction(in->objectId);
+ yaffs_Device *dev = in->myDev;
+
+ if(!list_empty(&in->hashLink))
+ {
+ YINFO("!!!");
+ }
+
+
+ list_add(&in->hashLink,&dev->objectBucket[bucket].list);
+ dev->objectBucket[bucket].count++;
+
+}
+
+yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev,int number)
+{
+ int bucket = yaffs_HashFunction(number);
+ struct list_head *i;
+ yaffs_Object *in;
+
+ list_for_each(i,&dev->objectBucket[bucket].list)
+ {
+ // Lookm if it is in the list
+ in = list_entry(i, yaffs_Object,hashLink);
+ if(in->objectId == number)
+ {
+ return in;
+ }
+ }
+
+ return NULL;
+}
+
+
+
+yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev,int number,yaffs_ObjectType type)
+{
+
+ yaffs_Object *theObject;
+
+ if(number < 0)
+ {
+ number = yaffs_CreateNewObjectNumber(dev);
+ }
+
+ theObject = yaffs_AllocateEmptyObject(dev);
+
+ if(theObject)
+ {
+ theObject->fake = 0;
+ theObject->renameAllowed = 1;
+ theObject->unlinkAllowed = 1;
+ theObject->objectId = number;
+ theObject->myDev = dev;
+ yaffs_HashObject(theObject);
+ theObject->variantType = type;
+ theObject->st_atime = theObject->st_mtime = theObject->st_ctime = CURRENT_TIME;
+
+ switch(type)
+ {
+ case YAFFS_OBJECT_TYPE_FILE:
+ theObject->variant.fileVariant.fileSize = 0;
+ theObject->variant.fileVariant.topLevel = 0;
+ theObject->variant.fileVariant.top = yaffs_GetTnode(dev);
+ break;
+ case YAFFS_OBJECT_TYPE_DIRECTORY:
+ INIT_LIST_HEAD(&theObject->variant.directoryVariant.children);
+ break;
+ case YAFFS_OBJECT_TYPE_SYMLINK:
+ break;
+ case YAFFS_OBJECT_TYPE_HARDLINK:
+ break;
+ case YAFFS_OBJECT_TYPE_UNKNOWN:
+ // todo this should not happen
+ }
+ }
+
+ return theObject;
+}
+
+yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev, int number,yaffs_ObjectType type)
+{
+ yaffs_Object *theObject = NULL;
+
+ if(number >= 0)
+ {
+ theObject = yaffs_FindObjectByNumber(dev,number);
+ }
+
+ if(!theObject)
+ {
+ theObject = yaffs_CreateNewObject(dev,number,type);
+ }
+
+ return theObject;
+
+}
+
+char *yaffs_CloneString(const char *str)
+{
+ char *newStr = NULL;
+
+ if(str && *str)
+ {
+ newStr = YMALLOC(strlen(str) + 1);
+ strcpy(newStr,str);
+ }
+
+ return newStr;
+
+}
+
+//
+// Mknod (create) a new object.
+// equivalentObject only has meaning for a hard link;
+// aliasString only has meaning for a sumlink.
+yaffs_Object *yaffs_MknodObject( yaffs_ObjectType type,
+ yaffs_Object *parent,
+ const char *name,
+ __u32 mode,
+ __u32 uid,
+ __u32 gid,
+ yaffs_Object *equivalentObject,
+ const char *aliasString)
+{
+ yaffs_Object *in;
+
+ yaffs_Device *dev = parent->myDev;
+
+ in = yaffs_CreateNewObject(dev,-1,type);
+
+ if(in)
+ {
+ in->chunkId = -1;
+ in->valid = 1;
+ in->variantType = type;
+
+ in->st_mode = mode;
+ in->st_uid = uid;
+ in->st_gid = gid;
+ in->st_atime = in->st_mtime = in->st_ctime = CURRENT_TIME;
+
+ in->sum = yaffs_CalcNameSum(name);
+ in->dirty = 1;
+
+ yaffs_AddObjectToDirectory(parent,in);
+
+ in->myDev = parent->myDev;
+
+
+ switch(type)
+ {
+ case YAFFS_OBJECT_TYPE_SYMLINK:
+ in->variant.symLinkVariant.alias = yaffs_CloneString(aliasString);
+ break;
+ case YAFFS_OBJECT_TYPE_HARDLINK:
+ in->variant.hardLinkVariant.equivalentObject = equivalentObject;
+ in->variant.hardLinkVariant.equivalentObjectId = equivalentObject->objectId;
+ list_add(&in->hardLinks,&equivalentObject->hardLinks);
+ break;
+ case YAFFS_OBJECT_TYPE_FILE: // do nothing
+ case YAFFS_OBJECT_TYPE_DIRECTORY: // do nothing
+ case YAFFS_OBJECT_TYPE_UNKNOWN:
+ }
+
+ yaffs_UpdateObjectHeader(in,name);
+
+ }
+
+ return in;
+}
+
+yaffs_Object *yaffs_MknodFile(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
+{
+ return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE,parent,name,mode,uid,gid,NULL,NULL);
+}
+
+yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid)
+{
+ return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY,parent,name,mode,uid,gid,NULL,NULL);
+}
+
+yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent,const char *name, __u32 mode, __u32 uid, __u32 gid,const char *alias)
+{
+ return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK,parent,name,mode,uid,gid,NULL,alias);
+}
+
+// NB yaffs_Link returns the object id of the equivalent object.
+yaffs_Object *yaffs_Link(yaffs_Object *parent, const char *name, yaffs_Object *equivalentObject)
+{
+ // Get the real object in case we were fed a hard link as an equivalent object
+ equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
+
+ if(yaffs_MknodObject(YAFFS_OBJECT_TYPE_HARDLINK,parent,name,0,0,0,equivalentObject,NULL))
+ {
+ return equivalentObject;
+ }
+ else
+ {
+ return NULL;
+ }
+
+}
+
+
+static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir, const char *newName)
+{
+ //yaffs_Device *dev = obj->myDev;
+
+ if(newDir == NULL)
+ {
+ newDir = obj->parent; // use the old directory
+ }
+
+ // Only proceed if the new name does not exist and
+ // if we're putting it into a directory.
+ if(!yaffs_FindObjectByName(newDir,newName) &&
+ newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
+ {
+ obj->sum = yaffs_CalcNameSum(newName);
+ obj->dirty = 1;
+ yaffs_AddObjectToDirectory(newDir,obj);
+
+ return yaffs_UpdateObjectHeader(obj,newName);
+ }
+
+ return YAFFS_FAIL;
+}
+
+int yaffs_RenameObject(yaffs_Object *oldDir, const char *oldName, yaffs_Object *newDir, const char *newName)
+{
+ yaffs_Object *obj;
+
+ obj = yaffs_FindObjectByName(oldDir,oldName);
+ if(obj && obj->renameAllowed)
+ {
+ return yaffs_ChangeObjectName(obj,newDir,newName);
+ }
+ return YAFFS_FAIL;
+}
+
+
+
+static int yaffs_CheckObjectHashSanity(yaffs_Device *dev)
+{
+ // Scan the buckets and check that the lists
+ // have as many members as the count says there are
+ int bucket;
+ int countEm;
+ struct list_head *j;
+ int ok = YAFFS_OK;
+
+ for(bucket = 0; bucket < YAFFS_NOBJECT_BUCKETS; bucket++)
+ {
+ countEm = 0;
+
+ list_for_each(j,&dev->objectBucket[bucket].list)
+ {
+ countEm++;
+ }
+
+ if(countEm != dev->objectBucket[bucket].count)
+ {
+ YALERT("Inode hash inconsistency");
+ ok = YAFFS_FAIL;
+ }
+ }
+
+ return ok;
+}
+
+void yaffs_ObjectTest(yaffs_Device *dev)
+{
+ yaffs_Object *in[1000];
+ int inNo[1000];
+ yaffs_Object *inold[1000];
+ int i;
+ int j;
+
+ memset(in,0,1000*sizeof(yaffs_Object *));
+ memset(inold,0,1000*sizeof(yaffs_Object *));
+
+ yaffs_CheckObjectHashSanity(dev);
+
+ for(j = 0; j < 10; j++)
+ {
+ T(("%d\n",j));
+
+ for(i = 0; i < 1000; i++)
+ {
+ in[i] = yaffs_CreateNewObject(dev,-1,YAFFS_OBJECT_TYPE_FILE);
+ if(!in[i])
+ {
+ YINFO("No more inodes");
+ }
+ else
+ {
+ inNo[i] = in[i]->objectId;
+ }
+ }
+
+ for(i = 0; i < 1000; i++)
+ {
+ if(yaffs_FindObjectByNumber(dev,inNo[i]) != in[i])
+ {
+ T(("Differnce in look up test\n"));
+ }
+ else
+ {
+ // T(("Look up ok\n"));
+ }
+ }
+
+ yaffs_CheckObjectHashSanity(dev);
+
+ for(i = 0; i < 1000; i+=3)
+ {
+ yaffs_FreeObject(in[i]);
+ in[i] = NULL;
+ }
+
+
+ yaffs_CheckObjectHashSanity(dev);
+ }
+
+}
+
+
+
+/////////////////////////// Block Management and Page Allocation ///////////////////
+
+
+static void yaffs_InitialiseBlocks(yaffs_Device *dev)
+{
+ dev->blockInfo = YMALLOC(dev->nBlocks * sizeof(yaffs_BlockInfo));
+ memset(dev->blockInfo,0,dev->nBlocks * sizeof(yaffs_BlockInfo));
+ dev->allocationBlock = -1; // force it to get a new one
+}
+
+static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
+{
+ YFREE(dev->blockInfo);
+}
+
+// FindDiretiestBlock is used to select the dirtiest block (or close enough)
+// for garbage collection.
+
+static int yaffs_FindDirtiestBlock(yaffs_Device *dev)
+{
+
+ int b = dev->currentDirtyChecker;
+
+ int i;
+ int dirtiest = -1;
+ int pagesInUse = 100; // silly big number
+
+ for(i = dev->startBlock; i <= dev->endBlock && pagesInUse > 2 ; i++)
+ {
+ b++;
+ if (b > dev->endBlock)
+ {
+ b = dev->startBlock;
+ }
+
+ if(dev->blockInfo[b].blockState == YAFFS_BLOCK_STATE_FULL &&
+ (dev->blockInfo)[b].pagesInUse < pagesInUse)
+ {
+ dirtiest = b;
+ pagesInUse = (dev->blockInfo)[b].pagesInUse;
+ }
+ }
+
+ dev->currentDirtyChecker = b;
+
+ return dirtiest;
+}
+
+
+static int yaffs_FindBlockForAllocation(yaffs_Device *dev,int useReserve)
+{
+ int i;
+
+ if(useReserve && dev->nErasedBlocks < 1)
+ {
+ // Hoosterman we've got a problem.
+ // Can't get space to gc
+ return -1;
+ }
+ else if(!useReserve && dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
+ {
+ // We are not in GC, so we hold some in reserve so we can get
+ // a gc done.
+ }
+
+ // Find an empty block.
+
+ for(i = dev->startBlock; i <= dev->endBlock; i++)
+ {
+
+ if(dev->blockInfo[i].blockState == YAFFS_BLOCK_STATE_EMPTY)
+ {
+ dev->blockInfo[i].blockState = YAFFS_BLOCK_STATE_ALLOCATING;
+ dev->nErasedBlocks--;
+ if(dev->nErasedBlocks <= YAFFS_RESERVED_BLOCKS)
+ {
+ dev->garbageCollectionRequired = 1;
+ }
+
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+
+static void yaffs_BlockBecameDirty(yaffs_Device *dev,int blockNo)
+{
+ yaffs_BlockInfo *bi = &dev->blockInfo[blockNo];
+
+ // Mark as dirty, erase it and mark as clean.
+ bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
+ yaffs_EraseBlockInNAND(dev,blockNo);
+ bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
+ dev->nErasedBlocks++;
+ bi->pagesInUse = 0;
+ bi->pageBits = 0;
+
+ T(("Erased block %d\n",blockNo));
+}
+
+
+static int yaffs_AllocateChunk(yaffs_Device *dev,int useReserve)
+{
+ int retVal;
+
+ if(dev->allocationBlock < 0)
+ {
+ // Get next block to allocate off
+ dev->allocationBlock = yaffs_FindBlockForAllocation(dev,useReserve);
+ dev->allocationPage = 0;
+ }
+
+ // Next page please....
+ if(dev->allocationBlock >= 0)
+ {
+ retVal = (dev->allocationBlock * YAFFS_CHUNKS_PER_BLOCK) +
+ dev->allocationPage;
+ dev->blockInfo[dev->allocationBlock].pagesInUse++;
+ dev->blockInfo[dev->allocationBlock].pageBits |=
+ (1 << (dev->allocationPage));
+
+ dev->allocationPage++;
+
+ dev->nFreeChunks--;
+
+ // If the block is full set the state to full
+ if(dev->allocationPage >= YAFFS_CHUNKS_PER_BLOCK)
+ {
+ dev->blockInfo[dev->allocationBlock].blockState = YAFFS_BLOCK_STATE_FULL;
+ dev->allocationBlock = -1;
+ }
+
+#ifdef YAFFS_PARANOID
+ if(yaffs_CheckChunkErased(retVal) == YAFFS_FAIL)
+ {
+ T(("..................Trying to allocate non-erased page %d\n",retVal));
+ }
+#endif
+ return retVal;
+
+ }
+ T(("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!\n"));
+
+ return -1;
+}
+
+
+int yaffs_GarbageCollectBlock(yaffs_Device *dev,int block)
+{
+ int oldChunk;
+ int newChunk;
+ __u32 mask;
+
+
+ yaffs_Spare spare;
+ yaffs_Tags tags;
+ __u8 buffer[YAFFS_BYTES_PER_CHUNK];
+
+ yaffs_BlockInfo *bi = &dev->blockInfo[block];
+
+ yaffs_Object *object;
+
+ T(("Collecting block %d n %d bits %x\n",block, bi->pagesInUse, bi->pageBits));
+
+ for(mask = 1,oldChunk = block * YAFFS_CHUNKS_PER_BLOCK;
+ mask && bi->pageBits;
+ mask <<= 1, oldChunk++ )
+ {
+ if(bi->pageBits & mask)
+ {
+
+ // This page is in use and needs to be copied off
+
+ T(("copying page %x from %d to %d\n",mask,oldChunk,newChunk));
+
+ yaffs_ReadChunkFromNAND(dev,oldChunk,buffer, &spare);
+
+ yaffs_GetTagsFromSpare(&spare,&tags);
+ tags.serialNumber++;
+ yaffs_LoadTagsIntoSpare(&spare,&tags);
+
+#if 0
+ newChunk = yaffs_AllocatePage(dev,1);
+ if(newChunk < 0)
+ {
+ return YAFFS_FAIL;
+ }
+
+ yaffs_WriteChunkToNAND(dev,newChunk, buffer, &spare);
+
+#else
+ newChunk = yaffs_WriteNewChunkToNAND(dev, buffer, &spare,1);
+#endif
+ if(newChunk < 0)
+ {
+ return YAFFS_FAIL;
+ }
+
+ object = yaffs_FindObjectByNumber(dev,tags.objectId);
+
+ // Ok, now fix up the Tnodes etc.
+
+ if(tags.chunkId == 0)
+ {
+ // It's a header
+ object->chunkId = newChunk;
+ }
+ else
+ {
+ // It's a data chunk
+ yaffs_PutChunkIntoFile(object, tags.chunkId, newChunk);
+
+ }
+
+ yaffs_DeleteChunk(dev,oldChunk);
+
+ }
+ }
+
+ return YAFFS_OK;
+}
+
+int yaffs_CheckGarbageCollection(yaffs_Device *dev)
+{
+ int block;
+
+ if(dev->garbageCollectionRequired)
+ {
+ dev->garbageCollectionRequired = 0;
+ block = yaffs_FindDirtiestBlock(dev);
+ if(block >= 0)
+ {
+ return yaffs_GarbageCollectBlock(dev,block);
+ }
+ else
+ {
+ return YAFFS_FAIL;
+ }
+ }
+
+ return YAFFS_OK;
+}
+
+
+//////////////////////////// TAGS ///////////////////////////////////////
+
+static void yaffs_LoadTagsIntoSpare(yaffs_Spare *sparePtr, yaffs_Tags *tagsPtr)
+{
+ yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
+
+ yaffs_CalcTagsECC(tagsPtr);
+
+ sparePtr->tagByte0 = tu->asBytes[0];
+ sparePtr->tagByte1 = tu->asBytes[1];
+ sparePtr->tagByte2 = tu->asBytes[2];
+ sparePtr->tagByte3 = tu->asBytes[3];
+ sparePtr->tagByte4 = tu->asBytes[4];
+ sparePtr->tagByte5 = tu->asBytes[5];
+ sparePtr->tagByte6 = tu->asBytes[6];
+ sparePtr->tagByte7 = tu->asBytes[7];
+}
+
+static void yaffs_GetTagsFromSpare(yaffs_Spare *sparePtr,yaffs_Tags *tagsPtr)
+{
+ yaffs_TagsUnion *tu = (yaffs_TagsUnion *)tagsPtr;
+
+ tu->asBytes[0]= sparePtr->tagByte0;
+ tu->asBytes[1]= sparePtr->tagByte1;
+ tu->asBytes[2]= sparePtr->tagByte2;
+ tu->asBytes[3]= sparePtr->tagByte3;
+ tu->asBytes[4]= sparePtr->tagByte4;
+ tu->asBytes[5]= sparePtr->tagByte5;
+ tu->asBytes[6]= sparePtr->tagByte6;
+ tu->asBytes[7]= sparePtr->tagByte7;
+
+ // Todo Check ECC on tags
+}
+
+static void yaffs_SpareInitialise(yaffs_Spare *spare)
+{
+ memset(spare,0xFF,sizeof(yaffs_Spare));
+}
+
+static int yaffs_ReadChunkTagsFromNAND(yaffs_Device *dev,int chunkInNAND, yaffs_Tags *tags)
+{
+ if(tags)
+ {
+ yaffs_Spare spare;
+ if(yaffs_ReadChunkFromNAND(dev,chunkInNAND,NULL,&spare) == YAFFS_OK)
+ {
+ yaffs_GetTagsFromSpare(&spare,tags);
+ return YAFFS_OK;
+ }
+ else
+ {
+ return YAFFS_FAIL;
+ }
+ }
+
+ return YAFFS_OK;
+}
+
+static int yaffs_WriteChunkWithTagsToNAND(yaffs_Device *dev,int chunkInNAND, const __u8 *buffer, yaffs_Tags *tags)
+{
+ // NB There must be tags, data is optional
+ // If there is data, then an ECC is calculated on it.
+
+ yaffs_Spare spare;
+
+ if(!tags)
+ {
+ return YAFFS_FAIL;
+ }
+
+ yaffs_SpareInitialise(&spare);
+
+
+ if(buffer)
+ {
+ yaffs_CalcECC(buffer,&spare);
+ }
+
+ yaffs_LoadTagsIntoSpare(&spare,tags);
+
+ return yaffs_WriteChunkToNAND(dev,chunkInNAND,buffer,&spare);
+
+}
+
+static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev, const __u8 *buffer, yaffs_Tags *tags, int useReserve)
+{
+ // NB There must be tags, data is optional
+ // If there is data, then an ECC is calculated on it.
+
+ yaffs_Spare spare;
+
+ if(!tags)
+ {
+ return YAFFS_FAIL;
+ }
+
+ yaffs_SpareInitialise(&spare);
+
+
+ if(buffer)
+ {
+ yaffs_CalcECC(buffer,&spare);
+ }
+
+ yaffs_LoadTagsIntoSpare(&spare,tags);
+
+ return yaffs_WriteNewChunkToNAND(dev,buffer,&spare,useReserve);
+
+}
+
+
+
+
+int yaffs_FindChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
+{
+ //Get the Tnode, then get the level 0 offset chunk offset
+ yaffs_Tnode *tn;
+ int theChunk = -1;
+ yaffs_Tags localTags;
+ int i;
+ int found = 0;
+ yaffs_Device *dev = in->myDev;
+
+
+ if(!tags)
+ {
+ // Passed a NULL, so use our own tags space
+ tags = &localTags;
+ }
+
+ tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
+
+ if(tn)
+ {
+ theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
+
+ // Now we need to do the shifting etc and search for it
+ for(i = 0,found = 0; i < dev->chunkGroupSize && !found; i++)
+ {
+ yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags);
+ if(tags->chunkId == chunkInInode &&
+ tags->objectId == in->objectId)
+ {
+ // found it;
+ found = 1;
+ }
+ else
+ {
+ theChunk++;
+ }
+ }
+ }
+ return found ? theChunk : -1;
+}
+
+int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in,int chunkInInode,yaffs_Tags *tags)
+{
+ //Get the Tnode, then get the level 0 offset chunk offset
+ yaffs_Tnode *tn;
+ int theChunk = -1;
+ yaffs_Tags localTags;
+ int i;
+ int found = 0;
+ yaffs_Device *dev = in->myDev;
+
+ if(!tags)
+ {
+ // Passed a NULL, so use our own tags space
+ tags = &localTags;
+ }
+
+ tn = yaffs_FindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
+
+ if(tn)
+ {
+
+ theChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
+
+ // Now we need to do the shifting etc and search for it
+ for(i = 0,found = 0; i < dev->chunkGroupSize && !found; i++)
+ {
+ yaffs_ReadChunkTagsFromNAND(dev,theChunk,tags);
+ if(tags->chunkId == chunkInInode &&
+ tags->objectId == in->objectId)
+ {
+ // found it;
+ found = 1;
+ }
+ else
+ {
+ theChunk++;
+ }
+ }
+
+ // Delete the entry in the filestructure
+ if(found)
+ {
+ tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
+ }
+ }
+ else
+ {
+ T(("No level 0 found for %d\n", chunkInInode));
+ }
+
+ if(!found)
+ {
+ T(("Could not find %d to delete\n",chunkInInode));
+ }
+ return found ? theChunk : -1;
+}
+
+
+#if YAFFS_PARANOID
+
+static int yaffs_CheckFileSanity(yaffs_Object *in)
+{
+ int chunk;
+ int nChunks;
+ int fSize;
+ int failed = 0;
+ int objId;
+ yaffs_Tnode *tn;
+ yaffs_Tags localTags;
+ yaffs_Tags *tags = &localTags;
+ int theChunk;
+
+
+ if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
+ {
+ T(("Object not a file\n"));
+ return YAFFS_FAIL;
+ }
+
+ objId = in->objectId;
+ fSize = in->variant.fileVariant.fileSize;
+ nChunks = (fSize + YAFFS_BYTES_PER_CHUNK -1)/YAFFS_BYTES_PER_CHUNK;
+
+ for(chunk = 1; chunk <= nChunks; chunk++)
+ {
+ tn = yaffs_FindLevel0Tnode(&in->variant.fileVariant, chunk);
+
+ if(tn)
+ {
+
+ theChunk = tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << dev->chunkGroupBits;
+
+
+ yaffs_ReadChunkTagsFromNAND(theChunk,tags);
+ if(tags->chunkId == chunk &&
+ tags->objectId == in->objectId)
+ {
+ // found it;
+
+ }
+ else
+ {
+ //T(("File problem file [%d,%d] NAND %d tags[%d,%d]\n",
+ // objId,chunk,theChunk,tags->chunkId,tags->objectId);
+
+ failed = 1;
+
+ }
+
+ }
+ else
+ {
+ T(("No level 0 found for %d\n", chunk));
+ }
+ }
+
+ return failed ? YAFFS_FAIL : YAFFS_OK;
+}
+
+#endif
+
+static int yaffs_PutChunkIntoFile(yaffs_Object *in,int chunkInInode, int chunkInNAND)
+{
+ yaffs_Tnode *tn;
+ yaffs_Device *dev = in->myDev;
+
+ tn = yaffs_AddOrFindLevel0Tnode(dev,&in->variant.fileVariant, chunkInInode);
+ tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = chunkInNAND;
+ return YAFFS_OK;
+}
+
+
+
+int yaffs_ReadChunkDataFromObject(yaffs_Object *in,int chunkInInode, __u8 *buffer)
+{
+ int chunkInNAND = yaffs_FindChunkInFile(in,chunkInInode,NULL);
+
+ if(chunkInNAND >= 0)
+ {
+ return yaffs_ReadChunkFromNAND(in->myDev,chunkInNAND,buffer,NULL);
+ }
+ else
+ {
+ return 0;
+ }
+
+}
+
+
+static void yaffs_DeleteChunk(yaffs_Device *dev,int chunkId)
+{
+ int block = chunkId / YAFFS_CHUNKS_PER_BLOCK;
+ int page = chunkId % YAFFS_CHUNKS_PER_BLOCK;
+ yaffs_Tags tags;
+
+ // Mark the deleted NAND page as deleted
+ tags.chunkId = 0;
+ tags.objectId = 0;
+ tags.byteCount = 0;
+ tags.ecc = 0;
+
+ yaffs_WriteChunkWithTagsToNAND(dev,chunkId,NULL,&tags);
+
+
+ // Pull out of the management area.
+ if( dev->blockInfo[block].blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
+ dev->blockInfo[block].blockState == YAFFS_BLOCK_STATE_FULL)
+ {
+ dev->nFreeChunks++;
+
+ dev->blockInfo[block].pageBits &= ~(1 << page);
+ dev->blockInfo[block].pagesInUse--;
+
+ if( dev->blockInfo[block].pagesInUse == 0 &&
+ dev->blockInfo[block].blockState == YAFFS_BLOCK_STATE_FULL)
+ {
+ yaffs_BlockBecameDirty(dev,block);
+ }
+
+ }
+ else
+ {
+ T(("Bad news deteing chunk %d\n",chunkId));
+ }
+
+}
+
+
+
+
+int yaffs_WriteChunkDataToObject(yaffs_Object *in,int chunkInInode, const __u8 *buffer,int nBytes,int useReserve)
+{
+ // Find old chunk Need to do this to get serial number
+ // Write new one and patch into tree.
+ // Invalidate old tags.
+
+ int prevChunkId;
+ yaffs_Tags prevTags;
+
+ int newChunkId;
+ yaffs_Tags newTags;
+
+ yaffs_Device *dev = in->myDev;
+
+ yaffs_CheckGarbageCollection(dev);
+
+ // Get the previous chunk at this location in the file if it exists
+ prevChunkId = yaffs_FindChunkInFile(in,chunkInInode,&prevTags);
+
+ // Set up new tags
+ newTags.chunkId = chunkInInode;
+ newTags.objectId = in->objectId;
+ newTags.serialNumber = (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
+ newTags.byteCount = nBytes;
+ newTags.unusedStuff = 0xFFFFFFFF;
+
+ yaffs_CalcTagsECC(&newTags);
+
+
+ #if 0
+ // Create new chunk in NAND
+ newChunkId = yaffs_AllocatePage(dev,useReserve);
+
+
+ if(newChunkId >= 0)
+ {
+
+
+ yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,buffer,&newTags);
+
+ yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId);
+
+
+ if(prevChunkId >= 0)
+ {
+ yaffs_DeleteChunk(dev,prevChunkId);
+
+ }
+
+ yaffs_CheckFileSanity(in);
+
+ return newChunkId;
+ }
+
+
+ return -1;
+#else
+
+ newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,buffer,&newTags,useReserve);
+ if(newChunkId >= 0)
+ {
+ yaffs_PutChunkIntoFile(in,chunkInInode,newChunkId);
+
+
+ if(prevChunkId >= 0)
+ {
+ yaffs_DeleteChunk(dev,prevChunkId);
+
+ }
+
+ yaffs_CheckFileSanity(in);
+ }
+ return newChunkId;
+
+#endif
+
+
+
+}
+
+
+// UpdateObjectHeader updates the header on NAND for an object.
+// If name is not NULL, then that new name is used.
+//
+int yaffs_UpdateObjectHeader(yaffs_Object *in,const char *name)
+{
+
+ yaffs_Device *dev = in->myDev;
+
+ int prevChunkId;
+
+ int newChunkId;
+ yaffs_Tags newTags;
+ __u8 bufferNew[YAFFS_BYTES_PER_CHUNK];
+ __u8 bufferOld[YAFFS_BYTES_PER_CHUNK];
+
+ yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)bufferNew;
+ yaffs_ObjectHeader *ohOld = (yaffs_ObjectHeader *)bufferOld;
+
+ if(!in->fake)
+ {
+
+ yaffs_CheckGarbageCollection(dev);
+
+ memset(bufferNew,0xFF,YAFFS_BYTES_PER_CHUNK);
+
+ prevChunkId = in->chunkId;
+
+ if(prevChunkId >= 0)
+ {
+ yaffs_ReadChunkFromNAND(dev,prevChunkId,bufferOld,NULL);
+ }
+
+ // Header data
+ oh->type = in->variantType;
+
+ oh->st_mode = in->st_mode;
+ oh->st_uid = in->st_uid;
+ oh->st_gid = in->st_gid;
+ oh->st_atime = in->st_atime;
+ oh->st_mtime = in->st_mtime;
+ oh->st_ctime = in->st_ctime;
+
+ oh->parentObjectId = in->parent->objectId;
+ oh->sum = in->sum;
+ if(name && *name)
+ {
+ memset(oh->name,0,YAFFS_MAX_NAME_LENGTH + 1);
+ strncpy(oh->name,name,YAFFS_MAX_NAME_LENGTH);
+ }
+ else
+ {
+ memcpy(oh->name, ohOld->name,YAFFS_MAX_NAME_LENGTH + 1);
+ }
+
+ switch(in->variantType)
+ {
+ case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
+ break;
+ case YAFFS_OBJECT_TYPE_FILE:
+ oh->fileSize = in->variant.fileVariant.fileSize;
+ break;
+ case YAFFS_OBJECT_TYPE_HARDLINK:
+ oh->equivalentObjectId = in->variant.hardLinkVariant.equivalentObjectId;
+ break;
+ case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
+ break;
+ case YAFFS_OBJECT_TYPE_SYMLINK:
+ strncpy(oh->alias,in->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
+ oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
+ break;
+ }
+
+ // Tags
+ in->serial++;
+ newTags.chunkId = 0;
+ newTags.objectId = in->objectId;
+ newTags.serialNumber = in->serial;
+ newTags.byteCount = 0xFFFFFFFF;
+ newTags.unusedStuff = 0xFFFFFFFF;
+
+ yaffs_CalcTagsECC(&newTags);
+
+
+
+#if 0
+ // Create new chunk in NAND
+ newChunkId = yaffs_AllocatePage(dev,1);
+
+ if(newChunkId >= 0)
+ {
+
+ yaffs_WriteChunkWithTagsToNAND(dev,newChunkId,bufferNew,&newTags);
+
+ in->chunkId = newChunkId;
+
+ if(prevChunkId >= 0)
+ {
+ yaffs_DeleteChunk(dev,prevChunkId);
+ }
+
+ in->dirty = 0;
+ return newChunkId;
+ }
+
+ return -1;
+#else
+ // Create new chunk in NAND
+ newChunkId = yaffs_WriteNewChunkWithTagsToNAND(dev,bufferNew,&newTags,1);
+
+ if(newChunkId >= 0)
+ {
+
+ in->chunkId = newChunkId;
+
+ if(prevChunkId >= 0)
+ {
+ yaffs_DeleteChunk(dev,prevChunkId);
+ }
+
+ in->dirty = 0;
+ }
+
+ return newChunkId;
+
+#endif
+ }
+ return 0;
+}
+
+
+
+///////////////////////// File read/write ///////////////////////////////
+// Read and write have very similar structures.
+// In general the read/write has three parts to it
+// * An incomplete chunk to start with (if the read/write is not chunk-aligned)
+// * Some complete chunks
+// * An incomplete chunk to end off with
+//
+// Curve-balls: the first chunk might also be the last chunk.
+
+int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 * buffer, __u32 offset, int nBytes)
+{
+
+// yaffs_Device *dev = in->myDev;
+
+ __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
+
+ int chunk;
+ int start;
+ int nToCopy;
+ int n = nBytes;
+ int nDone = 0;
+
+ while(n > 0)
+ {
+ chunk = offset / YAFFS_BYTES_PER_CHUNK + 1; // The first chunk is 1
+ start = offset % YAFFS_BYTES_PER_CHUNK;
+
+ // OK now check for the curveball where the start and end are in
+ // the same chunk.
+ if( (start + n) < YAFFS_BYTES_PER_CHUNK)
+ {
+ nToCopy = n;
+ }
+ else
+ {
+ nToCopy = YAFFS_BYTES_PER_CHUNK - start;
+ }
+
+ if(nToCopy != YAFFS_BYTES_PER_CHUNK)
+ {
+ // An incomplete start or end chunk (or maybe both start and end chunk)
+ // Read into the local buffer then copy...
+
+ yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
+ memcpy(buffer,&localBuffer[start],nToCopy);
+ }
+ else
+ {
+ // A full chunk. Read directly into the supplied buffer.
+ yaffs_ReadChunkDataFromObject(in,chunk,buffer);
+ }
+
+ n -= nToCopy;
+ offset += nToCopy;
+ buffer += nToCopy;
+ nDone += nToCopy;
+
+ }
+
+ return nDone;
+}
+
+
+int yaffs_WriteDataToFile(yaffs_Object *in,const __u8 * buffer, __u32 offset, int nBytes)
+{
+ __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
+
+ int chunk;
+ int start;
+ int nToCopy;
+ int n = nBytes;
+ int nDone = 0;
+ int nToWriteBack;
+ int endOfWrite = offset+nBytes;
+ int chunkWritten = 0;
+
+ while(n > 0 && chunkWritten >= 0)
+ {
+ chunk = offset / YAFFS_BYTES_PER_CHUNK + 1;
+ start = offset % YAFFS_BYTES_PER_CHUNK;
+
+
+ // OK now check for the curveball where the start and end are in
+ // the same chunk.
+ if( (start + n) < YAFFS_BYTES_PER_CHUNK)
+ {
+ nToCopy = n;
+ nToWriteBack = (start + n);
+ }
+ else
+ {
+ nToCopy = YAFFS_BYTES_PER_CHUNK - start;
+ nToWriteBack = YAFFS_BYTES_PER_CHUNK;
+ }
+
+ if(nToCopy != YAFFS_BYTES_PER_CHUNK)
+ {
+ // An incomplete start or end chunk (or maybe both start and end chunk)
+ // Read into the local buffer then copy, then copy over and write back.
+
+ yaffs_ReadChunkDataFromObject(in,chunk,localBuffer);
+
+ memcpy(&localBuffer[start],buffer,nToCopy);
+
+ chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,localBuffer,nToWriteBack,0);
+
+ T(("Write with readback to chunk %d %d\n",chunk,chunkWritten));
+
+ }
+ else
+ {
+ // A full chunk. Write directly from the supplied buffer.
+ chunkWritten = yaffs_WriteChunkDataToObject(in,chunk,buffer,YAFFS_BYTES_PER_CHUNK,0);
+ T(("Write to chunk %d %d\n",chunk,chunkWritten));
+ }
+
+ if(chunkWritten >= 0)
+ {
+ n -= nToCopy;
+ offset += nToCopy;
+ buffer += nToCopy;
+ nDone += nToCopy;
+ }
+
+ }
+
+ // Update file object
+
+ if(endOfWrite > in->variant.fileVariant.fileSize)
+ {
+ in->variant.fileVariant.fileSize = endOfWrite;
+ }
+
+ in->dirty = 1;
+ in->st_mtime = CURRENT_TIME;
+
+ return nDone;
+}
+
+
+int yaffs_ResizeFile(yaffs_Object *in, int newSize)
+{
+ int i;
+ int chunkId;
+ int oldFileSize = in->variant.fileVariant.fileSize;
+ int sizeOfLastChunk = newSize % YAFFS_BYTES_PER_CHUNK;
+
+ yaffs_Device *dev = in->myDev;
+
+ __u8 localBuffer[YAFFS_BYTES_PER_CHUNK];
+
+ if(in->variantType != YAFFS_OBJECT_TYPE_FILE)
+ {
+ return yaffs_GetFileSize(in);
+ }
+
+ if(newSize < oldFileSize)
+ {
+
+ int lastDel = 1 + oldFileSize/YAFFS_BYTES_PER_CHUNK;
+
+ int startDel = 1 + (newSize + YAFFS_BYTES_PER_CHUNK - 1)/
+ YAFFS_BYTES_PER_CHUNK;
+
+ for(i = startDel; i <= lastDel; i++)
+ {
+ // NB this could be optimised somewhat,
+ // eg. could retrieve the tags and write them without
+ // using yaffs_DeleteChunk
+ chunkId = yaffs_FindAndDeleteChunkInFile(in,i,NULL);
+ if(chunkId < 0 || chunkId >= (dev->endBlock * 32))
+ {
+ T(("Found daft chunkId %d for %d\n",chunkId,i));
+ }
+ else
+ {
+ yaffs_DeleteChunk(dev,chunkId);
+ }
+ }
+
+
+ if(sizeOfLastChunk != 0)
+ {
+ int lastChunk = 1+ newSize/YAFFS_BYTES_PER_CHUNK;
+
+ // Got to read and rewrite the last chunk with its new size.
+ yaffs_ReadChunkDataFromObject(in,lastChunk,localBuffer);
+
+ yaffs_WriteChunkDataToObject(in,lastChunk,localBuffer,sizeOfLastChunk,1);
+
+ }
+
+ in->variant.fileVariant.fileSize = newSize;
+
+ yaffs_PruneFileStructure(dev,&in->variant.fileVariant);
+
+ return newSize;
+
+ }
+ else
+ {
+ return oldFileSize;
+ }
+}
+
+
+loff_t yaffs_GetFileSize(yaffs_Object *obj)
+{
+ obj = yaffs_GetEquivalentObject(obj);
+
+ switch(obj->variantType)
+ {
+ case YAFFS_OBJECT_TYPE_FILE:
+ return obj->variant.fileVariant.fileSize;
+ case YAFFS_OBJECT_TYPE_SYMLINK:
+ return strlen(obj->variant.symLinkVariant.alias);
+ default:
+ return 0;
+ }
+}
+
+
+
+// yaffs_FlushFile() updates the file's
+// objectId in NAND
+
+int yaffs_FlushFile(yaffs_Object *in)
+{
+ int retVal;
+ if(in->dirty)
+ {
+ retVal = yaffs_UpdateObjectHeader(in,NULL);
+ }
+ else
+ {
+ retVal = YAFFS_OK;
+ }
+
+ return retVal;
+
+}
+
+
+static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
+{
+ yaffs_RemoveObjectFromDirectory(in);
+ yaffs_DeleteChunk(in->myDev,in->chunkId);
+ yaffs_FreeObject(in);
+ return YAFFS_OK;
+
+}
+
+// yaffs_DeleteFile deletes the whole file data
+// and the inode associated with the file.
+// It does not delete the links associated with the file.
+static int yaffs_DeleteFile(yaffs_Object *in)
+{
+ // Delete the file data & tnodes
+ yaffs_ResizeFile(in,0);
+ yaffs_FreeTnode(in->myDev,in->variant.fileVariant.top);
+
+ return yaffs_DoGenericObjectDeletion(in);
+}
+
+static int yaffs_DeleteDirectory(yaffs_Object *in)
+{
+ //First check that the directory is empty.
+ if(list_empty(&in->variant.directoryVariant.children))
+ {
+ return yaffs_DoGenericObjectDeletion(in);
+ }
+
+ return YAFFS_FAIL;
+
+}
+
+static int yaffs_DeleteSymLink(yaffs_Object *in)
+{
+ YFREE(in->variant.symLinkVariant.alias);
+
+ return yaffs_DoGenericObjectDeletion(in);
+}
+
+static int yaffs_DeleteHardLink(yaffs_Object *in)
+{
+ // remove this hardlink from the list assocaited with the equivalent
+ // object
+ list_del(&in->hardLinks);
+ return yaffs_DoGenericObjectDeletion(in);
+}
+
+
+static int yaffs_UnlinkWorker(yaffs_Object *obj)
+{
+
+
+ if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
+ {
+ return yaffs_DeleteHardLink(obj);
+ }
+ else if(!list_empty(&obj->hardLinks))
+ {
+#if 0
+ // Curve ball: We're unlinking an object that has a hardlink.
+ // Therefore we can't really delete the object.
+ // Instead, we do the following:
+ // - Select a hardlink.
+ // - Re-type a hardlink as the equivalent object and populate the fields, including the
+ // objectId. Updating the object id is important so that all the hardlinks do not need
+ // to be rewritten.
+ // - Update the equivalet object pointers.
+ // - Delete all object.
+
+ yaffs_Object *hl;
+ struct list_head *i;
+
+
+ yaffs_RemoveObjectFromDirectory(obj);
+
+
+
+ hl = list_entry(obj->hardLinks.next, yaffs_Object,hardLinks);
+
+ hl->dirty = 1;
+ hl->st_mode = obj->st_mode;
+ hl->st_uid = obj->st_uid;
+ hl->st_gid = obj->st_gid;
+ hl->st_atime = obj->st_atime;
+ hl->st_mtime = obj->st_mtime;
+ hl->st_ctime = obj->st_ctime;
+
+ hl->variantType = obj->variantType;
+
+ switch(hl->variantType)
+ {
+ case YAFFS_OBJECT_TYPE_FILE:
+ case YAFFS_OBJECT_TYPE_SYMLINK:
+ // These types are OK to just copy across.
+ hl->variant = obj->variant;
+ break;
+ case YAFFS_OBJECT_TYPE_DIRECTORY:
+ // Fix the list up
+ list_add(&hl->variant.directoryVariant.children,
+ &obj->variant.directoryVariant.children);
+ list_del(&obj->variant.directoryVariant.children);
+
+ // Now change all the directory children to point to the new parent.
+ list_for_each(i,&hl->variant.directoryVariant.children)
+ {
+ list_entry(i,yaffs_Object,siblings)->parent = hl;
+ }
+ break;
+
+ case YAFFS_OBJECT_TYPE_HARDLINK:
+ case YAFFS_OBJECT_TYPE_UNKNOWN:
+ // Should not be either of these types.
+ }
+
+ // Now fix up the hardlink chain
+ list_del(&obj->hardLinks);
+
+ list_for_each(i,&hl->hardLinks)
+ {
+ list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObject = hl;
+ list_entry(i,yaffs_Object,hardLinks)->variant.hardLinkVariant.equivalentObjectId = hl->objectId;
+ }
+
+ // Now fix up the hash links.
+ yaffs_UnhashObject(hl);
+ hl->objectId = obj->objectId;
+ yaffs_HashObject(hl);
+
+ // Update the hardlink which has become an object
+ yaffs_UpdateObjectHeader(hl,NULL);
+
+ // Finally throw away the deleted object
+ yaffs_DeleteChunk(obj->myDev,obj->chunkId);
+ yaffs_FreeObject(obj);
+
+ return YAFFS_OK;
+#else
+ // Curve ball: We're unlinking an object that has a hardlink.
+ //
+ // This problem arises because we are not strictly following
+ // The Linux link/inode model.
+ //
+ // We can't really delete the object.
+ // Instead, we do the following:
+ // - Select a hardlink.
+ // - Unhook it from the hard links
+ // - Unhook it from its parent directory (so that the rename can work)
+ // - Rename the object to the hardlink's name.
+ // - Delete the hardlink
+
+
+ yaffs_Object *hl;
+ int retVal;
+ char name[YAFFS_MAX_NAME_LENGTH+1];
+
+ hl = list_entry(obj->hardLinks.next,yaffs_Object,hardLinks);
+ list_del_init(&hl->hardLinks);
+ list_del_init(&hl->siblings);
+
+ yaffs_GetObjectName(hl,name,YAFFS_MAX_NAME_LENGTH+1);
+
+ retVal = yaffs_ChangeObjectName(obj, hl->parent, name);
+ if(retVal == YAFFS_OK)
+ {
+ retVal = yaffs_DoGenericObjectDeletion(hl);
+ }
+ return retVal;
+
+#endif
+
+
+ }
+ else
+ {
+ switch(obj->variantType)
+ {
+ case YAFFS_OBJECT_TYPE_FILE:
+ return yaffs_DeleteFile(obj);
+ break;
+ case YAFFS_OBJECT_TYPE_DIRECTORY:
+ return yaffs_DeleteDirectory(obj);
+ break;
+ case YAFFS_OBJECT_TYPE_SYMLINK:
+ return yaffs_DeleteSymLink(obj);
+ break;
+ case YAFFS_OBJECT_TYPE_HARDLINK:
+ case YAFFS_OBJECT_TYPE_UNKNOWN:
+ default:
+ return YAFFS_FAIL;
+ }
+ }
+}
+
+int yaffs_Unlink(yaffs_Object *dir, const char *name)
+{
+ yaffs_Object *obj;
+
+ obj = yaffs_FindObjectByName(dir,name);
+
+ if(obj && obj->unlinkAllowed)
+ {
+ return yaffs_UnlinkWorker(obj);
+ }
+
+ return YAFFS_FAIL;
+
+}
+
+//////////////// Initialisation Scanning /////////////////
+
+
+static int yaffs_Scan(yaffs_Device *dev)
+{
+ yaffs_Spare spare;
+ yaffs_Tags tags;
+ int blk;
+ int chunk;
+ int c;
+ int deleted;
+ int inuse;
+ yaffs_BlockState state;
+ yaffs_Object *hardList = NULL;
+ yaffs_Object *hl;
+
+ __u32 pageBits;
+
+ yaffs_ObjectHeader *oh;
+ yaffs_Object *in;
+ yaffs_Object *parent;
+
+ __u8 chunkData[YAFFS_BYTES_PER_CHUNK];
+
+ for(blk = dev->startBlock; blk <= dev->endBlock; blk++)
+ {
+ deleted = 0;
+ pageBits = 0;
+ inuse = 0;
+ state = YAFFS_BLOCK_STATE_UNKNOWN;
+
+ for(c = 0; c < YAFFS_CHUNKS_PER_BLOCK &&
+ state == YAFFS_BLOCK_STATE_UNKNOWN; c++)
+ {
+ // Read the spare area and decide what to do
+ chunk = blk * YAFFS_CHUNKS_PER_BLOCK + c;
+ yaffs_ReadChunkFromNAND(dev,chunk,NULL,&spare);
+
+
+ // Is this a valid block?
+ if(yaffs_countBits[spare.blockStatus] >= 7)
+ {
+ // This block looks ok, now what's in this chunk?
+ yaffs_GetTagsFromSpare(&spare,&tags);
+
+ if(tags.objectId == YAFFS_UNUSED_OBJECT_ID)
+ {
+ // An unassigned chunk in the block
+ // This means that either the block is empty or
+ // this is the one being allocated from
+
+ if(c == 0)
+ {
+ // the block is unused
+ state = YAFFS_BLOCK_STATE_EMPTY;
+ dev->nErasedBlocks++;
+ }
+ else
+ {
+ // this is the block being allocated from
+ T((" allocating %d %d\n",blk,c));
+ state = YAFFS_BLOCK_STATE_ALLOCATING;
+ dev->allocationBlock = blk;
+ dev->allocationPage = c;
+ }
+
+ dev->nFreeChunks += (YAFFS_CHUNKS_PER_BLOCK - c);
+ }
+ else if(tags.objectId == 0)
+ {
+ // A deleted chunk
+ deleted++;
+ dev->nFreeChunks ++;
+ T((" %d %d deleted\n",blk,c));
+ }
+ else if(tags.chunkId > 0)
+ {
+ // A data chunk.
+ inuse++;
+ pageBits |= ( 1 <<c);
+ in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,YAFFS_OBJECT_TYPE_FILE);
+ // todo check for a clash (two data chunks with
+ // the same chunkId).
+ yaffs_PutChunkIntoFile(in,tags.chunkId,chunk);
+ T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));
+ }
+ else
+ {
+ // chunkId == 0, so it is an ObjectHeader.
+ inuse++;
+ pageBits |= ( 1 <<c);
+ yaffs_ReadChunkFromNAND(dev,chunk,chunkData,NULL);
+ oh = (yaffs_ObjectHeader *)chunkData;
+
+ in = yaffs_FindOrCreateObjectByNumber(dev,tags.objectId,oh->type);
+ if(in->valid)
+ {
+ // todo we have already filled this one. We have
+ // a duplicate. Need to fix
+ }
+
+ // we don't have a duplicate...
+
+ in->valid = 1;
+ in->variantType = oh->type;
+
+ in->st_mode = oh->st_mode;
+ in->st_uid = oh->st_uid;
+ in->st_gid = oh->st_gid;
+ in->st_atime = oh->st_atime;
+ in->st_mtime = oh->st_mtime;
+ in->st_ctime = oh->st_ctime;
+ in->chunkId = chunk;
+
+ in->sum = oh->sum;
+ in->dirty = 0;
+
+ // directory stuff...
+ // hook up to parent
+
+ parent = yaffs_FindOrCreateObjectByNumber(dev,oh->parentObjectId,YAFFS_OBJECT_TYPE_DIRECTORY);
+ if(parent->variantType == YAFFS_OBJECT_TYPE_UNKNOWN)
+ {
+ // Set up as a directory
+ parent->variantType = YAFFS_OBJECT_TYPE_DIRECTORY;
+ INIT_LIST_HEAD(&parent->variant.directoryVariant.children);
+ }
+ else if(parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
+ {
+ // Hoosterman, another problem....
+ // We're trying to use a non-directory as a directory
+ // Todo ... handle
+ }
+
+ yaffs_AddObjectToDirectory(parent,in);
+
+ // Note re hardlinks.
+ // Since we might scan a hardlink before its equivalent object is scanned
+ // we put them all in a list.
+ // After scanning is complete, we should have all the objects, so we run through this
+ // list and fix up all the chains.
+
+ switch(in->variantType)
+ {
+ case YAFFS_OBJECT_TYPE_UNKNOWN: // Todo got a problem
+ break;
+ case YAFFS_OBJECT_TYPE_FILE:
+ in->variant.fileVariant.fileSize = oh->fileSize;
+ break;
+ case YAFFS_OBJECT_TYPE_HARDLINK:
+ in->variant.hardLinkVariant.equivalentObjectId = oh->equivalentObjectId;
+ (yaffs_Object *)(in->hardLinks.next) = hardList;
+ hardList = in;
+ break;
+ case YAFFS_OBJECT_TYPE_DIRECTORY: // Do nothing
+ break;
+ case YAFFS_OBJECT_TYPE_SYMLINK: // Do nothing
+ in->variant.symLinkVariant.alias = yaffs_CloneString(oh->alias);
+ break;
+ }
+ T((" %d %d header %d \"%s\" type %d\n",blk,c,tags.objectId,oh->name,in->variantType));
+ }
+ }
+ else
+ {
+ // it's a bad block
+ state = YAFFS_BLOCK_STATE_DEAD;
+ }
+ }
+
+ if(state == YAFFS_BLOCK_STATE_UNKNOWN)
+ {
+ // If we got this far, then the block is fully allocated.
+ // ie. Full or Dirty
+ state = (inuse) ? YAFFS_BLOCK_STATE_FULL : YAFFS_BLOCK_STATE_DIRTY;
+
+ }
+
+ dev->blockInfo[blk].pageBits = pageBits;
+ dev->blockInfo[blk].pagesInUse = inuse;
+ dev->blockInfo[blk].blockState = state;
+
+ }
+
+ // Todo fix up the hard link chains
+ while(hardList)
+ {
+ hl = hardList;
+ hardList = (yaffs_Object *)(hardList->hardLinks.next);
+
+ in = yaffs_FindObjectByNumber(dev,hl->variant.hardLinkVariant.equivalentObjectId);
+
+ if(in)
+ {
+ hl->variant.hardLinkVariant.equivalentObject=in;
+ list_add(&hl->hardLinks,&in->hardLinks);
+ }
+ else
+ {
+ //Todo Need to report this better.
+ hl->variant.hardLinkVariant.equivalentObject=NULL;
+ INIT_LIST_HEAD(&hl->hardLinks);
+
+ }
+
+ }
+
+
+
+ return YAFFS_OK;
+}
+
+
+////////////////////////// Directory Functions /////////////////////////
+
+
+static void yaffs_AddObjectToDirectory(yaffs_Object *directory, yaffs_Object *obj)
+{
+
+ if(obj->siblings.prev == NULL)
+ {
+ // Not initialised
+ INIT_LIST_HEAD(&obj->siblings);
+
+ }
+ else if(!list_empty(&obj->siblings))
+ {
+ // If it is holed up somewhere else, un hook it
+ list_del_init(&obj->siblings);
+ }
+ // Now add it
+ list_add(&obj->siblings,&directory->variant.directoryVariant.children);
+ obj->parent = directory;
+}
+
+static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
+{
+ list_del_init(&obj->siblings);
+ obj->parent = NULL;
+}
+
+yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,const char *name)
+{
+ int sum;
+
+ struct list_head *i;
+ __u8 buffer[YAFFS_BYTES_PER_CHUNK];
+ yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
+
+ yaffs_Object *l;
+
+ sum = yaffs_CalcNameSum(name);
+
+ list_for_each(i,&directory->variant.directoryVariant.children)
+ {
+ l = list_entry(i, yaffs_Object,siblings);
+
+ // Special case for lost-n-found
+ if(l->objectId == YAFFS_OBJECTID_LOSTNFOUND)
+ {
+ if(strcmp(name,YAFFS_LOSTNFOUND_NAME) == 0)
+ {
+ return l;
+ }
+ }
+ else if(l->sum == sum)
+ {
+ // Do a real check
+ yaffs_ReadChunkFromNAND(l->myDev,l->chunkId,buffer,NULL);
+ if(strcmp(name,oh->name) == 0)
+ {
+ return l;
+ }
+
+
+ }
+ }
+
+ return NULL;
+}
+
+
+int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,int (*fn)(yaffs_Object *))
+{
+ struct list_head *i;
+ yaffs_Object *l;
+
+
+ list_for_each(i,&theDir->variant.directoryVariant.children)
+ {
+ l = list_entry(i, yaffs_Object,siblings);
+ if(!fn(l))
+ {
+ return YAFFS_FAIL;
+ }
+ }
+
+ return YAFFS_OK;
+
+}
+
+
+// GetEquivalentObject dereferences any hard links to get to the
+// actual object.
+
+static yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
+{
+ if(obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
+ {
+ // We want the object id of the equivalent object, not this one
+ obj = obj->variant.hardLinkVariant.equivalentObject;
+ }
+ return obj;
+
+}
+
+int yaffs_GetObjectName(yaffs_Object *obj,char *name,int buffSize)
+{
+ memset(name,0,buffSize);
+
+ if(obj->objectId == YAFFS_OBJECTID_LOSTNFOUND)
+ {
+ strncpy(name,YAFFS_LOSTNFOUND_NAME,buffSize - 1);
+ }
+ else
+ {
+ __u8 buffer[YAFFS_BYTES_PER_CHUNK];
+ yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
+
+ memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
+
+ if(obj->chunkId >= 0)
+ {
+ yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
+ }
+ strncpy(name,oh->name,buffSize - 1);
+ }
+
+ return strlen(name);
+}
+
+int yaffs_GetObjectFileLength(yaffs_Object *obj)
+{
+
+ // Dereference any hard linking
+ obj = yaffs_GetEquivalentObject(obj);
+
+ if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
+ {
+ return obj->variant.fileVariant.fileSize;
+ }
+ if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
+ {
+ return strlen(obj->variant.symLinkVariant.alias);
+ }
+ else
+ {
+ // Only a directory should drop through to here
+ return YAFFS_BYTES_PER_CHUNK;
+ }
+}
+
+int yaffs_GetObjectLinkCount(yaffs_Object *obj)
+{
+ int count = 1; // the object itself
+ struct list_head *i;
+
+ list_for_each(i,&obj->hardLinks)
+ {
+ count++;
+ }
+ return count;
+
+}
+
+
+int yaffs_GetObjectInode(yaffs_Object *obj)
+{
+ obj = yaffs_GetEquivalentObject(obj);
+
+ return obj->objectId;
+}
+
+unsigned yaffs_GetObjectType(yaffs_Object *obj)
+{
+ obj = yaffs_GetEquivalentObject(obj);
+
+ switch(obj->variantType)
+ {
+ case YAFFS_OBJECT_TYPE_FILE: return DT_REG; break;
+ case YAFFS_OBJECT_TYPE_DIRECTORY: return DT_DIR; break;
+ case YAFFS_OBJECT_TYPE_SYMLINK: return DT_LNK; break;
+ case YAFFS_OBJECT_TYPE_HARDLINK: return DT_REG; break;
+ default: return DT_REG; break;
+ }
+}
+
+char *yaffs_GetSymlinkAlias(yaffs_Object *obj)
+{
+ obj = yaffs_GetEquivalentObject(obj);
+ if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
+ {
+ return yaffs_CloneString(obj->variant.symLinkVariant.alias);
+ }
+ else
+ {
+ return yaffs_CloneString("");
+ }
+}
+
+
+int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
+{
+ unsigned int valid = attr->ia_valid;
+
+ if(valid & ATTR_MODE) obj->st_mode = attr->ia_mode;
+ if(valid & ATTR_UID) obj->st_uid = attr->ia_uid;
+ if(valid & ATTR_GID) obj->st_gid = attr->ia_gid;
+
+ if(valid & ATTR_ATIME) obj->st_atime = attr->ia_atime;
+ if(valid & ATTR_CTIME) obj->st_ctime = attr->ia_ctime;
+ if(valid & ATTR_MTIME) obj->st_mtime = attr->ia_mtime;
+
+ if(valid & ATTR_SIZE) yaffs_ResizeFile(obj,attr->ia_size);
+
+ yaffs_UpdateObjectHeader(obj,NULL);
+
+ return YAFFS_OK;
+
+}
+int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
+{
+ unsigned int valid = 0;
+
+ attr->ia_mode = obj->st_mode; valid |= ATTR_MODE;
+ attr->ia_uid = obj->st_uid; valid |= ATTR_UID;
+ attr->ia_gid = obj->st_gid; valid |= ATTR_GID;
+
+ attr->ia_atime = obj->st_atime; valid |= ATTR_ATIME;
+ attr->ia_ctime = obj->st_ctime; valid |= ATTR_CTIME;
+ attr->ia_mtime = obj->st_mtime; valid |= ATTR_MTIME;
+
+ attr->ia_size = yaffs_GetFileSize(obj); valid |= ATTR_SIZE;
+
+ attr->ia_valid = valid;
+
+ return YAFFS_OK;
+
+}
+
+
+
+int yaffs_DumpObject(yaffs_Object *obj)
+{
+ __u8 buffer[YAFFS_BYTES_PER_CHUNK];
+ char name[256];
+// yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *)buffer;
+
+ memset(buffer,0,YAFFS_BYTES_PER_CHUNK);
+
+ if(obj->chunkId >= 0)
+ {
+ yaffs_ReadChunkFromNAND(obj->myDev,obj->chunkId,buffer,NULL);
+ }
+
+ yaffs_GetObjectName(obj,name,256);
+
+ YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d type %d size %d\n",
+ yaffs_GetObjectInode(obj), name, obj->dirty, obj->valid, obj->serial,
+ obj->sum, obj->chunkId, yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
+
+#if 0
+ YPRINTF(("Object %d \"%s\"\n dirty %d valid %d serial %d sum %d chunk %d\n",
+ obj->objectId, oh->name, obj->dirty, obj->valid, obj->serial,
+ obj->sum, obj->chunkId));
+ switch(obj->variantType)
+ {
+ case YAFFS_OBJECT_TYPE_FILE:
+ YPRINTF((" FILE length %d\n",obj->variant.fileVariant.fileSize));
+ break;
+ case YAFFS_OBJECT_TYPE_DIRECTORY:
+ YPRINTF((" DIRECTORY\n"));
+ break;
+ case YAFFS_OBJECT_TYPE_HARDLINK: //todo
+ case YAFFS_OBJECT_TYPE_SYMLINK:
+ case YAFFS_OBJECT_TYPE_UNKNOWN:
+ default:
+ }
+#endif
+
+ return YAFFS_OK;
+}
+
+
+///////////////////////// Initialisation code ///////////////////////////
+
+
+
+int yaffs_GutsInitialise(yaffs_Device *dev)
+{
+ unsigned nChunks,x;
+ int bits;
+
+
+ dev = dev;
+
+ if(!yaffs_CheckStructures())
+ {
+ return YAFFS_FAIL;
+ }
+
+
+ // OK now calculate a few things for the device
+ // Calculate chunkGroupBits.
+ // If there are 64k or less chunks then this is 1
+ // Else it is log2(nChunks) - 16
+ //
+ x = nChunks = YAFFS_CHUNKS_PER_BLOCK * dev->nBlocks;
+
+ for(bits = 0, x = nChunks; (x & 1) == 0; bits++)
+ {
+ x >>= 1;
+ }
+
+ if( x != 1)
+ {
+ // Not a power of 2
+ YPRINTF(("nBlocks should be a power of 2 but is %u\n",
+ dev->nBlocks));
+ return YAFFS_FAIL;
+ }
+
+ if(bits <= 16)
+ {
+ dev->chunkGroupBits = 0;
+ dev->chunkGroupSize = 1;
+ }
+ else
+ {
+ dev->chunkGroupBits = bits - 16;
+ dev->chunkGroupSize = nChunks/0x10000;
+ }
+
+ // More device initialisation
+ dev->garbageCollectionRequired = 0;
+ dev->currentDirtyChecker = 0;
+
+ yaffs_InitialiseBlocks(dev);
+
+ yaffs_InitialiseTnodes(dev);
+
+ yaffs_InitialiseObjects(dev);
+
+
+ // Initialise the root and lost and found directories
+ dev->lostNFoundDir = dev->rootDir = NULL;
+ dev->rootDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_ROOT,YAFFS_ROOT_MODE | S_IFDIR);
+ dev->lostNFoundDir = yaffs_CreateFakeDirectory(dev,YAFFS_OBJECTID_LOSTNFOUND,YAFFS_ROOT_MODE | S_IFDIR);
+ yaffs_AddObjectToDirectory(dev->rootDir,dev->lostNFoundDir);
+
+ // Now scan the flash.
+ yaffs_Scan(dev);
+
+
+ return YAFFS_OK;
+
+}
+
+void yaffs_Deinitialise(yaffs_Device *dev)
+{
+ yaffs_DeinitialiseBlocks(dev);
+ yaffs_DeinitialiseTnodes(dev);
+ yaffs_DeinitialiseObjects(dev);
+
+}
+
+int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
+{
+ int nFree = dev->nFreeChunks - (YAFFS_CHUNKS_PER_BLOCK * YAFFS_RESERVED_BLOCKS);
+
+ return (nFree < 0) ? 0 : nFree;
+
+}
+
+
+/////////////////// YAFFS test code //////////////////////////////////
+
+#define yaffs_CheckStruct(structure,syze, name) \
+ if(sizeof(structure) != syze) \
+ { YPRINTF(("%s should be %d but is %d\n",name,syze,sizeof(structure))); \
+ return YAFFS_FAIL; \
+ }
+
+
+static int yaffs_CheckStructures(void)
+{
+ yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags")
+ yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion")
+ yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare")
+ yaffs_CheckStruct(yaffs_Tnode,2* YAFFS_NTNODES_LEVEL0,"yaffs_Tnode")
+ yaffs_CheckStruct(yaffs_ObjectHeader,512,"yaffs_ObjectHeader")
+
+
+ return YAFFS_OK;
+}
+
+void yaffs_GutsTest(yaffs_Device *dev)
+{
+
+ if(yaffs_CheckStructures() != YAFFS_OK)
+ {
+ YPRINTF(("One or more structures malformed-- aborting\n"));
+ }
+ else
+ {
+ YPRINTF(("Structures OK\n"));
+ }
+
+ yaffs_TnodeTest(dev);
+ yaffs_ObjectTest(dev);
+}
+
+