2 * YAFFS: Yet another FFS. A NAND-flash specific file system.
4 * Copyright (C) 2002 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
15 const char *yaffs_guts_c_version =
16 "$Id: yaffs_guts.c,v 1.39 2006-10-03 10:13:03 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #ifdef CONFIG_YAFFS_WINCE
37 void yfsd_LockYAFFS(BOOL fsLockOnly);
38 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
41 #define YAFFS_PASSIVE_GC_CHUNKS 2
43 #include "yaffs_ecc.h"
46 /* Robustification (if it ever comes about...) */
47 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
48 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
49 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
51 const yaffs_ExtendedTags * tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
53 const yaffs_ExtendedTags * tags);
55 /* Other local prototypes */
56 static int yaffs_UnlinkObject( yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
61 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
63 yaffs_ExtendedTags * tags,
65 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
66 int chunkInNAND, int inScan);
68 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
69 yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
72 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
73 int force, int isShrink, int shadows);
74 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
75 static int yaffs_CheckStructures(void);
76 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
77 int chunkOffset, int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
82 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
83 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
86 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
89 static int yaffs_UnlinkWorker(yaffs_Object * obj);
90 static void yaffs_DestroyObject(yaffs_Object * obj);
92 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
95 loff_t yaffs_GetFileSize(yaffs_Object * obj);
97 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
99 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
101 #ifdef YAFFS_PARANOID
102 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #define yaffs_CheckFileSanity(in)
107 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
108 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
114 /* Function to calculate chunk and offset */
116 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
119 /* Easy-peasy power of 2 case */
120 *chunk = (__u32)(addr >> dev->chunkShift);
121 *offset = (__u32)(addr & dev->chunkMask);
123 else if(dev->crumbsPerChunk)
125 /* Case where we're using "crumbs" */
126 *offset = (__u32)(addr & dev->crumbMask);
127 addr >>= dev->crumbShift;
128 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
129 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
135 /* Function to return the number of shifts for a power of 2 greater than or equal
136 * to the given number
137 * Note we don't try to cater for all possible numbers and this does not have to
138 * be hellishly efficient.
141 static __u32 ShiftsGE(__u32 x)
146 nShifts = extraBits = 0;
149 if(x & 1) extraBits++;
160 /* Function to return the number of shifts to get a 1 in bit 0
163 static __u32 ShiftDiv(__u32 x)
182 * Temporary buffer manipulations.
185 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
188 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
189 if (dev->tempBuffer[i].line == 0) {
190 dev->tempBuffer[i].line = lineNo;
191 if ((i + 1) > dev->maxTemp) {
192 dev->maxTemp = i + 1;
193 for (j = 0; j <= i; j++)
194 dev->tempBuffer[j].maxLine =
195 dev->tempBuffer[j].line;
198 return dev->tempBuffer[i].buffer;
202 T(YAFFS_TRACE_BUFFERS,
203 (TSTR("Out of temp buffers at line %d, other held by lines:"),
205 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
206 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
208 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
211 * If we got here then we have to allocate an unmanaged one
215 dev->unmanagedTempAllocations++;
216 return YMALLOC(dev->nDataBytesPerChunk);
220 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
224 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
225 if (dev->tempBuffer[i].buffer == buffer) {
226 dev->tempBuffer[i].line = 0;
232 /* assume it is an unmanaged one. */
233 T(YAFFS_TRACE_BUFFERS,
234 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
237 dev->unmanagedTempDeallocations++;
243 * Determine if we have a managed buffer.
245 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
248 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
249 if (dev->tempBuffer[i].buffer == buffer)
254 for (i = 0; i < dev->nShortOpCaches; i++) {
255 if( dev->srCache[i].data == buffer )
260 if (buffer == dev->checkpointBuffer)
263 T(YAFFS_TRACE_ALWAYS,
264 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
269 * Chunk bitmap manipulations
272 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
274 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
276 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
280 return dev->chunkBits +
281 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
284 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
286 __u8 *blkBits = yaffs_BlockBits(dev, blk);
288 memset(blkBits, 0, dev->chunkBitmapStride);
291 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
293 __u8 *blkBits = yaffs_BlockBits(dev, blk);
295 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
298 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
300 __u8 *blkBits = yaffs_BlockBits(dev, blk);
302 blkBits[chunk / 8] |= (1 << (chunk & 7));
305 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
307 __u8 *blkBits = yaffs_BlockBits(dev, blk);
308 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
311 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
313 __u8 *blkBits = yaffs_BlockBits(dev, blk);
315 for (i = 0; i < dev->chunkBitmapStride; i++) {
324 * Simple hash function. Needs to have a reasonable spread
327 static Y_INLINE int yaffs_HashFunction(int n)
330 return (n % YAFFS_NOBJECT_BUCKETS);
334 * Access functions to useful fake objects
337 yaffs_Object *yaffs_Root(yaffs_Device * dev)
342 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
344 return dev->lostNFoundDir;
349 * Erased NAND checking functions
352 int yaffs_CheckFF(__u8 * buffer, int nBytes)
354 /* Horrible, slow implementation */
363 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
367 int retval = YAFFS_OK;
368 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
369 yaffs_ExtendedTags tags;
372 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
374 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
378 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
379 T(YAFFS_TRACE_NANDACCESS,
380 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
384 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
390 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
392 yaffs_ExtendedTags * tags,
402 yaffs_InvalidateCheckpoint(dev);
405 chunk = yaffs_AllocateChunk(dev, useReserve,&bi);
408 /* First check this chunk is erased, if it needs checking.
409 * The checking policy (unless forced always on) is as follows:
410 * Check the first page we try to write in a block.
411 * - If the check passes then we don't need to check any more.
412 * - If the check fails, we check again...
413 * If the block has been erased, we don't need to check.
415 * However, if the block has been prioritised for gc, then
416 * we think there might be something odd about this block
420 * We should only ever see chunks that have not been erased
421 * if there was a partially written chunk due to power loss
422 * This checking policy should catch that case with very
423 * few checks and thus save a lot of checks that are most likely not
427 if(bi->gcPrioritise){
428 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
430 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
432 bi->skipErasedCheck = 0;
435 if(!bi->skipErasedCheck){
436 erasedOk = yaffs_CheckChunkErased(dev, chunk);
437 if(erasedOk && !bi->gcPrioritise)
438 bi->skipErasedCheck = 1;
444 ("**>> yaffs chunk %d was not erased"
448 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
456 * Copy the data into the robustification buffer.
457 * NB We do this at the end to prevent duplicates in the case of a write error.
460 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
463 /* The erased check or write failed */
464 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
469 } while (chunk >= 0 && !writeOk);
473 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
475 dev->nRetriedWrites += (attempts - 1);
482 * Block retiring for handling a broken block.
485 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
488 yaffs_InvalidateCheckpoint(dev);
490 yaffs_MarkBlockBad(dev, blockInNAND);
492 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
493 YAFFS_BLOCK_STATE_DEAD;
495 dev->nRetiredBlocks++;
499 * Functions for robustisizing TODO
503 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
505 const yaffs_ExtendedTags * tags)
509 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
510 const yaffs_ExtendedTags * tags)
514 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
517 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
518 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
520 bi->gcPrioritise = 1;
521 dev->hasPendingPrioritisedGCs = 1;
524 /* Was an actual write failure, so mark the block for retirement */
526 bi->needsRetiring = 1;
529 /* Delete the chunk */
530 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
534 /*---------------- Name handling functions ------------*/
536 static __u16 yaffs_CalcNameSum(const YCHAR * name)
541 YUCHAR *bname = (YUCHAR *) name;
543 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
545 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
546 sum += yaffs_toupper(*bname) * i;
557 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
559 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
560 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
561 yaffs_strcpy(obj->shortName, name);
563 obj->shortName[0] = _Y('\0');
566 obj->sum = yaffs_CalcNameSum(name);
569 /*-------------------- TNODES -------------------
571 * List of spare tnodes
572 * The list is hooked together using the first pointer
576 /* yaffs_CreateTnodes creates a bunch more tnodes and
577 * adds them to the tnode free list.
578 * Don't use this function directly
581 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
585 yaffs_Tnode *newTnodes;
589 yaffs_TnodeList *tnl;
594 /* Calculate the tnode size in bytes for variable width tnode support.
595 * Must be a multiple of 32-bits */
596 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
598 /* make these things */
600 newTnodes = YMALLOC(nTnodes * tnodeSize);
601 mem = (__u8 *)newTnodes;
605 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
609 /* Hook them into the free list */
611 for (i = 0; i < nTnodes - 1; i++) {
612 newTnodes[i].internal[0] = &newTnodes[i + 1];
613 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
614 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
618 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
619 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
620 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
622 dev->freeTnodes = newTnodes;
624 /* New hookup for wide tnodes */
625 for(i = 0; i < nTnodes -1; i++) {
626 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
627 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
628 curr->internal[0] = next;
631 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
632 curr->internal[0] = dev->freeTnodes;
633 dev->freeTnodes = (yaffs_Tnode *)mem;
638 dev->nFreeTnodes += nTnodes;
639 dev->nTnodesCreated += nTnodes;
641 /* Now add this bunch of tnodes to a list for freeing up.
642 * NB If we can't add this to the management list it isn't fatal
643 * but it just means we can't free this bunch of tnodes later.
646 tnl = YMALLOC(sizeof(yaffs_TnodeList));
650 ("yaffs: Could not add tnodes to management list" TENDSTR)));
653 tnl->tnodes = newTnodes;
654 tnl->next = dev->allocatedTnodeList;
655 dev->allocatedTnodeList = tnl;
658 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
663 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
665 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
667 yaffs_Tnode *tn = NULL;
669 /* If there are none left make more */
670 if (!dev->freeTnodes) {
671 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
674 if (dev->freeTnodes) {
675 tn = dev->freeTnodes;
676 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
677 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
678 /* Hoosterman, this thing looks like it isn't in the list */
679 T(YAFFS_TRACE_ALWAYS,
680 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
683 dev->freeTnodes = dev->freeTnodes->internal[0];
690 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
692 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
695 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
700 /* FreeTnode frees up a tnode and puts it back on the free list */
701 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
704 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
705 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
706 /* Hoosterman, this thing looks like it is already in the list */
707 T(YAFFS_TRACE_ALWAYS,
708 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
710 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
712 tn->internal[0] = dev->freeTnodes;
713 dev->freeTnodes = tn;
718 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
720 /* Free the list of allocated tnodes */
721 yaffs_TnodeList *tmp;
723 while (dev->allocatedTnodeList) {
724 tmp = dev->allocatedTnodeList->next;
726 YFREE(dev->allocatedTnodeList->tnodes);
727 YFREE(dev->allocatedTnodeList);
728 dev->allocatedTnodeList = tmp;
732 dev->freeTnodes = NULL;
733 dev->nFreeTnodes = 0;
736 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
738 dev->allocatedTnodeList = NULL;
739 dev->freeTnodes = NULL;
740 dev->nFreeTnodes = 0;
741 dev->nTnodesCreated = 0;
746 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
748 __u32 *map = (__u32 *)tn;
754 pos &= YAFFS_TNODES_LEVEL0_MASK;
755 val >>= dev->chunkGroupBits;
757 bitInMap = pos * dev->tnodeWidth;
758 wordInMap = bitInMap /32;
759 bitInWord = bitInMap & (32 -1);
761 mask = dev->tnodeMask << bitInWord;
763 map[wordInMap] &= ~mask;
764 map[wordInMap] |= (mask & (val << bitInWord));
766 if(dev->tnodeWidth > (32-bitInWord)) {
767 bitInWord = (32 - bitInWord);
769 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
770 map[wordInMap] &= ~mask;
771 map[wordInMap] |= (mask & (val >> bitInWord));
775 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
777 __u32 *map = (__u32 *)tn;
783 pos &= YAFFS_TNODES_LEVEL0_MASK;
785 bitInMap = pos * dev->tnodeWidth;
786 wordInMap = bitInMap /32;
787 bitInWord = bitInMap & (32 -1);
789 val = map[wordInMap] >> bitInWord;
791 if(dev->tnodeWidth > (32-bitInWord)) {
792 bitInWord = (32 - bitInWord);
794 val |= (map[wordInMap] << bitInWord);
797 val &= dev->tnodeMask;
798 val <<= dev->chunkGroupBits;
803 /* ------------------- End of individual tnode manipulation -----------------*/
805 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
806 * The look up tree is represented by the top tnode and the number of topLevel
807 * in the tree. 0 means only the level 0 tnode is in the tree.
810 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
811 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
812 yaffs_FileStructure * fStruct,
816 yaffs_Tnode *tn = fStruct->top;
818 int requiredTallness;
819 int level = fStruct->topLevel;
821 /* Check sane level and chunk Id */
822 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
826 if (chunkId > YAFFS_MAX_CHUNK_ID) {
830 /* First check we're tall enough (ie enough topLevel) */
832 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
833 requiredTallness = 0;
835 i >>= YAFFS_TNODES_INTERNAL_BITS;
839 if (requiredTallness > fStruct->topLevel) {
840 /* Not tall enough, so we can't find it, return NULL. */
844 /* Traverse down to level 0 */
845 while (level > 0 && tn) {
848 ( YAFFS_TNODES_LEVEL0_BITS +
850 YAFFS_TNODES_INTERNAL_BITS)
852 YAFFS_TNODES_INTERNAL_MASK];
860 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
861 * This happens in two steps:
862 * 1. If the tree isn't tall enough, then make it taller.
863 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
865 * Used when modifying the tree.
867 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
868 * be plugged into the ttree.
871 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
872 yaffs_FileStructure * fStruct,
874 yaffs_Tnode *passedTn)
877 int requiredTallness;
885 /* Check sane level and page Id */
886 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
890 if (chunkId > YAFFS_MAX_CHUNK_ID) {
894 /* First check we're tall enough (ie enough topLevel) */
896 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
897 requiredTallness = 0;
899 x >>= YAFFS_TNODES_INTERNAL_BITS;
904 if (requiredTallness > fStruct->topLevel) {
905 /* Not tall enough,gotta make the tree taller */
906 for (i = fStruct->topLevel; i < requiredTallness; i++) {
908 tn = yaffs_GetTnode(dev);
911 tn->internal[0] = fStruct->top;
915 (TSTR("yaffs: no more tnodes" TENDSTR)));
919 fStruct->topLevel = requiredTallness;
922 /* Traverse down to level 0, adding anything we need */
924 l = fStruct->topLevel;
928 while (l > 0 && tn) {
930 ( YAFFS_TNODES_LEVEL0_BITS +
931 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
932 YAFFS_TNODES_INTERNAL_MASK;
935 if((l>1) && !tn->internal[x]){
936 /* Add missing non-level-zero tnode */
937 tn->internal[x] = yaffs_GetTnode(dev);
940 /* Looking from level 1 at level 0 */
942 /* If we already have one, then release it.*/
944 yaffs_FreeTnode(dev,tn->internal[x]);
945 tn->internal[x] = passedTn;
947 } else if(!tn->internal[x]) {
948 /* Don't have one, none passed in */
949 tn->internal[x] = yaffs_GetTnode(dev);
953 tn = tn->internal[x];
959 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
960 yaffs_FreeTnode(dev,passedTn);
967 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
968 yaffs_ExtendedTags * tags, int objectId,
973 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
974 if (yaffs_CheckChunkBit
975 (dev, theChunk / dev->nChunksPerBlock,
976 theChunk % dev->nChunksPerBlock)) {
977 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
979 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
991 /* DeleteWorker scans backwards through the tnode tree and deletes all the
992 * chunks and tnodes in the file
993 * Returns 1 if the tree was deleted.
994 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
997 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
998 int chunkOffset, int *limit)
1003 yaffs_ExtendedTags tags;
1005 yaffs_Device *dev = in->myDev;
1012 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1014 if (tn->internal[i]) {
1015 if (limit && (*limit) < 0) {
1019 yaffs_DeleteWorker(in,
1027 YAFFS_TNODES_INTERNAL_BITS)
1032 yaffs_FreeTnode(dev,
1035 tn->internal[i] = NULL;
1040 return (allDone) ? 1 : 0;
1041 } else if (level == 0) {
1044 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1046 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1051 YAFFS_TNODES_LEVEL0_BITS) + i;
1054 yaffs_FindChunkInGroup(dev,
1060 if (foundChunk > 0) {
1061 yaffs_DeleteChunk(dev,
1066 *limit = *limit - 1;
1074 yaffs_PutLevel0Tnode(dev,tn,i,0);
1078 return (i < 0) ? 1 : 0;
1088 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1091 yaffs_BlockInfo *theBlock;
1093 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1095 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1097 theBlock->softDeletions++;
1102 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1103 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1105 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1108 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1109 __u32 level, int chunkOffset)
1114 yaffs_Device *dev = in->myDev;
1119 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1121 if (tn->internal[i]) {
1123 yaffs_SoftDeleteWorker(in,
1129 YAFFS_TNODES_INTERNAL_BITS)
1132 yaffs_FreeTnode(dev,
1135 tn->internal[i] = NULL;
1137 /* Hoosterman... how could this happen? */
1141 return (allDone) ? 1 : 0;
1142 } else if (level == 0) {
1144 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1145 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1147 /* Note this does not find the real chunk, only the chunk group.
1148 * We make an assumption that a chunk group is not larger than
1151 yaffs_SoftDeleteChunk(dev, theChunk);
1152 yaffs_PutLevel0Tnode(dev,tn,i,0);
1166 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1169 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1170 if (obj->nDataChunks <= 0) {
1171 /* Empty file with no duplicate object headers, just delete it immediately */
1172 yaffs_FreeTnode(obj->myDev,
1173 obj->variant.fileVariant.top);
1174 obj->variant.fileVariant.top = NULL;
1175 T(YAFFS_TRACE_TRACING,
1176 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1178 yaffs_DoGenericObjectDeletion(obj);
1180 yaffs_SoftDeleteWorker(obj,
1181 obj->variant.fileVariant.top,
1182 obj->variant.fileVariant.
1184 obj->softDeleted = 1;
1189 /* Pruning removes any part of the file structure tree that is beyond the
1190 * bounds of the file (ie that does not point to chunks).
1192 * A file should only get pruned when its size is reduced.
1194 * Before pruning, the chunks must be pulled from the tree and the
1195 * level 0 tnode entries must be zeroed out.
1196 * Could also use this for file deletion, but that's probably better handled
1197 * by a special case.
1200 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1201 __u32 level, int del0)
1209 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1210 if (tn->internal[i] && level > 0) {
1212 yaffs_PruneWorker(dev, tn->internal[i],
1214 (i == 0) ? del0 : 1);
1217 if (tn->internal[i]) {
1222 if (hasData == 0 && del0) {
1223 /* Free and return NULL */
1225 yaffs_FreeTnode(dev, tn);
1235 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1236 yaffs_FileStructure * fStruct)
1243 if (fStruct->topLevel > 0) {
1245 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1247 /* Now we have a tree with all the non-zero branches NULL but the height
1248 * is the same as it was.
1249 * Let's see if we can trim internal tnodes to shorten the tree.
1250 * We can do this if only the 0th element in the tnode is in use
1251 * (ie all the non-zero are NULL)
1254 while (fStruct->topLevel && !done) {
1258 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1259 if (tn->internal[i]) {
1265 fStruct->top = tn->internal[0];
1266 fStruct->topLevel--;
1267 yaffs_FreeTnode(dev, tn);
1277 /*-------------------- End of File Structure functions.-------------------*/
1279 /* yaffs_CreateFreeObjects creates a bunch more objects and
1280 * adds them to the object free list.
1282 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1285 yaffs_Object *newObjects;
1286 yaffs_ObjectList *list;
1291 /* make these things */
1292 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1295 T(YAFFS_TRACE_ALLOCATE,
1296 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1300 /* Hook them into the free list */
1301 for (i = 0; i < nObjects - 1; i++) {
1302 newObjects[i].siblings.next =
1303 (struct list_head *)(&newObjects[i + 1]);
1306 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1307 dev->freeObjects = newObjects;
1308 dev->nFreeObjects += nObjects;
1309 dev->nObjectsCreated += nObjects;
1311 /* Now add this bunch of Objects to a list for freeing up. */
1313 list = YMALLOC(sizeof(yaffs_ObjectList));
1315 T(YAFFS_TRACE_ALLOCATE,
1316 (TSTR("Could not add objects to management list" TENDSTR)));
1318 list->objects = newObjects;
1319 list->next = dev->allocatedObjectList;
1320 dev->allocatedObjectList = list;
1327 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1328 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1330 yaffs_Object *tn = NULL;
1332 /* If there are none left make more */
1333 if (!dev->freeObjects) {
1334 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1337 if (dev->freeObjects) {
1338 tn = dev->freeObjects;
1340 (yaffs_Object *) (dev->freeObjects->siblings.next);
1341 dev->nFreeObjects--;
1343 /* Now sweeten it up... */
1345 memset(tn, 0, sizeof(yaffs_Object));
1348 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1349 INIT_LIST_HEAD(&(tn->hardLinks));
1350 INIT_LIST_HEAD(&(tn->hashLink));
1351 INIT_LIST_HEAD(&tn->siblings);
1353 /* Add it to the lost and found directory.
1354 * NB Can't put root or lostNFound in lostNFound so
1355 * check if lostNFound exists first
1357 if (dev->lostNFoundDir) {
1358 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1365 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1370 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1372 obj->fake = 1; /* it is fake so it has no NAND presence... */
1373 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1374 obj->unlinkAllowed = 0; /* ... or unlink it */
1377 obj->yst_mode = mode;
1379 obj->chunkId = 0; /* Not a valid chunk. */
1386 static void yaffs_UnhashObject(yaffs_Object * tn)
1389 yaffs_Device *dev = tn->myDev;
1391 /* If it is still linked into the bucket list, free from the list */
1392 if (!list_empty(&tn->hashLink)) {
1393 list_del_init(&tn->hashLink);
1394 bucket = yaffs_HashFunction(tn->objectId);
1395 dev->objectBucket[bucket].count--;
1400 /* FreeObject frees up a Object and puts it back on the free list */
1401 static void yaffs_FreeObject(yaffs_Object * tn)
1404 yaffs_Device *dev = tn->myDev;
1408 /* We're still hooked up to a cached inode.
1409 * Don't delete now, but mark for later deletion
1411 tn->deferedFree = 1;
1416 yaffs_UnhashObject(tn);
1418 /* Link into the free list. */
1419 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1420 dev->freeObjects = tn;
1421 dev->nFreeObjects++;
1426 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1428 if (obj->deferedFree) {
1429 yaffs_FreeObject(obj);
1435 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1437 /* Free the list of allocated Objects */
1439 yaffs_ObjectList *tmp;
1441 while (dev->allocatedObjectList) {
1442 tmp = dev->allocatedObjectList->next;
1443 YFREE(dev->allocatedObjectList->objects);
1444 YFREE(dev->allocatedObjectList);
1446 dev->allocatedObjectList = tmp;
1449 dev->freeObjects = NULL;
1450 dev->nFreeObjects = 0;
1453 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1457 dev->allocatedObjectList = NULL;
1458 dev->freeObjects = NULL;
1459 dev->nFreeObjects = 0;
1461 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1462 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1463 dev->objectBucket[i].count = 0;
1468 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1473 int lowest = 999999;
1475 /* First let's see if we can find one that's empty. */
1477 for (i = 0; i < 10 && lowest > 0; i++) {
1479 x %= YAFFS_NOBJECT_BUCKETS;
1480 if (dev->objectBucket[x].count < lowest) {
1481 lowest = dev->objectBucket[x].count;
1487 /* If we didn't find an empty list, then try
1488 * looking a bit further for a short one
1491 for (i = 0; i < 10 && lowest > 3; i++) {
1493 x %= YAFFS_NOBJECT_BUCKETS;
1494 if (dev->objectBucket[x].count < lowest) {
1495 lowest = dev->objectBucket[x].count;
1504 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1506 int bucket = yaffs_FindNiceObjectBucket(dev);
1508 /* Now find an object value that has not already been taken
1509 * by scanning the list.
1513 struct list_head *i;
1515 __u32 n = (__u32) bucket;
1517 /* yaffs_CheckObjectHashSanity(); */
1521 n += YAFFS_NOBJECT_BUCKETS;
1522 if (1 || dev->objectBucket[bucket].count > 0) {
1523 list_for_each(i, &dev->objectBucket[bucket].list) {
1524 /* If there is already one in the list */
1526 && list_entry(i, yaffs_Object,
1527 hashLink)->objectId == n) {
1538 static void yaffs_HashObject(yaffs_Object * in)
1540 int bucket = yaffs_HashFunction(in->objectId);
1541 yaffs_Device *dev = in->myDev;
1543 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1544 dev->objectBucket[bucket].count++;
1548 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1550 int bucket = yaffs_HashFunction(number);
1551 struct list_head *i;
1554 list_for_each(i, &dev->objectBucket[bucket].list) {
1555 /* Look if it is in the list */
1557 in = list_entry(i, yaffs_Object, hashLink);
1558 if (in->objectId == number) {
1560 /* Don't tell the VFS about this one if it is defered free */
1561 if (in->deferedFree)
1573 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1574 yaffs_ObjectType type)
1577 yaffs_Object *theObject;
1580 number = yaffs_CreateNewObjectNumber(dev);
1583 theObject = yaffs_AllocateEmptyObject(dev);
1586 theObject->fake = 0;
1587 theObject->renameAllowed = 1;
1588 theObject->unlinkAllowed = 1;
1589 theObject->objectId = number;
1590 yaffs_HashObject(theObject);
1591 theObject->variantType = type;
1592 #ifdef CONFIG_YAFFS_WINCE
1593 yfsd_WinFileTimeNow(theObject->win_atime);
1594 theObject->win_ctime[0] = theObject->win_mtime[0] =
1595 theObject->win_atime[0];
1596 theObject->win_ctime[1] = theObject->win_mtime[1] =
1597 theObject->win_atime[1];
1601 theObject->yst_atime = theObject->yst_mtime =
1602 theObject->yst_ctime = Y_CURRENT_TIME;
1605 case YAFFS_OBJECT_TYPE_FILE:
1606 theObject->variant.fileVariant.fileSize = 0;
1607 theObject->variant.fileVariant.scannedFileSize = 0;
1608 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1609 theObject->variant.fileVariant.topLevel = 0;
1610 theObject->variant.fileVariant.top =
1611 yaffs_GetTnode(dev);
1613 case YAFFS_OBJECT_TYPE_DIRECTORY:
1614 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1617 case YAFFS_OBJECT_TYPE_SYMLINK:
1618 case YAFFS_OBJECT_TYPE_HARDLINK:
1619 case YAFFS_OBJECT_TYPE_SPECIAL:
1620 /* No action required */
1622 case YAFFS_OBJECT_TYPE_UNKNOWN:
1623 /* todo this should not happen */
1631 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1633 yaffs_ObjectType type)
1635 yaffs_Object *theObject = NULL;
1638 theObject = yaffs_FindObjectByNumber(dev, number);
1642 theObject = yaffs_CreateNewObject(dev, number, type);
1650 static YCHAR *yaffs_CloneString(const YCHAR * str)
1652 YCHAR *newStr = NULL;
1655 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1656 yaffs_strcpy(newStr, str);
1664 * Mknod (create) a new object.
1665 * equivalentObject only has meaning for a hard link;
1666 * aliasString only has meaning for a sumlink.
1667 * rdev only has meaning for devices (a subset of special objects)
1670 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1671 yaffs_Object * parent,
1676 yaffs_Object * equivalentObject,
1677 const YCHAR * aliasString, __u32 rdev)
1681 yaffs_Device *dev = parent->myDev;
1683 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1684 if (yaffs_FindObjectByName(parent, name)) {
1688 in = yaffs_CreateNewObject(dev, -1, type);
1693 in->variantType = type;
1695 in->yst_mode = mode;
1697 #ifdef CONFIG_YAFFS_WINCE
1698 yfsd_WinFileTimeNow(in->win_atime);
1699 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1700 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1703 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1705 in->yst_rdev = rdev;
1709 in->nDataChunks = 0;
1711 yaffs_SetObjectName(in, name);
1714 yaffs_AddObjectToDirectory(parent, in);
1716 in->myDev = parent->myDev;
1719 case YAFFS_OBJECT_TYPE_SYMLINK:
1720 in->variant.symLinkVariant.alias =
1721 yaffs_CloneString(aliasString);
1723 case YAFFS_OBJECT_TYPE_HARDLINK:
1724 in->variant.hardLinkVariant.equivalentObject =
1726 in->variant.hardLinkVariant.equivalentObjectId =
1727 equivalentObject->objectId;
1728 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1730 case YAFFS_OBJECT_TYPE_FILE:
1731 case YAFFS_OBJECT_TYPE_DIRECTORY:
1732 case YAFFS_OBJECT_TYPE_SPECIAL:
1733 case YAFFS_OBJECT_TYPE_UNKNOWN:
1738 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1739 /* Could not create the object header, fail the creation */
1740 yaffs_DestroyObject(in);
1749 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1750 __u32 mode, __u32 uid, __u32 gid)
1752 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1753 uid, gid, NULL, NULL, 0);
1756 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1757 __u32 mode, __u32 uid, __u32 gid)
1759 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1760 mode, uid, gid, NULL, NULL, 0);
1763 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1764 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1766 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1767 uid, gid, NULL, NULL, rdev);
1770 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1771 __u32 mode, __u32 uid, __u32 gid,
1772 const YCHAR * alias)
1774 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1775 uid, gid, NULL, alias, 0);
1778 /* yaffs_Link returns the object id of the equivalent object.*/
1779 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1780 yaffs_Object * equivalentObject)
1782 /* Get the real object in case we were fed a hard link as an equivalent object */
1783 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1785 if (yaffs_MknodObject
1786 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1787 equivalentObject, NULL, 0)) {
1788 return equivalentObject;
1795 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1796 const YCHAR * newName, int force, int shadows)
1801 yaffs_Object *existingTarget;
1803 if (newDir == NULL) {
1804 newDir = obj->parent; /* use the old directory */
1807 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1808 T(YAFFS_TRACE_ALWAYS,
1810 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1815 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1816 if (obj->myDev->isYaffs2) {
1817 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1819 unlinkOp = (newDir == obj->myDev->unlinkedDir
1820 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1823 deleteOp = (newDir == obj->myDev->deletedDir);
1825 existingTarget = yaffs_FindObjectByName(newDir, newName);
1827 /* If the object is a file going into the unlinked directory,
1828 * then it is OK to just stuff it in since duplicate names are allowed.
1829 * else only proceed if the new name does not exist and if we're putting
1830 * it into a directory.
1837 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1838 yaffs_SetObjectName(obj, newName);
1841 yaffs_AddObjectToDirectory(newDir, obj);
1846 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1847 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1854 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1855 yaffs_Object * newDir, const YCHAR * newName)
1858 yaffs_Object *existingTarget;
1861 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1862 /* Special case for case insemsitive systems (eg. WinCE).
1863 * While look-up is case insensitive, the name isn't.
1864 * Therefore we might want to change x.txt to X.txt
1866 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1871 obj = yaffs_FindObjectByName(oldDir, oldName);
1872 /* Check new name to long. */
1873 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1874 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1877 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1878 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1882 if (obj && obj->renameAllowed) {
1884 /* Now do the handling for an existing target, if there is one */
1886 existingTarget = yaffs_FindObjectByName(newDir, newName);
1887 if (existingTarget &&
1888 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1889 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1890 /* There is a target that is a non-empty directory, so we fail */
1891 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1892 } else if (existingTarget && existingTarget != obj) {
1893 /* Nuke the target first, using shadowing,
1894 * but only if it isn't the same object
1896 yaffs_ChangeObjectName(obj, newDir, newName, force,
1897 existingTarget->objectId);
1898 yaffs_UnlinkObject(existingTarget);
1901 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1906 /*------------------------- Block Management and Page Allocation ----------------*/
1908 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1910 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1912 dev->allocationBlock = -1; /* force it to get a new one */
1914 /* Todo we're assuming the malloc will pass. */
1915 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1916 if(!dev->blockInfo){
1917 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1918 dev->blockInfoAlt = 1;
1921 dev->blockInfoAlt = 0;
1923 /* Set up dynamic blockinfo stuff. */
1924 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; // round up bytes
1925 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1926 if(!dev->chunkBits){
1927 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1928 dev->chunkBitsAlt = 1;
1931 dev->chunkBitsAlt = 0;
1933 if (dev->blockInfo && dev->chunkBits) {
1934 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1935 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1943 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1945 if(dev->blockInfoAlt)
1946 YFREE_ALT(dev->blockInfo);
1948 YFREE(dev->blockInfo);
1949 dev->blockInfoAlt = 0;
1951 dev->blockInfo = NULL;
1953 if(dev->chunkBitsAlt)
1954 YFREE_ALT(dev->chunkBits);
1956 YFREE(dev->chunkBits);
1957 dev->chunkBitsAlt = 0;
1958 dev->chunkBits = NULL;
1961 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1962 yaffs_BlockInfo * bi)
1969 return 1; /* disqualification only applies to yaffs2. */
1971 if (!bi->hasShrinkHeader)
1972 return 1; /* can gc */
1974 /* Find the oldest dirty sequence number if we don't know it and save it
1975 * so we don't have to keep recomputing it.
1977 if (!dev->oldestDirtySequence) {
1978 seq = dev->sequenceNumber;
1980 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1982 b = yaffs_GetBlockInfo(dev, i);
1983 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1984 (b->pagesInUse - b->softDeletions) <
1985 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1986 seq = b->sequenceNumber;
1989 dev->oldestDirtySequence = seq;
1992 /* Can't do gc of this block if there are any blocks older than this one that have
1995 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2001 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2002 * for garbage collection.
2005 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2009 int b = dev->currentDirtyChecker;
2016 yaffs_BlockInfo *bi;
2017 static int nonAggressiveSkip = 0;
2019 /* First let's see if we need to grab a prioritised block */
2020 if(dev->hasPendingPrioritisedGCs){
2021 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2023 bi = yaffs_GetBlockInfo(dev, i);
2024 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2026 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2027 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2030 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2033 if(dirtiest < 0) /* None found, so we can clear this */
2034 dev->hasPendingPrioritisedGCs = 0;
2037 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2039 * else (we're doing a leasurely gc), then we only bother to do this if the
2040 * block has only a few pages in use.
2043 nonAggressiveSkip--;
2045 if (!aggressive && (nonAggressiveSkip > 0)) {
2051 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2055 dev->internalEndBlock - dev->internalStartBlock + 1;
2058 dev->internalEndBlock - dev->internalStartBlock + 1;
2059 iterations = iterations / 16;
2060 if (iterations > 200) {
2065 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2067 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2068 b = dev->internalStartBlock;
2071 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2072 T(YAFFS_TRACE_ERROR,
2073 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2077 bi = yaffs_GetBlockInfo(dev, b);
2080 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2087 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2088 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2089 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2091 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2095 dev->currentDirtyChecker = b;
2099 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2100 dev->nChunksPerBlock - pagesInUse,prioritised));
2103 dev->oldestDirtySequence = 0;
2106 nonAggressiveSkip = 4;
2112 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2114 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2118 /* If the block is still healthy erase it and mark as clean.
2119 * If the block has had a data failure, then retire it.
2121 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2123 if (!bi->needsRetiring) {
2124 yaffs_InvalidateCheckpoint(dev);
2125 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2127 dev->nErasureFailures++;
2128 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2129 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2133 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2135 for (i = 0; i < dev->nChunksPerBlock; i++) {
2136 if (!yaffs_CheckChunkErased
2137 (dev, blockNo * dev->nChunksPerBlock + i)) {
2138 T(YAFFS_TRACE_ERROR,
2140 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2141 TENDSTR), blockNo, i));
2147 /* Clean it up... */
2148 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2149 dev->nErasedBlocks++;
2151 bi->softDeletions = 0;
2152 bi->hasShrinkHeader = 0;
2153 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2154 bi->gcPrioritise = 0;
2155 yaffs_ClearChunkBits(dev, blockNo);
2157 T(YAFFS_TRACE_ERASE,
2158 (TSTR("Erased block %d" TENDSTR), blockNo));
2160 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2162 yaffs_RetireBlock(dev, blockNo);
2163 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2164 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2168 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2172 yaffs_BlockInfo *bi;
2174 if (dev->nErasedBlocks < 1) {
2175 /* Hoosterman we've got a problem.
2176 * Can't get space to gc
2178 T(YAFFS_TRACE_ERROR,
2179 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2184 /* Find an empty block. */
2186 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2187 dev->allocationBlockFinder++;
2188 if (dev->allocationBlockFinder < dev->internalStartBlock
2189 || dev->allocationBlockFinder > dev->internalEndBlock) {
2190 dev->allocationBlockFinder = dev->internalStartBlock;
2193 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2195 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2196 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2197 dev->sequenceNumber++;
2198 bi->sequenceNumber = dev->sequenceNumber;
2199 dev->nErasedBlocks--;
2200 T(YAFFS_TRACE_ALLOCATE,
2201 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2202 dev->allocationBlockFinder, dev->sequenceNumber,
2203 dev->nErasedBlocks));
2204 return dev->allocationBlockFinder;
2208 T(YAFFS_TRACE_ALWAYS,
2210 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2211 TENDSTR), dev->nErasedBlocks));
2217 // Check if there's space to allocate...
2218 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2219 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2222 int reservedBlocks = dev->nReservedBlocks;
2223 int checkpointBlocks;
2225 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2226 if(checkpointBlocks < 0)
2227 checkpointBlocks = 0;
2229 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2231 return (dev->nFreeChunks > reservedChunks);
2234 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2237 yaffs_BlockInfo *bi;
2239 if (dev->allocationBlock < 0) {
2240 /* Get next block to allocate off */
2241 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2242 dev->allocationPage = 0;
2245 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2246 /* Not enough space to allocate unless we're allowed to use the reserve. */
2250 if (dev->nErasedBlocks < dev->nReservedBlocks
2251 && dev->allocationPage == 0) {
2252 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2255 /* Next page please.... */
2256 if (dev->allocationBlock >= 0) {
2257 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2259 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2260 dev->allocationPage;
2262 yaffs_SetChunkBit(dev, dev->allocationBlock,
2263 dev->allocationPage);
2265 dev->allocationPage++;
2269 /* If the block is full set the state to full */
2270 if (dev->allocationPage >= dev->nChunksPerBlock) {
2271 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2272 dev->allocationBlock = -1;
2281 T(YAFFS_TRACE_ERROR,
2282 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2287 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2291 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2293 if (dev->allocationBlock > 0) {
2294 n += (dev->nChunksPerBlock - dev->allocationPage);
2301 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2307 int retVal = YAFFS_OK;
2310 int isCheckpointBlock;
2312 int chunksBefore = yaffs_GetErasedChunks(dev);
2315 yaffs_ExtendedTags tags;
2317 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2319 yaffs_Object *object;
2321 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2323 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2325 T(YAFFS_TRACE_TRACING,
2326 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2327 bi->pagesInUse, bi->hasShrinkHeader));
2329 /*yaffs_VerifyFreeChunks(dev); */
2331 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2333 /* Take off the number of soft deleted entries because
2334 * they're going to get really deleted during GC.
2336 dev->nFreeChunks -= bi->softDeletions;
2340 if (isCheckpointBlock ||
2341 !yaffs_StillSomeChunkBits(dev, block)) {
2342 T(YAFFS_TRACE_TRACING,
2344 ("Collecting block %d that has no chunks in use" TENDSTR),
2346 yaffs_BlockBecameDirty(dev, block);
2349 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2351 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2352 chunkInBlock < dev->nChunksPerBlock
2353 && yaffs_StillSomeChunkBits(dev, block);
2354 chunkInBlock++, oldChunk++) {
2355 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2357 /* This page is in use and might need to be copied off */
2361 yaffs_InitialiseTags(&tags);
2363 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2367 yaffs_FindObjectByNumber(dev,
2370 T(YAFFS_TRACE_GC_DETAIL,
2372 ("Collecting page %d, %d %d %d " TENDSTR),
2373 chunkInBlock, tags.objectId, tags.chunkId,
2377 T(YAFFS_TRACE_ERROR,
2379 ("page %d in gc has no object "
2380 TENDSTR), oldChunk));
2383 if (object && object->deleted
2384 && tags.chunkId != 0) {
2385 /* Data chunk in a deleted file, throw it away
2386 * It's a soft deleted data chunk,
2387 * No need to copy this, just forget about it and
2388 * fix up the object.
2391 object->nDataChunks--;
2393 if (object->nDataChunks <= 0) {
2394 /* remeber to clean up the object */
2395 dev->gcCleanupList[cleanups] =
2401 /* Todo object && object->deleted && object->nDataChunks == 0 */
2403 /* Deleted object header with no data chunks.
2404 * Can be discarded and the file deleted.
2406 object->chunkId = 0;
2407 yaffs_FreeTnode(object->myDev,
2410 object->variant.fileVariant.top = NULL;
2411 yaffs_DoGenericObjectDeletion(object);
2413 } else if (object) {
2414 /* It's either a data chunk in a live file or
2415 * an ObjectHeader, so we're interested in it.
2416 * NB Need to keep the ObjectHeaders of deleted files
2417 * until the whole file has been deleted off
2419 tags.serialNumber++;
2423 if (tags.chunkId == 0) {
2424 /* It is an object Id,
2425 * We need to nuke the shrinkheader flags first
2426 * We no longer want the shrinkHeader flag since its work is done
2427 * and if it is left in place it will mess up scanning.
2428 * Also, clear out any shadowing stuff
2431 yaffs_ObjectHeader *oh;
2432 oh = (yaffs_ObjectHeader *)buffer;
2434 oh->shadowsObject = -1;
2435 tags.extraShadows = 0;
2436 tags.extraIsShrinkHeader = 0;
2440 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2443 retVal = YAFFS_FAIL;
2446 /* Ok, now fix up the Tnodes etc. */
2448 if (tags.chunkId == 0) {
2450 object->chunkId = newChunk;
2451 object->serial = tags.serialNumber;
2453 /* It's a data chunk */
2454 yaffs_PutChunkIntoFile
2462 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2467 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2470 /* Do any required cleanups */
2471 for (i = 0; i < cleanups; i++) {
2472 /* Time to delete the file too */
2474 yaffs_FindObjectByNumber(dev,
2475 dev->gcCleanupList[i]);
2477 yaffs_FreeTnode(dev,
2478 object->variant.fileVariant.
2480 object->variant.fileVariant.top = NULL;
2483 ("yaffs: About to finally delete object %d"
2484 TENDSTR), object->objectId));
2485 yaffs_DoGenericObjectDeletion(object);
2486 object->myDev->nDeletedFiles--;
2493 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2496 ("gc did not increase free chunks before %d after %d"
2497 TENDSTR), chunksBefore, chunksAfter));
2505 /* New garbage collector
2506 * If we're very low on erased blocks then we do aggressive garbage collection
2507 * otherwise we do "leasurely" garbage collection.
2508 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2509 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2511 * The idea is to help clear out space in a more spread-out manner.
2512 * Dunno if it really does anything useful.
2514 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2518 int gcOk = YAFFS_OK;
2521 int checkpointBlockAdjust;
2523 if (dev->isDoingGC) {
2524 /* Bail out so we don't get recursive gc */
2528 /* This loop should pass the first time.
2529 * We'll only see looping here if the erase of the collected block fails.
2535 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2536 if(checkpointBlockAdjust < 0)
2537 checkpointBlockAdjust = 0;
2539 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2540 /* We need a block soon...*/
2543 /* We're in no hurry */
2547 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2550 dev->garbageCollections++;
2552 dev->passiveGarbageCollections++;
2557 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2558 dev->nErasedBlocks, aggressive));
2560 gcOk = yaffs_GarbageCollectBlock(dev, block);
2563 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2566 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2567 TENDSTR), dev->nErasedBlocks, maxTries, block));
2569 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2572 return aggressive ? gcOk : YAFFS_OK;
2575 /*------------------------- TAGS --------------------------------*/
2577 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2580 return (tags->chunkId == chunkInObject &&
2581 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2586 /*-------------------- Data file manipulation -----------------*/
2588 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2589 yaffs_ExtendedTags * tags)
2591 /*Get the Tnode, then get the level 0 offset chunk offset */
2594 yaffs_ExtendedTags localTags;
2597 yaffs_Device *dev = in->myDev;
2600 /* Passed a NULL, so use our own tags space */
2604 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2607 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2610 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2616 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2617 yaffs_ExtendedTags * tags)
2619 /* Get the Tnode, then get the level 0 offset chunk offset */
2622 yaffs_ExtendedTags localTags;
2624 yaffs_Device *dev = in->myDev;
2628 /* Passed a NULL, so use our own tags space */
2632 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2636 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2639 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2642 /* Delete the entry in the filestructure (if found) */
2644 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2647 /*T(("No level 0 found for %d\n", chunkInInode)); */
2651 /* T(("Could not find %d to delete\n",chunkInInode)); */
2656 #ifdef YAFFS_PARANOID
2658 static int yaffs_CheckFileSanity(yaffs_Object * in)
2666 yaffs_Tags localTags;
2667 yaffs_Tags *tags = &localTags;
2671 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2672 /* T(("Object not a file\n")); */
2676 objId = in->objectId;
2677 fSize = in->variant.fileVariant.fileSize;
2679 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
2681 for (chunk = 1; chunk <= nChunks; chunk++) {
2682 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2687 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2689 if (yaffs_CheckChunkBits
2690 (dev, theChunk / dev->nChunksPerBlock,
2691 theChunk % dev->nChunksPerBlock)) {
2693 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2697 (tags, in->objectId, chunk, chunkDeleted)) {
2707 /* T(("No level 0 found for %d\n", chunk)); */
2711 return failed ? YAFFS_FAIL : YAFFS_OK;
2716 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2717 int chunkInNAND, int inScan)
2719 /* NB inScan is zero unless scanning.
2720 * For forward scanning, inScan is > 0;
2721 * for backward scanning inScan is < 0
2725 yaffs_Device *dev = in->myDev;
2727 yaffs_ExtendedTags existingTags;
2728 yaffs_ExtendedTags newTags;
2729 unsigned existingSerial, newSerial;
2731 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2732 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2733 * If it is not during Scanning then something went wrong!
2736 T(YAFFS_TRACE_ERROR,
2738 ("yaffs tragedy:attempt to put data chunk into a non-file"
2743 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2747 tn = yaffs_AddOrFindLevel0Tnode(dev,
2748 &in->variant.fileVariant,
2755 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2758 /* If we're scanning then we need to test for duplicates
2759 * NB This does not need to be efficient since it should only ever
2760 * happen when the power fails during a write, then only one
2761 * chunk should ever be affected.
2763 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2764 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2767 if (existingChunk != 0) {
2768 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2769 * thus we have to do a FindChunkInFile to get the real chunk id.
2771 * We have a duplicate now we need to decide which one to use:
2773 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2774 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2775 * YAFFS1: Get both sets of tags and compare serial numbers.
2779 /* Only do this for forward scanning */
2780 yaffs_ReadChunkWithTagsFromNAND(dev,
2784 /* Do a proper find */
2786 yaffs_FindChunkInFile(in, chunkInInode,
2790 if (existingChunk <= 0) {
2791 /*Hoosterman - how did this happen? */
2793 T(YAFFS_TRACE_ERROR,
2795 ("yaffs tragedy: existing chunk < 0 in scan"
2800 /* NB The deleted flags should be false, otherwise the chunks will
2801 * not be loaded during a scan
2804 newSerial = newTags.serialNumber;
2805 existingSerial = existingTags.serialNumber;
2808 (in->myDev->isYaffs2 ||
2809 existingChunk <= 0 ||
2810 ((existingSerial + 1) & 3) == newSerial)) {
2811 /* Forward scanning.
2813 * Delete the old one and drop through to update the tnode
2815 yaffs_DeleteChunk(dev, existingChunk, 1,
2818 /* Backward scanning or we want to use the existing one
2820 * Delete the new one and return early so that the tnode isn't changed
2822 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2830 if (existingChunk == 0) {
2834 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2839 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2842 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2844 if (chunkInNAND >= 0) {
2845 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2848 T(YAFFS_TRACE_NANDACCESS,
2849 (TSTR("Chunk %d not found zero instead" TENDSTR),
2851 /* get sane (zero) data if you read a hole */
2852 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2858 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2862 yaffs_ExtendedTags tags;
2863 yaffs_BlockInfo *bi;
2869 block = chunkId / dev->nChunksPerBlock;
2870 page = chunkId % dev->nChunksPerBlock;
2872 bi = yaffs_GetBlockInfo(dev, block);
2874 T(YAFFS_TRACE_DELETION,
2875 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2878 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2880 yaffs_InitialiseTags(&tags);
2882 tags.chunkDeleted = 1;
2884 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2885 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2887 dev->nUnmarkedDeletions++;
2890 /* Pull out of the management area.
2891 * If the whole block became dirty, this will kick off an erasure.
2893 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2894 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2895 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2896 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2899 yaffs_ClearChunkBit(dev, block, page);
2903 if (bi->pagesInUse == 0 &&
2904 !bi->hasShrinkHeader &&
2905 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2906 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2907 yaffs_BlockBecameDirty(dev, block);
2911 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2916 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2917 const __u8 * buffer, int nBytes,
2920 /* Find old chunk Need to do this to get serial number
2921 * Write new one and patch into tree.
2922 * Invalidate old tags.
2926 yaffs_ExtendedTags prevTags;
2929 yaffs_ExtendedTags newTags;
2931 yaffs_Device *dev = in->myDev;
2933 yaffs_CheckGarbageCollection(dev);
2935 /* Get the previous chunk at this location in the file if it exists */
2936 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2938 /* Set up new tags */
2939 yaffs_InitialiseTags(&newTags);
2941 newTags.chunkId = chunkInInode;
2942 newTags.objectId = in->objectId;
2943 newTags.serialNumber =
2944 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2945 newTags.byteCount = nBytes;
2948 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2951 if (newChunkId >= 0) {
2952 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2954 if (prevChunkId >= 0) {
2955 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2959 yaffs_CheckFileSanity(in);
2965 /* UpdateObjectHeader updates the header on NAND for an object.
2966 * If name is not NULL, then that new name is used.
2968 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2969 int isShrink, int shadows)
2972 yaffs_BlockInfo *bi;
2974 yaffs_Device *dev = in->myDev;
2981 yaffs_ExtendedTags newTags;
2983 __u8 *buffer = NULL;
2984 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2986 yaffs_ObjectHeader *oh = NULL;
2988 if (!in->fake || force) {
2990 yaffs_CheckGarbageCollection(dev);
2992 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2993 oh = (yaffs_ObjectHeader *) buffer;
2995 prevChunkId = in->chunkId;
2997 if (prevChunkId >= 0) {
2998 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3000 memcpy(oldName, oh->name, sizeof(oh->name));
3003 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3005 oh->type = in->variantType;
3006 oh->yst_mode = in->yst_mode;
3007 oh->shadowsObject = shadows;
3009 #ifdef CONFIG_YAFFS_WINCE
3010 oh->win_atime[0] = in->win_atime[0];
3011 oh->win_ctime[0] = in->win_ctime[0];
3012 oh->win_mtime[0] = in->win_mtime[0];
3013 oh->win_atime[1] = in->win_atime[1];
3014 oh->win_ctime[1] = in->win_ctime[1];
3015 oh->win_mtime[1] = in->win_mtime[1];
3017 oh->yst_uid = in->yst_uid;
3018 oh->yst_gid = in->yst_gid;
3019 oh->yst_atime = in->yst_atime;
3020 oh->yst_mtime = in->yst_mtime;
3021 oh->yst_ctime = in->yst_ctime;
3022 oh->yst_rdev = in->yst_rdev;
3025 oh->parentObjectId = in->parent->objectId;
3027 oh->parentObjectId = 0;
3030 if (name && *name) {
3031 memset(oh->name, 0, sizeof(oh->name));
3032 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3033 } else if (prevChunkId) {
3034 memcpy(oh->name, oldName, sizeof(oh->name));
3036 memset(oh->name, 0, sizeof(oh->name));
3039 oh->isShrink = isShrink;
3041 switch (in->variantType) {
3042 case YAFFS_OBJECT_TYPE_UNKNOWN:
3043 /* Should not happen */
3045 case YAFFS_OBJECT_TYPE_FILE:
3047 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3048 || oh->parentObjectId ==
3049 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3050 fileVariant.fileSize;
3052 case YAFFS_OBJECT_TYPE_HARDLINK:
3053 oh->equivalentObjectId =
3054 in->variant.hardLinkVariant.equivalentObjectId;
3056 case YAFFS_OBJECT_TYPE_SPECIAL:
3059 case YAFFS_OBJECT_TYPE_DIRECTORY:
3062 case YAFFS_OBJECT_TYPE_SYMLINK:
3063 yaffs_strncpy(oh->alias,
3064 in->variant.symLinkVariant.alias,
3065 YAFFS_MAX_ALIAS_LENGTH);
3066 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3071 yaffs_InitialiseTags(&newTags);
3073 newTags.chunkId = 0;
3074 newTags.objectId = in->objectId;
3075 newTags.serialNumber = in->serial;
3077 /* Add extra info for file header */
3079 newTags.extraHeaderInfoAvailable = 1;
3080 newTags.extraParentObjectId = oh->parentObjectId;
3081 newTags.extraFileLength = oh->fileSize;
3082 newTags.extraIsShrinkHeader = oh->isShrink;
3083 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3084 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3085 newTags.extraObjectType = in->variantType;
3087 /* Create new chunk in NAND */
3089 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3090 (prevChunkId >= 0) ? 1 : 0);
3092 if (newChunkId >= 0) {
3094 in->chunkId = newChunkId;
3096 if (prevChunkId >= 0) {
3097 yaffs_DeleteChunk(dev, prevChunkId, 1,
3101 if(!yaffs_ObjectHasCachedWriteData(in))
3104 /* If this was a shrink, then mark the block that the chunk lives on */
3106 bi = yaffs_GetBlockInfo(in->myDev,
3107 newChunkId /in->myDev-> nChunksPerBlock);
3108 bi->hasShrinkHeader = 1;
3113 retVal = newChunkId;
3118 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3123 /*------------------------ Short Operations Cache ----------------------------------------
3124 * In many situations where there is no high level buffering (eg WinCE) a lot of
3125 * reads might be short sequential reads, and a lot of writes may be short
3126 * sequential writes. eg. scanning/writing a jpeg file.
3127 * In these cases, a short read/write cache can provide a huge perfomance benefit
3128 * with dumb-as-a-rock code.
3129 * In Linux, the page cache provides read buffering aand the short op cache provides write
3132 * There are a limited number (~10) of cache chunks per device so that we don't
3133 * need a very intelligent search.
3136 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3138 yaffs_Device *dev = obj->myDev;
3140 yaffs_ChunkCache *cache;
3141 int nCaches = obj->myDev->nShortOpCaches;
3143 for(i = 0; i < nCaches; i++){
3144 cache = &dev->srCache[i];
3145 if (cache->object == obj &&
3154 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3156 yaffs_Device *dev = obj->myDev;
3157 int lowest = -99; /* Stop compiler whining. */
3159 yaffs_ChunkCache *cache;
3160 int chunkWritten = 0;
3161 int nCaches = obj->myDev->nShortOpCaches;
3167 /* Find the dirty cache for this object with the lowest chunk id. */
3168 for (i = 0; i < nCaches; i++) {
3169 if (dev->srCache[i].object == obj &&
3170 dev->srCache[i].dirty) {
3172 || dev->srCache[i].chunkId <
3174 cache = &dev->srCache[i];
3175 lowest = cache->chunkId;
3180 if (cache && !cache->locked) {
3181 /* Write it out and free it up */
3184 yaffs_WriteChunkDataToObject(cache->object,
3190 cache->object = NULL;
3193 } while (cache && chunkWritten > 0);
3196 /* Hoosterman, disk full while writing cache out. */
3197 T(YAFFS_TRACE_ERROR,
3198 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3205 /*yaffs_FlushEntireDeviceCache(dev)
3210 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3213 int nCaches = dev->nShortOpCaches;
3216 /* Find a dirty object in the cache and flush it...
3217 * until there are no further dirty objects.
3221 for( i = 0; i < nCaches && !obj; i++) {
3222 if (dev->srCache[i].object &&
3223 dev->srCache[i].dirty)
3224 obj = dev->srCache[i].object;
3228 yaffs_FlushFilesChunkCache(obj);
3235 /* Grab us a cache chunk for use.
3236 * First look for an empty one.
3237 * Then look for the least recently used non-dirty one.
3238 * Then look for the least recently used dirty one...., flush and look again.
3240 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3246 if (dev->nShortOpCaches > 0) {
3247 for (i = 0; i < dev->nShortOpCaches; i++) {
3248 if (!dev->srCache[i].object)
3249 return &dev->srCache[i];
3255 usage = 0; /* just to stop the compiler grizzling */
3257 for (i = 0; i < dev->nShortOpCaches; i++) {
3258 if (!dev->srCache[i].dirty &&
3259 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3261 usage = dev->srCache[i].lastUse;
3267 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3274 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3276 yaffs_ChunkCache *cache;
3277 yaffs_Object *theObj;
3282 if (dev->nShortOpCaches > 0) {
3283 /* Try find a non-dirty one... */
3285 cache = yaffs_GrabChunkCacheWorker(dev);
3288 /* They were all dirty, find the last recently used object and flush
3289 * its cache, then find again.
3290 * NB what's here is not very accurate, we actually flush the object
3291 * the last recently used page.
3294 /* With locking we can't assume we can use entry zero */
3301 for (i = 0; i < dev->nShortOpCaches; i++) {
3302 if (dev->srCache[i].object &&
3303 !dev->srCache[i].locked &&
3304 (dev->srCache[i].lastUse < usage || !cache))
3306 usage = dev->srCache[i].lastUse;
3307 theObj = dev->srCache[i].object;
3308 cache = &dev->srCache[i];
3313 if (!cache || cache->dirty) {
3314 /* Flush and try again */
3315 yaffs_FlushFilesChunkCache(theObj);
3316 cache = yaffs_GrabChunkCacheWorker(dev);
3326 /* Find a cached chunk */
3327 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3330 yaffs_Device *dev = obj->myDev;
3332 if (dev->nShortOpCaches > 0) {
3333 for (i = 0; i < dev->nShortOpCaches; i++) {
3334 if (dev->srCache[i].object == obj &&
3335 dev->srCache[i].chunkId == chunkId) {
3338 return &dev->srCache[i];
3345 /* Mark the chunk for the least recently used algorithym */
3346 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3350 if (dev->nShortOpCaches > 0) {
3351 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3352 /* Reset the cache usages */
3354 for (i = 1; i < dev->nShortOpCaches; i++) {
3355 dev->srCache[i].lastUse = 0;
3362 cache->lastUse = dev->srLastUse;
3370 /* Invalidate a single cache page.
3371 * Do this when a whole page gets written,
3372 * ie the short cache for this page is no longer valid.
3374 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3376 if (object->myDev->nShortOpCaches > 0) {
3377 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3380 cache->object = NULL;
3385 /* Invalidate all the cache pages associated with this object
3386 * Do this whenever ther file is deleted or resized.
3388 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3391 yaffs_Device *dev = in->myDev;
3393 if (dev->nShortOpCaches > 0) {
3394 /* Invalidate it. */
3395 for (i = 0; i < dev->nShortOpCaches; i++) {
3396 if (dev->srCache[i].object == in) {
3397 dev->srCache[i].object = NULL;
3403 /*--------------------- Checkpointing --------------------*/
3406 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3408 yaffs_CheckpointValidity cp;
3409 cp.structType = sizeof(cp);
3410 cp.magic = YAFFS_MAGIC;
3412 cp.head = (head) ? 1 : 0;
3414 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3418 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3420 yaffs_CheckpointValidity cp;
3423 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3426 ok = (cp.structType == sizeof(cp)) &&
3427 (cp.magic == YAFFS_MAGIC) &&
3428 (cp.version == 1) &&
3429 (cp.head == ((head) ? 1 : 0));
3433 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3436 cp->nErasedBlocks = dev->nErasedBlocks;
3437 cp->allocationBlock = dev->allocationBlock;
3438 cp->allocationPage = dev->allocationPage;
3439 cp->nFreeChunks = dev->nFreeChunks;
3441 cp->nDeletedFiles = dev->nDeletedFiles;
3442 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3443 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3444 cp->sequenceNumber = dev->sequenceNumber;
3445 cp->oldestDirtySequence = dev->oldestDirtySequence;
3449 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3450 yaffs_CheckpointDevice *cp)
3452 dev->nErasedBlocks = cp->nErasedBlocks;
3453 dev->allocationBlock = cp->allocationBlock;
3454 dev->allocationPage = cp->allocationPage;
3455 dev->nFreeChunks = cp->nFreeChunks;
3457 dev->nDeletedFiles = cp->nDeletedFiles;
3458 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3459 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3460 dev->sequenceNumber = cp->sequenceNumber;
3461 dev->oldestDirtySequence = cp->oldestDirtySequence;
3465 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3467 yaffs_CheckpointDevice cp;
3469 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3473 /* Write device runtime values*/
3474 yaffs_DeviceToCheckpointDevice(&cp,dev);
3475 cp.structType = sizeof(cp);
3477 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3479 /* Write block info */
3481 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3482 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3485 /* Write chunk bits */
3487 nBytes = nBlocks * dev->chunkBitmapStride;
3488 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3494 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3496 yaffs_CheckpointDevice cp;
3498 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3502 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3506 if(cp.structType != sizeof(cp))
3510 yaffs_CheckpointDeviceToDevice(dev,&cp);
3512 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3514 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3518 nBytes = nBlocks * dev->chunkBitmapStride;
3520 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3525 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3529 cp->objectId = obj->objectId;
3530 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3531 cp->chunkId = obj->chunkId;
3532 cp->variantType = obj->variantType;
3533 cp->deleted = obj->deleted;
3534 cp->softDeleted = obj->softDeleted;
3535 cp->unlinked = obj->unlinked;
3536 cp->fake = obj->fake;
3537 cp->renameAllowed = obj->renameAllowed;
3538 cp->unlinkAllowed = obj->unlinkAllowed;
3539 cp->serial = obj->serial;
3540 cp->nDataChunks = obj->nDataChunks;
3542 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3543 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3544 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3545 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3548 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3551 yaffs_Object *parent;
3553 obj->objectId = cp->objectId;
3556 parent = yaffs_FindOrCreateObjectByNumber(
3559 YAFFS_OBJECT_TYPE_DIRECTORY);
3564 yaffs_AddObjectToDirectory(parent, obj);
3566 obj->chunkId = cp->chunkId;
3567 obj->variantType = cp->variantType;
3568 obj->deleted = cp->deleted;
3569 obj->softDeleted = cp->softDeleted;
3570 obj->unlinked = cp->unlinked;
3571 obj->fake = cp->fake;
3572 obj->renameAllowed = cp->renameAllowed;
3573 obj->unlinkAllowed = cp->unlinkAllowed;
3574 obj->serial = cp->serial;
3575 obj->nDataChunks = cp->nDataChunks;
3577 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3578 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3579 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3580 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3582 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3583 obj->lazyLoaded = 1;
3588 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3589 __u32 level, int chunkOffset)
3592 yaffs_Device *dev = in->myDev;
3594 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3599 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3600 if (tn->internal[i]) {
3601 ok = yaffs_CheckpointTnodeWorker(in,
3604 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3607 } else if (level == 0) {
3608 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3609 /* printf("write tnode at %d\n",baseOffset); */
3610 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3612 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3620 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3622 __u32 endMarker = ~0;
3625 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3626 ok = yaffs_CheckpointTnodeWorker(obj,
3627 obj->variant.fileVariant.top,
3628 obj->variant.fileVariant.topLevel,
3631 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3638 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3642 yaffs_Device *dev = obj->myDev;
3643 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3646 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3648 while(ok && (~baseChunk)){
3649 /* Read level 0 tnode */
3651 /* printf("read tnode at %d\n",baseChunk); */
3652 tn = yaffs_GetTnodeRaw(dev);
3654 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3655 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3660 ok = yaffs_AddOrFindLevel0Tnode(dev,
3667 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3675 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3678 yaffs_CheckpointObject cp;
3681 struct list_head *lh;
3684 /* Iterate through the objects in each hash entry,
3685 * dumping them to the checkpointing stream.
3688 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3689 list_for_each(lh, &dev->objectBucket[i].list) {
3691 obj = list_entry(lh, yaffs_Object, hashLink);
3692 if (!obj->deferedFree) {
3693 yaffs_ObjectToCheckpointObject(&cp,obj);
3694 cp.structType = sizeof(cp);
3695 /* printf("Write out object %d type %d\n",obj->objectId,obj->variantType); */
3696 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3698 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3699 ok = yaffs_WriteCheckpointTnodes(obj);
3706 /* Dump end of list */
3707 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3708 cp.structType = sizeof(cp);
3711 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3716 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3719 yaffs_CheckpointObject cp;
3722 yaffs_Object *hardList = NULL;
3724 while(ok && !done) {
3725 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3726 if(cp.structType != sizeof(cp)) {
3727 /* printf("structure parsing failed\n"); */
3731 if(ok && cp.objectId == ~0)
3734 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Read object %d parent %d type %d" TENDSTR),
3735 cp.objectId,cp.parentId,cp.variantType));
3736 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3738 yaffs_CheckpointObjectToObject(obj,&cp);
3739 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3740 ok = yaffs_ReadCheckpointTnodes(obj);
3741 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3742 obj->hardLinks.next =
3743 (struct list_head *)
3753 yaffs_HardlinkFixup(dev,hardList);
3758 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3763 ok = yaffs_CheckpointOpen(dev,1);
3766 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3768 ok = yaffs_WriteCheckpointDevice(dev);
3770 ok = yaffs_WriteCheckpointObjects(dev);
3772 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3774 if(!yaffs_CheckpointClose(dev))
3778 dev->isCheckpointed = 1;
3780 dev->isCheckpointed = 0;
3782 return dev->isCheckpointed;
3785 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3789 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3792 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3794 ok = yaffs_ReadCheckpointDevice(dev);
3796 ok = yaffs_ReadCheckpointObjects(dev);
3798 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3802 if(!yaffs_CheckpointClose(dev))
3806 dev->isCheckpointed = 1;
3808 dev->isCheckpointed = 0;
3814 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3816 if(dev->isCheckpointed ||
3817 dev->blocksInCheckpoint > 0){
3818 dev->isCheckpointed = 0;
3819 yaffs_CheckpointInvalidateStream(dev);
3820 if(dev->superBlock && dev->markSuperBlockDirty)
3821 dev->markSuperBlockDirty(dev->superBlock);
3826 int yaffs_CheckpointSave(yaffs_Device *dev)
3828 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3830 if(!dev->isCheckpointed)
3831 yaffs_WriteCheckpointData(dev);
3833 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3835 return dev->isCheckpointed;
3838 int yaffs_CheckpointRestore(yaffs_Device *dev)
3841 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3843 retval = yaffs_ReadCheckpointData(dev);
3845 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3850 /*--------------------- File read/write ------------------------
3851 * Read and write have very similar structures.
3852 * In general the read/write has three parts to it
3853 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3854 * Some complete chunks
3855 * An incomplete chunk to end off with
3857 * Curve-balls: the first chunk might also be the last chunk.
3860 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
3869 yaffs_ChunkCache *cache;
3876 //chunk = offset / dev->nDataBytesPerChunk + 1;
3877 //start = offset % dev->nDataBytesPerChunk;
3878 yaffs_AddrToChunk(dev,offset,&chunk,&start);
3881 /* OK now check for the curveball where the start and end are in
3884 if ((start + n) < dev->nDataBytesPerChunk) {
3887 nToCopy = dev->nDataBytesPerChunk - start;
3890 cache = yaffs_FindChunkCache(in, chunk);
3892 /* If the chunk is already in the cache or it is less than a whole chunk
3893 * then use the cache (if there is caching)
3894 * else bypass the cache.
3896 if (cache || nToCopy != dev->nDataBytesPerChunk) {
3897 if (dev->nShortOpCaches > 0) {
3899 /* If we can't find the data in the cache, then load it up. */
3902 cache = yaffs_GrabChunkCache(in->myDev);
3904 cache->chunkId = chunk;
3907 yaffs_ReadChunkDataFromObject(in, chunk,
3913 yaffs_UseChunkCache(dev, cache, 0);
3917 #ifdef CONFIG_YAFFS_WINCE
3918 yfsd_UnlockYAFFS(TRUE);
3920 memcpy(buffer, &cache->data[start], nToCopy);
3922 #ifdef CONFIG_YAFFS_WINCE
3923 yfsd_LockYAFFS(TRUE);
3927 /* Read into the local buffer then copy..*/
3930 yaffs_GetTempBuffer(dev, __LINE__);
3931 yaffs_ReadChunkDataFromObject(in, chunk,
3933 #ifdef CONFIG_YAFFS_WINCE
3934 yfsd_UnlockYAFFS(TRUE);
3936 memcpy(buffer, &localBuffer[start], nToCopy);
3938 #ifdef CONFIG_YAFFS_WINCE
3939 yfsd_LockYAFFS(TRUE);
3941 yaffs_ReleaseTempBuffer(dev, localBuffer,
3946 #ifdef CONFIG_YAFFS_WINCE
3947 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3949 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3950 * This is because we otherwise screw up WinCE's memory mapper
3952 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3954 #ifdef CONFIG_YAFFS_WINCE
3955 yfsd_UnlockYAFFS(TRUE);
3957 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
3959 #ifdef CONFIG_YAFFS_WINCE
3960 yfsd_LockYAFFS(TRUE);
3961 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3965 /* A full chunk. Read directly into the supplied buffer. */
3966 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3980 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
3981 int nBytes, int writeThrough)
3990 int startOfWrite = offset;
3991 int chunkWritten = 0;
3998 while (n > 0 && chunkWritten >= 0) {
3999 //chunk = offset / dev->nDataBytesPerChunk + 1;
4000 //start = offset % dev->nDataBytesPerChunk;
4001 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4004 /* OK now check for the curveball where the start and end are in
4008 if ((start + n) < dev->nDataBytesPerChunk) {
4011 /* Now folks, to calculate how many bytes to write back....
4012 * If we're overwriting and not writing to then end of file then
4013 * we need to write back as much as was there before.
4017 in->variant.fileVariant.fileSize -
4018 ((chunk - 1) * dev->nDataBytesPerChunk);
4020 if (nBytesRead > dev->nDataBytesPerChunk) {
4021 nBytesRead = dev->nDataBytesPerChunk;
4026 (start + n)) ? nBytesRead : (start + n);
4029 nToCopy = dev->nDataBytesPerChunk - start;
4030 nToWriteBack = dev->nDataBytesPerChunk;
4033 if (nToCopy != dev->nDataBytesPerChunk) {
4034 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4035 if (dev->nShortOpCaches > 0) {
4036 yaffs_ChunkCache *cache;
4037 /* If we can't find the data in the cache, then load the cache */
4038 cache = yaffs_FindChunkCache(in, chunk);
4041 && yaffs_CheckSpaceForAllocation(in->
4043 cache = yaffs_GrabChunkCache(in->myDev);
4045 cache->chunkId = chunk;
4048 yaffs_ReadChunkDataFromObject(in, chunk,
4054 !yaffs_CheckSpaceForAllocation(in->myDev)){
4055 /* Drop the cache if it was a read cache item and
4056 * no space check has been made for it.
4062 yaffs_UseChunkCache(dev, cache, 1);
4064 #ifdef CONFIG_YAFFS_WINCE
4065 yfsd_UnlockYAFFS(TRUE);
4068 memcpy(&cache->data[start], buffer,
4071 #ifdef CONFIG_YAFFS_WINCE
4072 yfsd_LockYAFFS(TRUE);
4075 cache->nBytes = nToWriteBack;
4079 yaffs_WriteChunkDataToObject
4082 cache->data, cache->nBytes,
4088 chunkWritten = -1; /* fail the write */
4091 /* An incomplete start or end chunk (or maybe both start and end chunk)
4092 * Read into the local buffer then copy, then copy over and write back.
4096 yaffs_GetTempBuffer(dev, __LINE__);
4098 yaffs_ReadChunkDataFromObject(in, chunk,
4101 #ifdef CONFIG_YAFFS_WINCE
4102 yfsd_UnlockYAFFS(TRUE);
4105 memcpy(&localBuffer[start], buffer, nToCopy);
4107 #ifdef CONFIG_YAFFS_WINCE
4108 yfsd_LockYAFFS(TRUE);
4111 yaffs_WriteChunkDataToObject(in, chunk,
4116 yaffs_ReleaseTempBuffer(dev, localBuffer,
4123 #ifdef CONFIG_YAFFS_WINCE
4124 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4125 * This is because we otherwise screw up WinCE's memory mapper
4127 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4128 #ifdef CONFIG_YAFFS_WINCE
4129 yfsd_UnlockYAFFS(TRUE);
4131 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4132 #ifdef CONFIG_YAFFS_WINCE
4133 yfsd_LockYAFFS(TRUE);
4136 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4137 dev->nDataBytesPerChunk,
4139 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4141 /* A full chunk. Write directly from the supplied buffer. */
4143 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4144 dev->nDataBytesPerChunk,
4147 /* Since we've overwritten the cached data, we better invalidate it. */
4148 yaffs_InvalidateChunkCache(in, chunk);
4151 if (chunkWritten >= 0) {
4160 /* Update file object */
4162 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4163 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4172 /* ---------------------- File resizing stuff ------------------ */
4174 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4177 yaffs_Device *dev = in->myDev;
4178 int oldFileSize = in->variant.fileVariant.fileSize;
4180 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4182 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4183 dev->nDataBytesPerChunk;
4187 /* Delete backwards so that we don't end up with holes if
4188 * power is lost part-way through the operation.
4190 for (i = lastDel; i >= startDel; i--) {
4191 /* NB this could be optimised somewhat,
4192 * eg. could retrieve the tags and write them without
4193 * using yaffs_DeleteChunk
4196 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4199 (dev->internalStartBlock * dev->nChunksPerBlock)
4201 ((dev->internalEndBlock +
4202 1) * dev->nChunksPerBlock)) {
4203 T(YAFFS_TRACE_ALWAYS,
4204 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4208 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4215 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4218 int oldFileSize = in->variant.fileVariant.fileSize;
4219 int newSizeOfPartialChunk;
4222 yaffs_Device *dev = in->myDev;
4224 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4226 yaffs_FlushFilesChunkCache(in);
4227 yaffs_InvalidateWholeChunkCache(in);
4229 yaffs_CheckGarbageCollection(dev);
4231 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4232 return yaffs_GetFileSize(in);
4235 if (newSize == oldFileSize) {
4239 if (newSize < oldFileSize) {
4241 yaffs_PruneResizedChunks(in, newSize);
4243 if (newSizeOfPartialChunk != 0) {
4244 int lastChunk = 1 + newFullChunks;
4246 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4248 /* Got to read and rewrite the last chunk with its new size and zero pad */
4249 yaffs_ReadChunkDataFromObject(in, lastChunk,
4252 memset(localBuffer + newSizeOfPartialChunk, 0,
4253 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4255 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4256 newSizeOfPartialChunk, 1);
4258 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4261 in->variant.fileVariant.fileSize = newSize;
4263 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4265 /* Write a new object header.
4266 * show we've shrunk the file, if need be
4267 * Do this only if the file is not in the deleted directories.
4269 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4270 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4271 yaffs_UpdateObjectHeader(in, NULL, 0,
4272 (newSize < oldFileSize) ? 1 : 0, 0);
4278 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4280 obj = yaffs_GetEquivalentObject(obj);
4282 switch (obj->variantType) {
4283 case YAFFS_OBJECT_TYPE_FILE:
4284 return obj->variant.fileVariant.fileSize;
4285 case YAFFS_OBJECT_TYPE_SYMLINK:
4286 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4294 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4298 yaffs_FlushFilesChunkCache(in);
4300 #ifdef CONFIG_YAFFS_WINCE
4301 yfsd_WinFileTimeNow(in->win_mtime);
4304 in->yst_mtime = Y_CURRENT_TIME;
4310 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4311 0) ? YAFFS_OK : YAFFS_FAIL;
4320 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4323 /* First off, invalidate the file's data in the cache, without flushing. */
4324 yaffs_InvalidateWholeChunkCache(in);
4326 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4327 /* Move to the unlinked directory so we have a record that it was deleted. */
4328 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4332 yaffs_RemoveObjectFromDirectory(in);
4333 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4336 yaffs_FreeObject(in);
4341 /* yaffs_DeleteFile deletes the whole file data
4342 * and the inode associated with the file.
4343 * It does not delete the links associated with the file.
4345 static int yaffs_UnlinkFile(yaffs_Object * in)
4349 int immediateDeletion = 0;
4354 immediateDeletion = 1;
4358 if (in->inUse <= 0) {
4359 immediateDeletion = 1;
4363 if (immediateDeletion) {
4365 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4367 T(YAFFS_TRACE_TRACING,
4368 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4371 in->myDev->nDeletedFiles++;
4372 if (0 && in->myDev->isYaffs2) {
4373 yaffs_ResizeFile(in, 0);
4375 yaffs_SoftDeleteFile(in);
4378 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4386 int yaffs_DeleteFile(yaffs_Object * in)
4388 int retVal = YAFFS_OK;
4390 if (in->nDataChunks > 0) {
4391 /* Use soft deletion if there is data in the file */
4392 if (!in->unlinked) {
4393 retVal = yaffs_UnlinkFile(in);
4395 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4397 in->myDev->nDeletedFiles++;
4398 yaffs_SoftDeleteFile(in);
4400 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4402 /* The file has no data chunks so we toss it immediately */
4403 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4404 in->variant.fileVariant.top = NULL;
4405 yaffs_DoGenericObjectDeletion(in);
4411 static int yaffs_DeleteDirectory(yaffs_Object * in)
4413 /* First check that the directory is empty. */
4414 if (list_empty(&in->variant.directoryVariant.children)) {
4415 return yaffs_DoGenericObjectDeletion(in);
4422 static int yaffs_DeleteSymLink(yaffs_Object * in)
4424 YFREE(in->variant.symLinkVariant.alias);
4426 return yaffs_DoGenericObjectDeletion(in);
4429 static int yaffs_DeleteHardLink(yaffs_Object * in)
4431 /* remove this hardlink from the list assocaited with the equivalent
4434 list_del(&in->hardLinks);
4435 return yaffs_DoGenericObjectDeletion(in);
4438 static void yaffs_DestroyObject(yaffs_Object * obj)
4440 switch (obj->variantType) {
4441 case YAFFS_OBJECT_TYPE_FILE:
4442 yaffs_DeleteFile(obj);
4444 case YAFFS_OBJECT_TYPE_DIRECTORY:
4445 yaffs_DeleteDirectory(obj);
4447 case YAFFS_OBJECT_TYPE_SYMLINK:
4448 yaffs_DeleteSymLink(obj);
4450 case YAFFS_OBJECT_TYPE_HARDLINK:
4451 yaffs_DeleteHardLink(obj);
4453 case YAFFS_OBJECT_TYPE_SPECIAL:
4454 yaffs_DoGenericObjectDeletion(obj);
4456 case YAFFS_OBJECT_TYPE_UNKNOWN:
4457 break; /* should not happen. */
4461 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4464 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4465 return yaffs_DeleteHardLink(obj);
4466 } else if (!list_empty(&obj->hardLinks)) {
4467 /* Curve ball: We're unlinking an object that has a hardlink.
4469 * This problem arises because we are not strictly following
4470 * The Linux link/inode model.
4472 * We can't really delete the object.
4473 * Instead, we do the following:
4474 * - Select a hardlink.
4475 * - Unhook it from the hard links
4476 * - Unhook it from its parent directory (so that the rename can work)
4477 * - Rename the object to the hardlink's name.
4478 * - Delete the hardlink
4483 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4485 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4487 list_del_init(&hl->hardLinks);
4488 list_del_init(&hl->siblings);
4490 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4492 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4494 if (retVal == YAFFS_OK) {
4495 retVal = yaffs_DoGenericObjectDeletion(hl);
4500 switch (obj->variantType) {
4501 case YAFFS_OBJECT_TYPE_FILE:
4502 return yaffs_UnlinkFile(obj);
4504 case YAFFS_OBJECT_TYPE_DIRECTORY:
4505 return yaffs_DeleteDirectory(obj);
4507 case YAFFS_OBJECT_TYPE_SYMLINK:
4508 return yaffs_DeleteSymLink(obj);
4510 case YAFFS_OBJECT_TYPE_SPECIAL:
4511 return yaffs_DoGenericObjectDeletion(obj);
4513 case YAFFS_OBJECT_TYPE_HARDLINK:
4514 case YAFFS_OBJECT_TYPE_UNKNOWN:
4522 static int yaffs_UnlinkObject( yaffs_Object *obj)
4525 if (obj && obj->unlinkAllowed) {
4526 return yaffs_UnlinkWorker(obj);
4532 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4536 obj = yaffs_FindObjectByName(dir, name);
4537 return yaffs_UnlinkObject(obj);
4540 /*----------------------- Initialisation Scanning ---------------------- */
4542 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4543 int backwardScanning)
4547 if (!backwardScanning) {
4548 /* Handle YAFFS1 forward scanning case
4549 * For YAFFS1 we always do the deletion
4553 /* Handle YAFFS2 case (backward scanning)
4554 * If the shadowed object exists then ignore.
4556 if (yaffs_FindObjectByNumber(dev, objId)) {
4561 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4562 * We put it in unlinked dir to be cleaned up after the scanning
4565 yaffs_FindOrCreateObjectByNumber(dev, objId,
4566 YAFFS_OBJECT_TYPE_FILE);
4567 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4568 obj->variant.fileVariant.shrinkSize = 0;
4569 obj->valid = 1; /* So that we don't read any other info for this file */
4579 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4586 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4588 in = yaffs_FindObjectByNumber(dev,
4589 hl->variant.hardLinkVariant.
4590 equivalentObjectId);
4593 /* Add the hardlink pointers */
4594 hl->variant.hardLinkVariant.equivalentObject = in;
4595 list_add(&hl->hardLinks, &in->hardLinks);
4597 /* Todo Need to report/handle this better.
4598 * Got a problem... hardlink to a non-existant object
4600 hl->variant.hardLinkVariant.equivalentObject = NULL;
4601 INIT_LIST_HEAD(&hl->hardLinks);
4613 static int ybicmp(const void *a, const void *b){
4614 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4615 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4616 register int ablock = ((yaffs_BlockIndex *)a)->block;
4617 register int bblock = ((yaffs_BlockIndex *)b)->block;
4619 return ablock - bblock;
4625 static int yaffs_Scan(yaffs_Device * dev)
4627 yaffs_ExtendedTags tags;
4632 int nBlocksToScan = 0;
4638 yaffs_BlockState state;
4639 yaffs_Object *hardList = NULL;
4641 yaffs_BlockInfo *bi;
4643 yaffs_ObjectHeader *oh;
4645 yaffs_Object *parent;
4646 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4650 yaffs_BlockIndex *blockIndex = NULL;
4652 if (dev->isYaffs2) {
4654 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4658 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4661 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4662 dev->internalStartBlock, dev->internalEndBlock));
4664 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4666 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4668 if (dev->isYaffs2) {
4669 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4672 /* Scan all the blocks to determine their state */
4673 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4674 bi = yaffs_GetBlockInfo(dev, blk);
4675 yaffs_ClearChunkBits(dev, blk);
4677 bi->softDeletions = 0;
4679 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4681 bi->blockState = state;
4682 bi->sequenceNumber = sequenceNumber;
4684 T(YAFFS_TRACE_SCAN_DEBUG,
4685 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4686 state, sequenceNumber));
4688 if (state == YAFFS_BLOCK_STATE_DEAD) {
4689 T(YAFFS_TRACE_BAD_BLOCKS,
4690 (TSTR("block %d is bad" TENDSTR), blk));
4691 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4692 T(YAFFS_TRACE_SCAN_DEBUG,
4693 (TSTR("Block empty " TENDSTR)));
4694 dev->nErasedBlocks++;
4695 dev->nFreeChunks += dev->nChunksPerBlock;
4696 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4698 /* Determine the highest sequence number */
4699 if (dev->isYaffs2 &&
4700 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4701 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4703 blockIndex[nBlocksToScan].seq = sequenceNumber;
4704 blockIndex[nBlocksToScan].block = blk;
4708 if (sequenceNumber >= dev->sequenceNumber) {
4709 dev->sequenceNumber = sequenceNumber;
4711 } else if (dev->isYaffs2) {
4712 /* TODO: Nasty sequence number! */
4715 ("Block scanning block %d has bad sequence number %d"
4716 TENDSTR), blk, sequenceNumber));
4723 * Dungy old bubble sort for now...
4725 if (dev->isYaffs2) {
4726 yaffs_BlockIndex temp;
4730 for (i = 0; i < nBlocksToScan; i++)
4731 for (j = i + 1; j < nBlocksToScan; j++)
4732 if (blockIndex[i].seq > blockIndex[j].seq) {
4733 temp = blockIndex[j];
4734 blockIndex[j] = blockIndex[i];
4735 blockIndex[i] = temp;
4739 /* Now scan the blocks looking at the data. */
4740 if (dev->isYaffs2) {
4742 endIterator = nBlocksToScan - 1;
4743 T(YAFFS_TRACE_SCAN_DEBUG,
4744 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4746 startIterator = dev->internalStartBlock;
4747 endIterator = dev->internalEndBlock;
4750 /* For each block.... */
4751 for (blockIterator = startIterator; blockIterator <= endIterator;
4754 if (dev->isYaffs2) {
4755 /* get the block to scan in the correct order */
4756 blk = blockIndex[blockIterator].block;
4758 blk = blockIterator;
4761 bi = yaffs_GetBlockInfo(dev, blk);
4762 state = bi->blockState;
4766 /* For each chunk in each block that needs scanning....*/
4767 for (c = 0; c < dev->nChunksPerBlock &&
4768 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4769 /* Read the tags and decide what to do */
4770 chunk = blk * dev->nChunksPerBlock + c;
4772 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4775 /* Let's have a good look at this chunk... */
4777 if (!dev->isYaffs2 && tags.chunkDeleted) {
4783 /*T((" %d %d deleted\n",blk,c)); */
4784 } else if (!tags.chunkUsed) {
4785 /* An unassigned chunk in the block
4786 * This means that either the block is empty or
4787 * this is the one being allocated from
4791 /* We're looking at the first chunk in the block so the block is unused */
4792 state = YAFFS_BLOCK_STATE_EMPTY;
4793 dev->nErasedBlocks++;
4795 /* this is the block being allocated from */
4798 (" Allocating from %d %d" TENDSTR),
4800 state = YAFFS_BLOCK_STATE_ALLOCATING;
4801 dev->allocationBlock = blk;
4802 dev->allocationPage = c;
4803 dev->allocationBlockFinder = blk;
4804 /* Set it to here to encourage the allocator to go forth from here. */
4806 /* Yaffs2 sanity check:
4807 * This should be the one with the highest sequence number
4810 && (dev->sequenceNumber !=
4811 bi->sequenceNumber)) {
4812 T(YAFFS_TRACE_ALWAYS,
4814 ("yaffs: Allocation block %d was not highest sequence id:"
4815 " block seq = %d, dev seq = %d"
4816 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4820 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4821 } else if (tags.chunkId > 0) {
4822 /* chunkId > 0 so it is a data chunk... */
4823 unsigned int endpos;
4825 yaffs_SetChunkBit(dev, blk, c);
4828 in = yaffs_FindOrCreateObjectByNumber(dev,
4831 YAFFS_OBJECT_TYPE_FILE);
4832 /* PutChunkIntoFile checks for a clash (two data chunks with
4833 * the same chunkId).
4835 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4838 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
4840 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4841 && in->variant.fileVariant.scannedFileSize <
4843 in->variant.fileVariant.
4844 scannedFileSize = endpos;
4845 if (!dev->useHeaderFileSize) {
4846 in->variant.fileVariant.
4848 in->variant.fileVariant.
4853 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4855 /* chunkId == 0, so it is an ObjectHeader.
4856 * Thus, we read in the object header and make the object
4858 yaffs_SetChunkBit(dev, blk, c);
4861 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4865 oh = (yaffs_ObjectHeader *) chunkData;
4867 in = yaffs_FindObjectByNumber(dev,
4869 if (in && in->variantType != oh->type) {
4870 /* This should not happen, but somehow
4871 * Wev'e ended up with an objectId that has been reused but not yet
4872 * deleted, and worse still it has changed type. Delete the old object.
4875 yaffs_DestroyObject(in);
4880 in = yaffs_FindOrCreateObjectByNumber(dev,
4885 if (oh->shadowsObject > 0) {
4886 yaffs_HandleShadowedObject(dev,
4893 /* We have already filled this one. We have a duplicate and need to resolve it. */
4895 unsigned existingSerial = in->serial;
4896 unsigned newSerial = tags.serialNumber;
4898 if (dev->isYaffs2 ||
4899 ((existingSerial + 1) & 3) ==
4901 /* Use new one - destroy the exisiting one */
4902 yaffs_DeleteChunk(dev,
4907 /* Use existing - destroy this one. */
4908 yaffs_DeleteChunk(dev, chunk, 1,
4914 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4915 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4916 /* We only load some info, don't fiddle with directory structure */
4918 in->variantType = oh->type;
4920 in->yst_mode = oh->yst_mode;
4921 #ifdef CONFIG_YAFFS_WINCE
4922 in->win_atime[0] = oh->win_atime[0];
4923 in->win_ctime[0] = oh->win_ctime[0];
4924 in->win_mtime[0] = oh->win_mtime[0];
4925 in->win_atime[1] = oh->win_atime[1];
4926 in->win_ctime[1] = oh->win_ctime[1];
4927 in->win_mtime[1] = oh->win_mtime[1];
4929 in->yst_uid = oh->yst_uid;
4930 in->yst_gid = oh->yst_gid;
4931 in->yst_atime = oh->yst_atime;
4932 in->yst_mtime = oh->yst_mtime;
4933 in->yst_ctime = oh->yst_ctime;
4934 in->yst_rdev = oh->yst_rdev;
4936 in->chunkId = chunk;
4938 } else if (!in->valid) {
4939 /* we need to load this info */
4942 in->variantType = oh->type;
4944 in->yst_mode = oh->yst_mode;
4945 #ifdef CONFIG_YAFFS_WINCE
4946 in->win_atime[0] = oh->win_atime[0];
4947 in->win_ctime[0] = oh->win_ctime[0];
4948 in->win_mtime[0] = oh->win_mtime[0];
4949 in->win_atime[1] = oh->win_atime[1];
4950 in->win_ctime[1] = oh->win_ctime[1];
4951 in->win_mtime[1] = oh->win_mtime[1];
4953 in->yst_uid = oh->yst_uid;
4954 in->yst_gid = oh->yst_gid;
4955 in->yst_atime = oh->yst_atime;
4956 in->yst_mtime = oh->yst_mtime;
4957 in->yst_ctime = oh->yst_ctime;
4958 in->yst_rdev = oh->yst_rdev;
4960 in->chunkId = chunk;
4962 yaffs_SetObjectName(in, oh->name);
4965 /* directory stuff...
4970 yaffs_FindOrCreateObjectByNumber
4971 (dev, oh->parentObjectId,
4972 YAFFS_OBJECT_TYPE_DIRECTORY);
4973 if (parent->variantType ==
4974 YAFFS_OBJECT_TYPE_UNKNOWN) {
4975 /* Set up as a directory */
4976 parent->variantType =
4977 YAFFS_OBJECT_TYPE_DIRECTORY;
4978 INIT_LIST_HEAD(&parent->variant.
4981 } else if (parent->variantType !=
4982 YAFFS_OBJECT_TYPE_DIRECTORY)
4984 /* Hoosterman, another problem....
4985 * We're trying to use a non-directory as a directory
4988 T(YAFFS_TRACE_ERROR,
4990 ("yaffs tragedy: attempting to use non-directory as"
4991 " a directory in scan. Put in lost+found."
4993 parent = dev->lostNFoundDir;
4996 yaffs_AddObjectToDirectory(parent, in);
4998 if (0 && (parent == dev->deletedDir ||
4999 parent == dev->unlinkedDir)) {
5000 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5001 dev->nDeletedFiles++;
5003 /* Note re hardlinks.
5004 * Since we might scan a hardlink before its equivalent object is scanned
5005 * we put them all in a list.
5006 * After scanning is complete, we should have all the objects, so we run through this
5007 * list and fix up all the chains.
5010 switch (in->variantType) {
5011 case YAFFS_OBJECT_TYPE_UNKNOWN:
5012 /* Todo got a problem */
5014 case YAFFS_OBJECT_TYPE_FILE:
5017 /* Prune back the shrunken chunks */
5018 yaffs_PruneResizedChunks
5020 /* Mark the block as having a shrinkHeader */
5021 bi->hasShrinkHeader = 1;
5024 if (dev->useHeaderFileSize)
5026 in->variant.fileVariant.
5031 case YAFFS_OBJECT_TYPE_HARDLINK:
5032 in->variant.hardLinkVariant.
5033 equivalentObjectId =
5034 oh->equivalentObjectId;
5035 in->hardLinks.next =
5036 (struct list_head *)
5040 case YAFFS_OBJECT_TYPE_DIRECTORY:
5043 case YAFFS_OBJECT_TYPE_SPECIAL:
5046 case YAFFS_OBJECT_TYPE_SYMLINK:
5047 in->variant.symLinkVariant.
5049 yaffs_CloneString(oh->alias);
5053 if (parent == dev->deletedDir) {
5054 yaffs_DestroyObject(in);
5055 bi->hasShrinkHeader = 1;
5061 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5062 /* If we got this far while scanning, then the block is fully allocated.*/
5063 state = YAFFS_BLOCK_STATE_FULL;
5066 bi->blockState = state;
5068 /* Now let's see if it was dirty */
5069 if (bi->pagesInUse == 0 &&
5070 !bi->hasShrinkHeader &&
5071 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5072 yaffs_BlockBecameDirty(dev, blk);
5082 /* Ok, we've done all the scanning.
5083 * Fix up the hard link chains.
5084 * We should now have scanned all the objects, now it's time to add these
5088 yaffs_HardlinkFixup(dev,hardList);
5090 /* Handle the unlinked files. Since they were left in an unlinked state we should
5094 struct list_head *i;
5095 struct list_head *n;
5098 /* Soft delete all the unlinked files */
5099 list_for_each_safe(i, n,
5100 &dev->unlinkedDir->variant.directoryVariant.
5103 l = list_entry(i, yaffs_Object, siblings);
5104 yaffs_DestroyObject(l);
5109 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5111 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5116 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5119 yaffs_ObjectHeader *oh;
5120 yaffs_Device *dev = in->myDev;
5121 yaffs_ExtendedTags tags;
5126 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5128 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5129 oh = (yaffs_ObjectHeader *) chunkData;
5131 in->yst_mode = oh->yst_mode;
5132 #ifdef CONFIG_YAFFS_WINCE
5133 in->win_atime[0] = oh->win_atime[0];
5134 in->win_ctime[0] = oh->win_ctime[0];
5135 in->win_mtime[0] = oh->win_mtime[0];
5136 in->win_atime[1] = oh->win_atime[1];
5137 in->win_ctime[1] = oh->win_ctime[1];
5138 in->win_mtime[1] = oh->win_mtime[1];
5140 in->yst_uid = oh->yst_uid;
5141 in->yst_gid = oh->yst_gid;
5142 in->yst_atime = oh->yst_atime;
5143 in->yst_mtime = oh->yst_mtime;
5144 in->yst_ctime = oh->yst_ctime;
5145 in->yst_rdev = oh->yst_rdev;
5148 yaffs_SetObjectName(in, oh->name);
5150 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5151 in->variant.symLinkVariant.alias =
5152 yaffs_CloneString(oh->alias);
5154 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5158 static int yaffs_ScanBackwards(yaffs_Device * dev)
5160 yaffs_ExtendedTags tags;
5165 int nBlocksToScan = 0;
5171 yaffs_BlockState state;
5172 yaffs_Object *hardList = NULL;
5173 yaffs_BlockInfo *bi;
5175 yaffs_ObjectHeader *oh;
5177 yaffs_Object *parent;
5178 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5184 int foundChunksInBlock;
5185 int equivalentObjectId;
5188 yaffs_BlockIndex *blockIndex = NULL;
5189 int altBlockIndex = 0;
5191 if (!dev->isYaffs2) {
5193 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5199 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5200 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5203 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5205 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5208 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5214 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5218 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5220 /* Scan all the blocks to determine their state */
5221 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5222 bi = yaffs_GetBlockInfo(dev, blk);
5223 yaffs_ClearChunkBits(dev, blk);
5225 bi->softDeletions = 0;
5227 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5229 bi->blockState = state;
5230 bi->sequenceNumber = sequenceNumber;
5232 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5233 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5235 T(YAFFS_TRACE_SCAN_DEBUG,
5236 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5237 state, sequenceNumber));
5240 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5241 /* todo .. fix free space ? */
5243 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5244 T(YAFFS_TRACE_BAD_BLOCKS,
5245 (TSTR("block %d is bad" TENDSTR), blk));
5246 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5247 T(YAFFS_TRACE_SCAN_DEBUG,
5248 (TSTR("Block empty " TENDSTR)));
5249 dev->nErasedBlocks++;
5250 dev->nFreeChunks += dev->nChunksPerBlock;
5251 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5253 /* Determine the highest sequence number */
5254 if (dev->isYaffs2 &&
5255 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5256 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5258 blockIndex[nBlocksToScan].seq = sequenceNumber;
5259 blockIndex[nBlocksToScan].block = blk;
5263 if (sequenceNumber >= dev->sequenceNumber) {
5264 dev->sequenceNumber = sequenceNumber;
5266 } else if (dev->isYaffs2) {
5267 /* TODO: Nasty sequence number! */
5270 ("Block scanning block %d has bad sequence number %d"
5271 TENDSTR), blk, sequenceNumber));
5278 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5284 /* Sort the blocks */
5285 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5287 /* Use qsort now. */
5288 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5292 /* Dungy old bubble sort... */
5294 yaffs_BlockIndex temp;
5298 for (i = 0; i < nBlocksToScan; i++)
5299 for (j = i + 1; j < nBlocksToScan; j++)
5300 if (blockIndex[i].seq > blockIndex[j].seq) {
5301 temp = blockIndex[j];
5302 blockIndex[j] = blockIndex[i];
5303 blockIndex[i] = temp;
5310 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5312 /* Now scan the blocks looking at the data. */
5314 endIterator = nBlocksToScan - 1;
5315 T(YAFFS_TRACE_SCAN_DEBUG,
5316 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5318 /* For each block.... backwards */
5319 for (blockIterator = endIterator; blockIterator >= startIterator;
5321 /* Cooperative multitasking! This loop can run for so
5322 long that watchdog timers expire. */
5325 /* get the block to scan in the correct order */
5326 blk = blockIndex[blockIterator].block;
5328 bi = yaffs_GetBlockInfo(dev, blk);
5329 state = bi->blockState;
5333 /* For each chunk in each block that needs scanning.... */
5334 foundChunksInBlock = 0;
5335 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5336 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5337 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5338 /* Scan backwards...
5339 * Read the tags and decide what to do
5341 chunk = blk * dev->nChunksPerBlock + c;
5343 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5346 /* Let's have a good look at this chunk... */
5348 if (!tags.chunkUsed) {
5349 /* An unassigned chunk in the block.
5350 * If there are used chunks after this one, then
5351 * it is a chunk that was skipped due to failing the erased
5352 * check. Just skip it so that it can be deleted.
5353 * But, more typically, We get here when this is an unallocated
5354 * chunk and his means that either the block is empty or
5355 * this is the one being allocated from
5358 if(foundChunksInBlock)
5360 /* This is a chunk that was skipped due to failing the erased check */
5362 } else if (c == 0) {
5363 /* We're looking at the first chunk in the block so the block is unused */
5364 state = YAFFS_BLOCK_STATE_EMPTY;
5365 dev->nErasedBlocks++;
5367 /* this is the block being allocated from */
5369 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5372 (" Allocating from %d %d"
5375 state = YAFFS_BLOCK_STATE_ALLOCATING;
5376 dev->allocationBlock = blk;
5377 dev->allocationPage = c;
5378 dev->allocationBlockFinder = blk;
5379 /* Set it to here to encourage the allocator to
5380 * go forth from here.
5383 /* Yaffs2 sanity check:
5384 * This should be the one with the highest sequence number
5387 && (dev->sequenceNumber !=
5388 bi->sequenceNumber)) {
5389 T(YAFFS_TRACE_ALWAYS,
5391 ("yaffs: Allocation block %d was not highest sequence "
5392 "id: block seq = %d, dev seq = %d"
5395 dev->sequenceNumber));
5400 } else if (tags.chunkId > 0) {
5401 /* chunkId > 0 so it is a data chunk... */
5402 unsigned int endpos;
5404 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
5406 foundChunksInBlock = 1;
5409 yaffs_SetChunkBit(dev, blk, c);
5412 in = yaffs_FindOrCreateObjectByNumber(dev,
5415 YAFFS_OBJECT_TYPE_FILE);
5416 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5418 in->variant.fileVariant.shrinkSize) {
5419 /* This has not been invalidated by a resize */
5420 yaffs_PutChunkIntoFile(in, tags.chunkId,
5423 /* File size is calculated by looking at the data chunks if we have not
5424 * seen an object header yet. Stop this practice once we find an object header.
5428 1) * dev->nDataBytesPerChunk +
5431 if (!in->valid && /* have not got an object header yet */
5432 in->variant.fileVariant.
5433 scannedFileSize < endpos) {
5434 in->variant.fileVariant.
5435 scannedFileSize = endpos;
5436 in->variant.fileVariant.
5438 in->variant.fileVariant.
5443 /* This chunk has been invalidated by a resize, so delete */
5444 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5448 /* chunkId == 0, so it is an ObjectHeader.
5449 * Thus, we read in the object header and make the object
5451 foundChunksInBlock = 1;
5453 yaffs_SetChunkBit(dev, blk, c);
5459 if (tags.extraHeaderInfoAvailable) {
5460 in = yaffs_FindOrCreateObjectByNumber
5461 (dev, tags.objectId,
5462 tags.extraObjectType);
5466 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5469 tags.extraShadows ||
5471 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5472 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5475 /* If we don't have valid info then we need to read the chunk
5476 * TODO In future we can probably defer reading the chunk and
5477 * living with invalid data until needed.
5480 result = yaffs_ReadChunkWithTagsFromNAND(dev,
5485 oh = (yaffs_ObjectHeader *) chunkData;
5488 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5493 /* TODO Hoosterman we have a problem! */
5494 T(YAFFS_TRACE_ERROR,
5496 ("yaffs tragedy: Could not make object for object %d "
5497 "at chunk %d during scan"
5498 TENDSTR), tags.objectId, chunk));
5503 /* We have already filled this one.
5504 * We have a duplicate that will be discarded, but
5505 * we first have to suck out resize info if it is a file.
5508 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5510 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5511 (tags.extraHeaderInfoAvailable &&
5512 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5515 (oh) ? oh->fileSize : tags.
5517 __u32 parentObjectId =
5519 parentObjectId : tags.
5520 extraParentObjectId;
5522 (oh) ? oh->isShrink : tags.
5523 extraIsShrinkHeader;
5525 /* If it is deleted (unlinked at start also means deleted)
5526 * we treat the file size as being zeroed at this point.
5528 if (parentObjectId ==
5529 YAFFS_OBJECTID_DELETED
5530 || parentObjectId ==
5531 YAFFS_OBJECTID_UNLINKED) {
5537 in->variant.fileVariant.
5538 shrinkSize > thisSize) {
5539 in->variant.fileVariant.
5545 bi->hasShrinkHeader = 1;
5549 /* Use existing - destroy this one. */
5550 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5555 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5557 YAFFS_OBJECTID_LOSTNFOUND)) {
5558 /* We only load some info, don't fiddle with directory structure */
5562 in->variantType = oh->type;
5564 in->yst_mode = oh->yst_mode;
5565 #ifdef CONFIG_YAFFS_WINCE
5566 in->win_atime[0] = oh->win_atime[0];
5567 in->win_ctime[0] = oh->win_ctime[0];
5568 in->win_mtime[0] = oh->win_mtime[0];
5569 in->win_atime[1] = oh->win_atime[1];
5570 in->win_ctime[1] = oh->win_ctime[1];
5571 in->win_mtime[1] = oh->win_mtime[1];
5573 in->yst_uid = oh->yst_uid;
5574 in->yst_gid = oh->yst_gid;
5575 in->yst_atime = oh->yst_atime;
5576 in->yst_mtime = oh->yst_mtime;
5577 in->yst_ctime = oh->yst_ctime;
5578 in->yst_rdev = oh->yst_rdev;
5582 in->variantType = tags.extraObjectType;
5586 in->chunkId = chunk;
5588 } else if (!in->valid) {
5589 /* we need to load this info */
5592 in->chunkId = chunk;
5595 in->variantType = oh->type;
5597 in->yst_mode = oh->yst_mode;
5598 #ifdef CONFIG_YAFFS_WINCE
5599 in->win_atime[0] = oh->win_atime[0];
5600 in->win_ctime[0] = oh->win_ctime[0];
5601 in->win_mtime[0] = oh->win_mtime[0];
5602 in->win_atime[1] = oh->win_atime[1];
5603 in->win_ctime[1] = oh->win_ctime[1];
5604 in->win_mtime[1] = oh->win_mtime[1];
5606 in->yst_uid = oh->yst_uid;
5607 in->yst_gid = oh->yst_gid;
5608 in->yst_atime = oh->yst_atime;
5609 in->yst_mtime = oh->yst_mtime;
5610 in->yst_ctime = oh->yst_ctime;
5611 in->yst_rdev = oh->yst_rdev;
5614 if (oh->shadowsObject > 0)
5615 yaffs_HandleShadowedObject(dev,
5621 yaffs_SetObjectName(in, oh->name);
5623 yaffs_FindOrCreateObjectByNumber
5624 (dev, oh->parentObjectId,
5625 YAFFS_OBJECT_TYPE_DIRECTORY);
5627 fileSize = oh->fileSize;
5628 isShrink = oh->isShrink;
5629 equivalentObjectId = oh->equivalentObjectId;
5633 in->variantType = tags.extraObjectType;
5635 yaffs_FindOrCreateObjectByNumber
5636 (dev, tags.extraParentObjectId,
5637 YAFFS_OBJECT_TYPE_DIRECTORY);
5638 fileSize = tags.extraFileLength;
5639 isShrink = tags.extraIsShrinkHeader;
5640 equivalentObjectId = tags.extraEquivalentObjectId;
5646 /* directory stuff...
5650 if (parent->variantType ==
5651 YAFFS_OBJECT_TYPE_UNKNOWN) {
5652 /* Set up as a directory */
5653 parent->variantType =
5654 YAFFS_OBJECT_TYPE_DIRECTORY;
5655 INIT_LIST_HEAD(&parent->variant.
5658 } else if (parent->variantType !=
5659 YAFFS_OBJECT_TYPE_DIRECTORY)
5661 /* Hoosterman, another problem....
5662 * We're trying to use a non-directory as a directory
5665 T(YAFFS_TRACE_ERROR,
5667 ("yaffs tragedy: attempting to use non-directory as"
5668 " a directory in scan. Put in lost+found."
5670 parent = dev->lostNFoundDir;
5673 yaffs_AddObjectToDirectory(parent, in);
5675 itsUnlinked = (parent == dev->deletedDir) ||
5676 (parent == dev->unlinkedDir);
5679 /* Mark the block as having a shrinkHeader */
5680 bi->hasShrinkHeader = 1;
5683 /* Note re hardlinks.
5684 * Since we might scan a hardlink before its equivalent object is scanned
5685 * we put them all in a list.
5686 * After scanning is complete, we should have all the objects, so we run
5687 * through this list and fix up all the chains.
5690 switch (in->variantType) {
5691 case YAFFS_OBJECT_TYPE_UNKNOWN:
5692 /* Todo got a problem */
5694 case YAFFS_OBJECT_TYPE_FILE:
5696 if (in->variant.fileVariant.
5697 scannedFileSize < fileSize) {
5698 /* This covers the case where the file size is greater
5699 * than where the data is
5700 * This will happen if the file is resized to be larger
5701 * than its current data extents.
5703 in->variant.fileVariant.fileSize = fileSize;
5704 in->variant.fileVariant.scannedFileSize =
5705 in->variant.fileVariant.fileSize;
5709 in->variant.fileVariant.shrinkSize > fileSize) {
5710 in->variant.fileVariant.shrinkSize = fileSize;
5714 case YAFFS_OBJECT_TYPE_HARDLINK:
5716 in->variant.hardLinkVariant.equivalentObjectId =
5718 in->hardLinks.next =
5719 (struct list_head *) hardList;
5723 case YAFFS_OBJECT_TYPE_DIRECTORY:
5726 case YAFFS_OBJECT_TYPE_SPECIAL:
5729 case YAFFS_OBJECT_TYPE_SYMLINK:
5731 in->variant.symLinkVariant.alias =
5732 yaffs_CloneString(oh->
5741 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5742 /* If we got this far while scanning, then the block is fully allocated. */
5743 state = YAFFS_BLOCK_STATE_FULL;
5746 bi->blockState = state;
5748 /* Now let's see if it was dirty */
5749 if (bi->pagesInUse == 0 &&
5750 !bi->hasShrinkHeader &&
5751 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5752 yaffs_BlockBecameDirty(dev, blk);
5758 YFREE_ALT(blockIndex);
5762 /* Ok, we've done all the scanning.
5763 * Fix up the hard link chains.
5764 * We should now have scanned all the objects, now it's time to add these
5767 yaffs_HardlinkFixup(dev,hardList);
5771 * Sort out state of unlinked and deleted objects.
5774 struct list_head *i;
5775 struct list_head *n;
5779 /* Soft delete all the unlinked files */
5780 list_for_each_safe(i, n,
5781 &dev->unlinkedDir->variant.directoryVariant.
5784 l = list_entry(i, yaffs_Object, siblings);
5785 yaffs_DestroyObject(l);
5789 /* Soft delete all the deletedDir files */
5790 list_for_each_safe(i, n,
5791 &dev->deletedDir->variant.directoryVariant.
5794 l = list_entry(i, yaffs_Object, siblings);
5795 yaffs_DestroyObject(l);
5801 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5803 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5808 /*------------------------------ Directory Functions ----------------------------- */
5810 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5812 yaffs_Device *dev = obj->myDev;
5814 if(dev && dev->removeObjectCallback)
5815 dev->removeObjectCallback(obj);
5817 list_del_init(&obj->siblings);
5822 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5827 T(YAFFS_TRACE_ALWAYS,
5829 ("tragedy: Trying to add an object to a null pointer directory"
5833 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5834 T(YAFFS_TRACE_ALWAYS,
5836 ("tragedy: Trying to add an object to a non-directory"
5841 if (obj->siblings.prev == NULL) {
5842 /* Not initialised */
5843 INIT_LIST_HEAD(&obj->siblings);
5845 } else if (!list_empty(&obj->siblings)) {
5846 /* If it is holed up somewhere else, un hook it */
5847 yaffs_RemoveObjectFromDirectory(obj);
5850 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5851 obj->parent = directory;
5853 if (directory == obj->myDev->unlinkedDir
5854 || directory == obj->myDev->deletedDir) {
5856 obj->myDev->nUnlinkedFiles++;
5857 obj->renameAllowed = 0;
5861 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5866 struct list_head *i;
5867 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5876 T(YAFFS_TRACE_ALWAYS,
5878 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5882 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5883 T(YAFFS_TRACE_ALWAYS,
5885 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5889 sum = yaffs_CalcNameSum(name);
5891 list_for_each(i, &directory->variant.directoryVariant.children) {
5893 l = list_entry(i, yaffs_Object, siblings);
5895 yaffs_CheckObjectDetailsLoaded(l);
5897 /* Special case for lost-n-found */
5898 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5899 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5902 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5904 /* LostnFound cunk called Objxxx
5907 yaffs_GetObjectName(l, buffer,
5908 YAFFS_MAX_NAME_LENGTH);
5909 if (yaffs_strcmp(name, buffer) == 0) {
5922 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5923 int (*fn) (yaffs_Object *))
5925 struct list_head *i;
5929 T(YAFFS_TRACE_ALWAYS,
5931 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5935 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5936 T(YAFFS_TRACE_ALWAYS,
5938 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5942 list_for_each(i, &theDir->variant.directoryVariant.children) {
5944 l = list_entry(i, yaffs_Object, siblings);
5956 /* GetEquivalentObject dereferences any hard links to get to the
5960 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5962 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5963 /* We want the object id of the equivalent object, not this one */
5964 obj = obj->variant.hardLinkVariant.equivalentObject;
5970 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5972 memset(name, 0, buffSize * sizeof(YCHAR));
5974 yaffs_CheckObjectDetailsLoaded(obj);
5976 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5977 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5978 } else if (obj->chunkId <= 0) {
5980 /* make up a name */
5981 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5983 yaffs_strncpy(name, locName, buffSize - 1);
5986 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5987 else if (obj->shortName[0]) {
5988 yaffs_strcpy(name, obj->shortName);
5993 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5995 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5997 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
5999 if (obj->chunkId >= 0) {
6000 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6001 obj->chunkId, buffer,
6004 yaffs_strncpy(name, oh->name, buffSize - 1);
6006 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6009 return yaffs_strlen(name);
6012 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6015 /* Dereference any hard linking */
6016 obj = yaffs_GetEquivalentObject(obj);
6018 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6019 return obj->variant.fileVariant.fileSize;
6021 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6022 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6024 /* Only a directory should drop through to here */
6025 return obj->myDev->nDataBytesPerChunk;
6029 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6032 struct list_head *i;
6034 if (!obj->unlinked) {
6035 count++; /* the object itself */
6037 list_for_each(i, &obj->hardLinks) {
6038 count++; /* add the hard links; */
6044 int yaffs_GetObjectInode(yaffs_Object * obj)
6046 obj = yaffs_GetEquivalentObject(obj);
6048 return obj->objectId;
6051 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6053 obj = yaffs_GetEquivalentObject(obj);
6055 switch (obj->variantType) {
6056 case YAFFS_OBJECT_TYPE_FILE:
6059 case YAFFS_OBJECT_TYPE_DIRECTORY:
6062 case YAFFS_OBJECT_TYPE_SYMLINK:
6065 case YAFFS_OBJECT_TYPE_HARDLINK:
6068 case YAFFS_OBJECT_TYPE_SPECIAL:
6069 if (S_ISFIFO(obj->yst_mode))
6071 if (S_ISCHR(obj->yst_mode))
6073 if (S_ISBLK(obj->yst_mode))
6075 if (S_ISSOCK(obj->yst_mode))
6083 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6085 obj = yaffs_GetEquivalentObject(obj);
6086 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6087 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6089 return yaffs_CloneString(_Y(""));
6093 #ifndef CONFIG_YAFFS_WINCE
6095 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6097 unsigned int valid = attr->ia_valid;
6099 if (valid & ATTR_MODE)
6100 obj->yst_mode = attr->ia_mode;
6101 if (valid & ATTR_UID)
6102 obj->yst_uid = attr->ia_uid;
6103 if (valid & ATTR_GID)
6104 obj->yst_gid = attr->ia_gid;
6106 if (valid & ATTR_ATIME)
6107 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6108 if (valid & ATTR_CTIME)
6109 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6110 if (valid & ATTR_MTIME)
6111 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6113 if (valid & ATTR_SIZE)
6114 yaffs_ResizeFile(obj, attr->ia_size);
6116 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6121 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6123 unsigned int valid = 0;
6125 attr->ia_mode = obj->yst_mode;
6127 attr->ia_uid = obj->yst_uid;
6129 attr->ia_gid = obj->yst_gid;
6132 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6133 valid |= ATTR_ATIME;
6134 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6135 valid |= ATTR_CTIME;
6136 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6137 valid |= ATTR_MTIME;
6139 attr->ia_size = yaffs_GetFileSize(obj);
6142 attr->ia_valid = valid;
6151 int yaffs_DumpObject(yaffs_Object * obj)
6155 yaffs_GetObjectName(obj, name, 256);
6157 T(YAFFS_TRACE_ALWAYS,
6159 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6160 " chunk %d type %d size %d\n"
6161 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6162 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6163 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6169 /*---------------------------- Initialisation code -------------------------------------- */
6171 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6174 /* Common functions, gotta have */
6175 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6178 #ifdef CONFIG_YAFFS_YAFFS2
6180 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6181 if (dev->writeChunkWithTagsToNAND &&
6182 dev->readChunkWithTagsFromNAND &&
6183 !dev->writeChunkToNAND &&
6184 !dev->readChunkFromNAND &&
6185 dev->markNANDBlockBad && dev->queryNANDBlock)
6189 /* Can use the "spare" style interface for yaffs1 */
6190 if (!dev->isYaffs2 &&
6191 !dev->writeChunkWithTagsToNAND &&
6192 !dev->readChunkWithTagsFromNAND &&
6193 dev->writeChunkToNAND &&
6194 dev->readChunkFromNAND &&
6195 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6202 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6204 /* Initialise the unlinked, deleted, root and lost and found directories */
6206 dev->lostNFoundDir = dev->rootDir = NULL;
6207 dev->unlinkedDir = dev->deletedDir = NULL;
6210 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6212 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6215 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6216 YAFFS_ROOT_MODE | S_IFDIR);
6217 dev->lostNFoundDir =
6218 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6219 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6220 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6223 int yaffs_GutsInitialise(yaffs_Device * dev)
6228 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6230 /* Check stuff that must be set */
6233 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6237 dev->internalStartBlock = dev->startBlock;
6238 dev->internalEndBlock = dev->endBlock;
6239 dev->blockOffset = 0;
6240 dev->chunkOffset = 0;
6241 dev->nFreeChunks = 0;
6243 if (dev->startBlock == 0) {
6244 dev->internalStartBlock = dev->startBlock + 1;
6245 dev->internalEndBlock = dev->endBlock + 1;
6246 dev->blockOffset = 1;
6247 dev->chunkOffset = dev->nChunksPerBlock;
6250 /* Check geometry parameters. */
6252 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
6253 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
6254 dev->nChunksPerBlock < 2 ||
6255 dev->nReservedBlocks < 2 ||
6256 dev->internalStartBlock <= 0 ||
6257 dev->internalEndBlock <= 0 ||
6258 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6260 T(YAFFS_TRACE_ALWAYS,
6262 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6263 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6267 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6268 T(YAFFS_TRACE_ALWAYS,
6269 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6273 /* Got the right mix of functions? */
6274 if (!yaffs_CheckDevFunctions(dev)) {
6275 /* Function missing */
6276 T(YAFFS_TRACE_ALWAYS,
6278 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6283 /* This is really a compilation check. */
6284 if (!yaffs_CheckStructures()) {
6285 T(YAFFS_TRACE_ALWAYS,
6286 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6290 if (dev->isMounted) {
6291 T(YAFFS_TRACE_ALWAYS,
6292 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6296 /* Finished with most checks. One or two more checks happen later on too. */
6302 /* OK now calculate a few things for the device */
6305 * Calculate all the chunk size manipulation numbers:
6307 /* Start off assuming it is a power of 2 */
6308 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
6309 dev->chunkMask = (1<<dev->chunkShift) - 1;
6311 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
6312 /* Yes it is a power of 2, disable crumbs */
6314 dev->crumbShift = 0;
6315 dev->crumbsPerChunk = 0;
6317 /* Not a power of 2, use crumbs instead */
6318 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
6319 dev->crumbMask = (1<<dev->crumbShift)-1;
6320 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
6321 dev->chunkShift = 0;
6327 * Calculate chunkGroupBits.
6328 * We need to find the next power of 2 > than internalEndBlock
6331 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6335 /* Set up tnode width if wide tnodes are enabled. */
6336 if(!dev->wideTnodesDisabled){
6337 /* bits must be even so that we end up with 32-bit words */
6341 dev->tnodeWidth = 16;
6343 dev->tnodeWidth = bits;
6346 dev->tnodeWidth = 16;
6348 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6350 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6351 * so if the bitwidth of the
6352 * chunk range we're using is greater than 16 we need
6353 * to figure out chunk shift and chunkGroupSize
6356 if (bits <= dev->tnodeWidth)
6357 dev->chunkGroupBits = 0;
6359 dev->chunkGroupBits = bits - dev->tnodeWidth;
6362 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6364 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6365 /* We have a problem because the soft delete won't work if
6366 * the chunk group size > chunks per block.
6367 * This can be remedied by using larger "virtual blocks".
6369 T(YAFFS_TRACE_ALWAYS,
6370 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6375 /* OK, we've finished verifying the device, lets continue with initialisation */
6377 /* More device initialisation */
6378 dev->garbageCollections = 0;
6379 dev->passiveGarbageCollections = 0;
6380 dev->currentDirtyChecker = 0;
6381 dev->bufferedBlock = -1;
6382 dev->doingBufferedBlockRewrite = 0;
6383 dev->nDeletedFiles = 0;
6384 dev->nBackgroundDeletions = 0;
6385 dev->nUnlinkedFiles = 0;
6387 dev->eccUnfixed = 0;
6388 dev->tagsEccFixed = 0;
6389 dev->tagsEccUnfixed = 0;
6390 dev->nErasureFailures = 0;
6391 dev->nErasedBlocks = 0;
6393 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
6395 /* Initialise temporary buffers and caches. */
6398 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6399 dev->tempBuffer[i].line = 0; /* not in use */
6400 dev->tempBuffer[i].buffer =
6401 YMALLOC_DMA(dev->nDataBytesPerChunk);
6405 if (dev->nShortOpCaches > 0) {
6408 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6409 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6413 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6415 for (i = 0; i < dev->nShortOpCaches; i++) {
6416 dev->srCache[i].object = NULL;
6417 dev->srCache[i].lastUse = 0;
6418 dev->srCache[i].dirty = 0;
6419 dev->srCache[i].data = YMALLOC_DMA(dev->nDataBytesPerChunk);
6426 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6428 if (dev->isYaffs2) {
6429 dev->useHeaderFileSize = 1;
6432 yaffs_InitialiseBlocks(dev);
6433 yaffs_InitialiseTnodes(dev);
6434 yaffs_InitialiseObjects(dev);
6436 yaffs_CreateInitialDirectories(dev);
6439 /* Now scan the flash. */
6440 if (dev->isYaffs2) {
6441 if(yaffs_CheckpointRestore(dev)) {
6442 T(YAFFS_TRACE_ALWAYS,
6443 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6446 /* Clean up the mess caused by an aborted checkpoint load
6447 * and scan backwards.
6449 yaffs_DeinitialiseBlocks(dev);
6450 yaffs_DeinitialiseTnodes(dev);
6451 yaffs_DeinitialiseObjects(dev);
6452 yaffs_InitialiseBlocks(dev);
6453 yaffs_InitialiseTnodes(dev);
6454 yaffs_InitialiseObjects(dev);
6455 yaffs_CreateInitialDirectories(dev);
6457 yaffs_ScanBackwards(dev);
6462 /* Zero out stats */
6463 dev->nPageReads = 0;
6464 dev->nPageWrites = 0;
6465 dev->nBlockErasures = 0;
6467 dev->nRetriedWrites = 0;
6469 dev->nRetiredBlocks = 0;
6471 yaffs_VerifyFreeChunks(dev);
6473 T(YAFFS_TRACE_TRACING,
6474 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6479 void yaffs_Deinitialise(yaffs_Device * dev)
6481 if (dev->isMounted) {
6484 yaffs_DeinitialiseBlocks(dev);
6485 yaffs_DeinitialiseTnodes(dev);
6486 yaffs_DeinitialiseObjects(dev);
6487 if (dev->nShortOpCaches > 0) {
6489 for (i = 0; i < dev->nShortOpCaches; i++) {
6490 YFREE(dev->srCache[i].data);
6493 YFREE(dev->srCache);
6496 YFREE(dev->gcCleanupList);
6498 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6499 YFREE(dev->tempBuffer[i].buffer);
6507 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6512 yaffs_BlockInfo *blk;
6514 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6516 blk = yaffs_GetBlockInfo(dev, b);
6518 switch (blk->blockState) {
6519 case YAFFS_BLOCK_STATE_EMPTY:
6520 case YAFFS_BLOCK_STATE_ALLOCATING:
6521 case YAFFS_BLOCK_STATE_COLLECTING:
6522 case YAFFS_BLOCK_STATE_FULL:
6524 (dev->nChunksPerBlock - blk->pagesInUse +
6525 blk->softDeletions);
6536 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6538 /* This is what we report to the outside world */
6541 int nDirtyCacheChunks;
6542 int blocksForCheckpoint;
6545 nFree = dev->nFreeChunks;
6547 nFree = yaffs_CountFreeChunks(dev);
6550 nFree += dev->nDeletedFiles;
6552 /* Now count the number of dirty chunks in the cache and subtract those */
6556 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6557 if (dev->srCache[i].dirty)
6558 nDirtyCacheChunks++;
6562 nFree -= nDirtyCacheChunks;
6564 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6566 /* Now we figure out how much to reserve for the checkpoint and report that... */
6567 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6568 if(blocksForCheckpoint < 0)
6569 blocksForCheckpoint = 0;
6571 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6580 static int yaffs_freeVerificationFailures;
6582 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6584 int counted = yaffs_CountFreeChunks(dev);
6586 int difference = dev->nFreeChunks - counted;
6589 T(YAFFS_TRACE_ALWAYS,
6590 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6591 dev->nFreeChunks, counted, difference));
6592 yaffs_freeVerificationFailures++;
6596 /*---------------------------------------- YAFFS test code ----------------------*/
6598 #define yaffs_CheckStruct(structure,syze, name) \
6599 if(sizeof(structure) != syze) \
6601 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6602 name,syze,sizeof(structure))); \
6603 return YAFFS_FAIL; \
6606 static int yaffs_CheckStructures(void)
6608 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6609 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6610 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6611 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6612 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6614 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")