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.37 2006-09-21 08:13:59 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"
35 #ifdef CONFIG_YAFFS_WINCE
36 void yfsd_LockYAFFS(BOOL fsLockOnly);
37 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
40 #define YAFFS_PASSIVE_GC_CHUNKS 2
42 #include "yaffs_ecc.h"
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
48 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
50 const yaffs_ExtendedTags * tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
52 const yaffs_ExtendedTags * tags);
54 /* Other local prototypes */
55 static int yaffs_UnlinkObject( yaffs_Object *obj);
56 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62 yaffs_ExtendedTags * tags,
64 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
65 int chunkInNAND, int inScan);
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
68 yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
72 int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
76 int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
82 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
85 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
88 static int yaffs_UnlinkWorker(yaffs_Object * obj);
89 static void yaffs_DestroyObject(yaffs_Object * obj);
91 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
94 loff_t yaffs_GetFileSize(yaffs_Object * obj);
96 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
98 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
100 #ifdef YAFFS_PARANOID
101 static int yaffs_CheckFileSanity(yaffs_Object * in);
103 #define yaffs_CheckFileSanity(in)
106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
107 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
109 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
112 * Temporary buffer manipulations.
115 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
118 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
119 if (dev->tempBuffer[i].line == 0) {
120 dev->tempBuffer[i].line = lineNo;
121 if ((i + 1) > dev->maxTemp) {
122 dev->maxTemp = i + 1;
123 for (j = 0; j <= i; j++)
124 dev->tempBuffer[j].maxLine =
125 dev->tempBuffer[j].line;
128 return dev->tempBuffer[i].buffer;
132 T(YAFFS_TRACE_BUFFERS,
133 (TSTR("Out of temp buffers at line %d, other held by lines:"),
135 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
136 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
138 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
141 * If we got here then we have to allocate an unmanaged one
145 dev->unmanagedTempAllocations++;
146 return YMALLOC(dev->nBytesPerChunk);
150 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
154 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
155 if (dev->tempBuffer[i].buffer == buffer) {
156 dev->tempBuffer[i].line = 0;
162 /* assume it is an unmanaged one. */
163 T(YAFFS_TRACE_BUFFERS,
164 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
167 dev->unmanagedTempDeallocations++;
173 * Determine if we have a managed buffer.
175 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
178 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
179 if (dev->tempBuffer[i].buffer == buffer)
184 for (i = 0; i < dev->nShortOpCaches; i++) {
185 if( dev->srCache[i].data == buffer )
190 if (buffer == dev->checkpointBuffer)
193 T(YAFFS_TRACE_ALWAYS,
194 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
199 * Chunk bitmap manipulations
202 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
204 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
206 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
210 return dev->chunkBits +
211 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
214 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
216 __u8 *blkBits = yaffs_BlockBits(dev, blk);
218 memset(blkBits, 0, dev->chunkBitmapStride);
221 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
223 __u8 *blkBits = yaffs_BlockBits(dev, blk);
225 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
228 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
230 __u8 *blkBits = yaffs_BlockBits(dev, blk);
232 blkBits[chunk / 8] |= (1 << (chunk & 7));
235 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
237 __u8 *blkBits = yaffs_BlockBits(dev, blk);
238 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
241 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
243 __u8 *blkBits = yaffs_BlockBits(dev, blk);
245 for (i = 0; i < dev->chunkBitmapStride; i++) {
254 * Simple hash function. Needs to have a reasonable spread
257 static Y_INLINE int yaffs_HashFunction(int n)
260 return (n % YAFFS_NOBJECT_BUCKETS);
264 * Access functions to useful fake objects
267 yaffs_Object *yaffs_Root(yaffs_Device * dev)
272 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
274 return dev->lostNFoundDir;
279 * Erased NAND checking functions
282 int yaffs_CheckFF(__u8 * buffer, int nBytes)
284 /* Horrible, slow implementation */
293 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
297 int retval = YAFFS_OK;
298 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
299 yaffs_ExtendedTags tags;
301 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
303 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
307 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
308 T(YAFFS_TRACE_NANDACCESS,
309 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
313 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
319 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
321 yaffs_ExtendedTags * tags,
331 yaffs_InvalidateCheckpoint(dev);
334 chunk = yaffs_AllocateChunk(dev, useReserve,&bi);
337 /* First check this chunk is erased, if it needs checking.
338 * The checking policy (unless forced always on) is as follows:
339 * Check the first page we try to write in a block.
340 * - If the check passes then we don't need to check any more.
341 * - If the check fails, we check again...
342 * If the block has been erased, we don't need to check.
344 * However, if the block has been prioritised for gc, then
345 * we think there might be something odd about this block
346 * and should continue doing erased checks.
349 * We should only ever see chunks that have not been erased
350 * if there was a partially written chunk due to power loss
351 * This checking policy should catch that case with very
352 * few checks and thus save a lot of checks that are most likely not
356 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
357 bi->skipErasedCheck = 1;
359 if(!bi->skipErasedCheck){
360 erasedOk = yaffs_CheckChunkErased(dev, chunk);
361 if(erasedOk && !bi->gcPrioritise)
362 bi->skipErasedCheck = 1;
368 ("**>> yaffs chunk %d was not erased"
372 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
380 * Copy the data into the robustification buffer.
381 * NB We do this at the end to prevent duplicates in the case of a write error.
384 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
387 /* The erased check or write failed */
388 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
392 } while (chunk >= 0 && !writeOk);
396 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
398 dev->nRetriedWrites += (attempts - 1);
405 * Block retiring for handling a broken block.
408 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
411 yaffs_InvalidateCheckpoint(dev);
413 yaffs_MarkBlockBad(dev, blockInNAND);
415 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
416 YAFFS_BLOCK_STATE_DEAD;
418 dev->nRetiredBlocks++;
422 * Functions for robustisizing TODO
426 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
428 const yaffs_ExtendedTags * tags)
432 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
433 const yaffs_ExtendedTags * tags)
437 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
440 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
441 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
442 bi->gcPrioritise = 1;
445 /* Was an actual write failure, so mark the block for retirement */
447 bi->needsRetiring = 1;
450 /* Delete the chunk */
451 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
455 /*---------------- Name handling functions ------------*/
457 static __u16 yaffs_CalcNameSum(const YCHAR * name)
462 YUCHAR *bname = (YUCHAR *) name;
464 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
466 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
467 sum += yaffs_toupper(*bname) * i;
478 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
480 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
481 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
482 yaffs_strcpy(obj->shortName, name);
484 obj->shortName[0] = _Y('\0');
487 obj->sum = yaffs_CalcNameSum(name);
490 /*-------------------- TNODES -------------------
492 * List of spare tnodes
493 * The list is hooked together using the first pointer
497 /* yaffs_CreateTnodes creates a bunch more tnodes and
498 * adds them to the tnode free list.
499 * Don't use this function directly
502 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
506 yaffs_Tnode *newTnodes;
510 yaffs_TnodeList *tnl;
515 /* Calculate the tnode size in bytes for variable width tnode support.
516 * Must be a multiple of 32-bits */
517 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
519 /* make these things */
521 newTnodes = YMALLOC(nTnodes * tnodeSize);
522 mem = (__u8 *)newTnodes;
526 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
530 /* Hook them into the free list */
532 for (i = 0; i < nTnodes - 1; i++) {
533 newTnodes[i].internal[0] = &newTnodes[i + 1];
534 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
535 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
539 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
540 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
541 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
543 dev->freeTnodes = newTnodes;
545 /* New hookup for wide tnodes */
546 for(i = 0; i < nTnodes -1; i++) {
547 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
548 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
549 curr->internal[0] = next;
552 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
553 curr->internal[0] = dev->freeTnodes;
554 dev->freeTnodes = (yaffs_Tnode *)mem;
559 dev->nFreeTnodes += nTnodes;
560 dev->nTnodesCreated += nTnodes;
562 /* Now add this bunch of tnodes to a list for freeing up.
563 * NB If we can't add this to the management list it isn't fatal
564 * but it just means we can't free this bunch of tnodes later.
567 tnl = YMALLOC(sizeof(yaffs_TnodeList));
571 ("yaffs: Could not add tnodes to management list" TENDSTR)));
574 tnl->tnodes = newTnodes;
575 tnl->next = dev->allocatedTnodeList;
576 dev->allocatedTnodeList = tnl;
579 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
584 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
586 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
588 yaffs_Tnode *tn = NULL;
590 /* If there are none left make more */
591 if (!dev->freeTnodes) {
592 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
595 if (dev->freeTnodes) {
596 tn = dev->freeTnodes;
597 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
598 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
599 /* Hoosterman, this thing looks like it isn't in the list */
600 T(YAFFS_TRACE_ALWAYS,
601 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
604 dev->freeTnodes = dev->freeTnodes->internal[0];
611 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
613 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
616 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
621 /* FreeTnode frees up a tnode and puts it back on the free list */
622 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
625 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
626 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
627 /* Hoosterman, this thing looks like it is already in the list */
628 T(YAFFS_TRACE_ALWAYS,
629 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
631 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
633 tn->internal[0] = dev->freeTnodes;
634 dev->freeTnodes = tn;
639 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
641 /* Free the list of allocated tnodes */
642 yaffs_TnodeList *tmp;
644 while (dev->allocatedTnodeList) {
645 tmp = dev->allocatedTnodeList->next;
647 YFREE(dev->allocatedTnodeList->tnodes);
648 YFREE(dev->allocatedTnodeList);
649 dev->allocatedTnodeList = tmp;
653 dev->freeTnodes = NULL;
654 dev->nFreeTnodes = 0;
657 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
659 dev->allocatedTnodeList = NULL;
660 dev->freeTnodes = NULL;
661 dev->nFreeTnodes = 0;
662 dev->nTnodesCreated = 0;
667 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
669 __u32 *map = (__u32 *)tn;
675 pos &= YAFFS_TNODES_LEVEL0_MASK;
676 val >>= dev->chunkGroupBits;
678 bitInMap = pos * dev->tnodeWidth;
679 wordInMap = bitInMap /32;
680 bitInWord = bitInMap & (32 -1);
682 mask = dev->tnodeMask << bitInWord;
684 map[wordInMap] &= ~mask;
685 map[wordInMap] |= (mask & (val << bitInWord));
687 if(dev->tnodeWidth > (32-bitInWord)) {
688 bitInWord = (32 - bitInWord);
690 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
691 map[wordInMap] &= ~mask;
692 map[wordInMap] |= (mask & (val >> bitInWord));
696 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
698 __u32 *map = (__u32 *)tn;
704 pos &= YAFFS_TNODES_LEVEL0_MASK;
706 bitInMap = pos * dev->tnodeWidth;
707 wordInMap = bitInMap /32;
708 bitInWord = bitInMap & (32 -1);
710 val = map[wordInMap] >> bitInWord;
712 if(dev->tnodeWidth > (32-bitInWord)) {
713 bitInWord = (32 - bitInWord);
715 val |= (map[wordInMap] << bitInWord);
718 val &= dev->tnodeMask;
719 val <<= dev->chunkGroupBits;
724 /* ------------------- End of individual tnode manipulation -----------------*/
726 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
727 * The look up tree is represented by the top tnode and the number of topLevel
728 * in the tree. 0 means only the level 0 tnode is in the tree.
731 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
732 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
733 yaffs_FileStructure * fStruct,
737 yaffs_Tnode *tn = fStruct->top;
739 int requiredTallness;
740 int level = fStruct->topLevel;
742 /* Check sane level and chunk Id */
743 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
747 if (chunkId > YAFFS_MAX_CHUNK_ID) {
751 /* First check we're tall enough (ie enough topLevel) */
753 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
754 requiredTallness = 0;
756 i >>= YAFFS_TNODES_INTERNAL_BITS;
760 if (requiredTallness > fStruct->topLevel) {
761 /* Not tall enough, so we can't find it, return NULL. */
765 /* Traverse down to level 0 */
766 while (level > 0 && tn) {
769 ( YAFFS_TNODES_LEVEL0_BITS +
771 YAFFS_TNODES_INTERNAL_BITS)
773 YAFFS_TNODES_INTERNAL_MASK];
781 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
782 * This happens in two steps:
783 * 1. If the tree isn't tall enough, then make it taller.
784 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
786 * Used when modifying the tree.
788 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
789 * be plugged into the ttree.
792 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
793 yaffs_FileStructure * fStruct,
795 yaffs_Tnode *passedTn)
798 int requiredTallness;
806 /* Check sane level and page Id */
807 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
811 if (chunkId > YAFFS_MAX_CHUNK_ID) {
815 /* First check we're tall enough (ie enough topLevel) */
817 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
818 requiredTallness = 0;
820 x >>= YAFFS_TNODES_INTERNAL_BITS;
825 if (requiredTallness > fStruct->topLevel) {
826 /* Not tall enough,gotta make the tree taller */
827 for (i = fStruct->topLevel; i < requiredTallness; i++) {
829 tn = yaffs_GetTnode(dev);
832 tn->internal[0] = fStruct->top;
836 (TSTR("yaffs: no more tnodes" TENDSTR)));
840 fStruct->topLevel = requiredTallness;
843 /* Traverse down to level 0, adding anything we need */
845 l = fStruct->topLevel;
849 while (l > 0 && tn) {
851 ( YAFFS_TNODES_LEVEL0_BITS +
852 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
853 YAFFS_TNODES_INTERNAL_MASK;
856 if((l>1) && !tn->internal[x]){
857 /* Add missing non-level-zero tnode */
858 tn->internal[x] = yaffs_GetTnode(dev);
861 /* Looking from level 1 at level 0 */
863 /* If we already have one, then release it.*/
865 yaffs_FreeTnode(dev,tn->internal[x]);
866 tn->internal[x] = passedTn;
868 } else if(!tn->internal[x]) {
869 /* Don't have one, none passed in */
870 tn->internal[x] = yaffs_GetTnode(dev);
874 tn = tn->internal[x];
880 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
881 yaffs_FreeTnode(dev,passedTn);
888 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
889 yaffs_ExtendedTags * tags, int objectId,
894 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
895 if (yaffs_CheckChunkBit
896 (dev, theChunk / dev->nChunksPerBlock,
897 theChunk % dev->nChunksPerBlock)) {
898 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
900 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
912 /* DeleteWorker scans backwards through the tnode tree and deletes all the
913 * chunks and tnodes in the file
914 * Returns 1 if the tree was deleted.
915 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
918 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
919 int chunkOffset, int *limit)
924 yaffs_ExtendedTags tags;
926 yaffs_Device *dev = in->myDev;
933 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
935 if (tn->internal[i]) {
936 if (limit && (*limit) < 0) {
940 yaffs_DeleteWorker(in,
948 YAFFS_TNODES_INTERNAL_BITS)
956 tn->internal[i] = NULL;
961 return (allDone) ? 1 : 0;
962 } else if (level == 0) {
965 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
967 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
972 YAFFS_TNODES_LEVEL0_BITS) + i;
975 yaffs_FindChunkInGroup(dev,
981 if (foundChunk > 0) {
982 yaffs_DeleteChunk(dev,
995 yaffs_PutLevel0Tnode(dev,tn,i,0);
999 return (i < 0) ? 1 : 0;
1009 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1012 yaffs_BlockInfo *theBlock;
1014 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1016 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1018 theBlock->softDeletions++;
1023 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1024 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1026 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1029 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1030 __u32 level, int chunkOffset)
1035 yaffs_Device *dev = in->myDev;
1040 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1042 if (tn->internal[i]) {
1044 yaffs_SoftDeleteWorker(in,
1050 YAFFS_TNODES_INTERNAL_BITS)
1053 yaffs_FreeTnode(dev,
1056 tn->internal[i] = NULL;
1058 /* Hoosterman... how could this happen? */
1062 return (allDone) ? 1 : 0;
1063 } else if (level == 0) {
1065 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1066 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1068 /* Note this does not find the real chunk, only the chunk group.
1069 * We make an assumption that a chunk group is not larger than
1072 yaffs_SoftDeleteChunk(dev, theChunk);
1073 yaffs_PutLevel0Tnode(dev,tn,i,0);
1087 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1090 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1091 if (obj->nDataChunks <= 0) {
1092 /* Empty file with no duplicate object headers, just delete it immediately */
1093 yaffs_FreeTnode(obj->myDev,
1094 obj->variant.fileVariant.top);
1095 obj->variant.fileVariant.top = NULL;
1096 T(YAFFS_TRACE_TRACING,
1097 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1099 yaffs_DoGenericObjectDeletion(obj);
1101 yaffs_SoftDeleteWorker(obj,
1102 obj->variant.fileVariant.top,
1103 obj->variant.fileVariant.
1105 obj->softDeleted = 1;
1110 /* Pruning removes any part of the file structure tree that is beyond the
1111 * bounds of the file (ie that does not point to chunks).
1113 * A file should only get pruned when its size is reduced.
1115 * Before pruning, the chunks must be pulled from the tree and the
1116 * level 0 tnode entries must be zeroed out.
1117 * Could also use this for file deletion, but that's probably better handled
1118 * by a special case.
1121 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1122 __u32 level, int del0)
1130 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1131 if (tn->internal[i] && level > 0) {
1133 yaffs_PruneWorker(dev, tn->internal[i],
1135 (i == 0) ? del0 : 1);
1138 if (tn->internal[i]) {
1143 if (hasData == 0 && del0) {
1144 /* Free and return NULL */
1146 yaffs_FreeTnode(dev, tn);
1156 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1157 yaffs_FileStructure * fStruct)
1164 if (fStruct->topLevel > 0) {
1166 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1168 /* Now we have a tree with all the non-zero branches NULL but the height
1169 * is the same as it was.
1170 * Let's see if we can trim internal tnodes to shorten the tree.
1171 * We can do this if only the 0th element in the tnode is in use
1172 * (ie all the non-zero are NULL)
1175 while (fStruct->topLevel && !done) {
1179 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1180 if (tn->internal[i]) {
1186 fStruct->top = tn->internal[0];
1187 fStruct->topLevel--;
1188 yaffs_FreeTnode(dev, tn);
1198 /*-------------------- End of File Structure functions.-------------------*/
1200 /* yaffs_CreateFreeObjects creates a bunch more objects and
1201 * adds them to the object free list.
1203 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1206 yaffs_Object *newObjects;
1207 yaffs_ObjectList *list;
1212 /* make these things */
1213 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1216 T(YAFFS_TRACE_ALLOCATE,
1217 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1221 /* Hook them into the free list */
1222 for (i = 0; i < nObjects - 1; i++) {
1223 newObjects[i].siblings.next =
1224 (struct list_head *)(&newObjects[i + 1]);
1227 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1228 dev->freeObjects = newObjects;
1229 dev->nFreeObjects += nObjects;
1230 dev->nObjectsCreated += nObjects;
1232 /* Now add this bunch of Objects to a list for freeing up. */
1234 list = YMALLOC(sizeof(yaffs_ObjectList));
1236 T(YAFFS_TRACE_ALLOCATE,
1237 (TSTR("Could not add objects to management list" TENDSTR)));
1239 list->objects = newObjects;
1240 list->next = dev->allocatedObjectList;
1241 dev->allocatedObjectList = list;
1248 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1249 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1251 yaffs_Object *tn = NULL;
1253 /* If there are none left make more */
1254 if (!dev->freeObjects) {
1255 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1258 if (dev->freeObjects) {
1259 tn = dev->freeObjects;
1261 (yaffs_Object *) (dev->freeObjects->siblings.next);
1262 dev->nFreeObjects--;
1264 /* Now sweeten it up... */
1266 memset(tn, 0, sizeof(yaffs_Object));
1269 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1270 INIT_LIST_HEAD(&(tn->hardLinks));
1271 INIT_LIST_HEAD(&(tn->hashLink));
1272 INIT_LIST_HEAD(&tn->siblings);
1274 /* Add it to the lost and found directory.
1275 * NB Can't put root or lostNFound in lostNFound so
1276 * check if lostNFound exists first
1278 if (dev->lostNFoundDir) {
1279 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1286 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1291 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1293 obj->fake = 1; /* it is fake so it has no NAND presence... */
1294 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1295 obj->unlinkAllowed = 0; /* ... or unlink it */
1298 obj->yst_mode = mode;
1300 obj->chunkId = 0; /* Not a valid chunk. */
1307 static void yaffs_UnhashObject(yaffs_Object * tn)
1310 yaffs_Device *dev = tn->myDev;
1312 /* If it is still linked into the bucket list, free from the list */
1313 if (!list_empty(&tn->hashLink)) {
1314 list_del_init(&tn->hashLink);
1315 bucket = yaffs_HashFunction(tn->objectId);
1316 dev->objectBucket[bucket].count--;
1321 /* FreeObject frees up a Object and puts it back on the free list */
1322 static void yaffs_FreeObject(yaffs_Object * tn)
1325 yaffs_Device *dev = tn->myDev;
1329 /* We're still hooked up to a cached inode.
1330 * Don't delete now, but mark for later deletion
1332 tn->deferedFree = 1;
1337 yaffs_UnhashObject(tn);
1339 /* Link into the free list. */
1340 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1341 dev->freeObjects = tn;
1342 dev->nFreeObjects++;
1347 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1349 if (obj->deferedFree) {
1350 yaffs_FreeObject(obj);
1356 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1358 /* Free the list of allocated Objects */
1360 yaffs_ObjectList *tmp;
1362 while (dev->allocatedObjectList) {
1363 tmp = dev->allocatedObjectList->next;
1364 YFREE(dev->allocatedObjectList->objects);
1365 YFREE(dev->allocatedObjectList);
1367 dev->allocatedObjectList = tmp;
1370 dev->freeObjects = NULL;
1371 dev->nFreeObjects = 0;
1374 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1378 dev->allocatedObjectList = NULL;
1379 dev->freeObjects = NULL;
1380 dev->nFreeObjects = 0;
1382 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1383 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1384 dev->objectBucket[i].count = 0;
1389 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1394 int lowest = 999999;
1396 /* First let's see if we can find one that's empty. */
1398 for (i = 0; i < 10 && lowest > 0; i++) {
1400 x %= YAFFS_NOBJECT_BUCKETS;
1401 if (dev->objectBucket[x].count < lowest) {
1402 lowest = dev->objectBucket[x].count;
1408 /* If we didn't find an empty list, then try
1409 * looking a bit further for a short one
1412 for (i = 0; i < 10 && lowest > 3; i++) {
1414 x %= YAFFS_NOBJECT_BUCKETS;
1415 if (dev->objectBucket[x].count < lowest) {
1416 lowest = dev->objectBucket[x].count;
1425 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1427 int bucket = yaffs_FindNiceObjectBucket(dev);
1429 /* Now find an object value that has not already been taken
1430 * by scanning the list.
1434 struct list_head *i;
1436 __u32 n = (__u32) bucket;
1438 /* yaffs_CheckObjectHashSanity(); */
1442 n += YAFFS_NOBJECT_BUCKETS;
1443 if (1 || dev->objectBucket[bucket].count > 0) {
1444 list_for_each(i, &dev->objectBucket[bucket].list) {
1445 /* If there is already one in the list */
1447 && list_entry(i, yaffs_Object,
1448 hashLink)->objectId == n) {
1459 static void yaffs_HashObject(yaffs_Object * in)
1461 int bucket = yaffs_HashFunction(in->objectId);
1462 yaffs_Device *dev = in->myDev;
1464 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1465 dev->objectBucket[bucket].count++;
1469 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1471 int bucket = yaffs_HashFunction(number);
1472 struct list_head *i;
1475 list_for_each(i, &dev->objectBucket[bucket].list) {
1476 /* Look if it is in the list */
1478 in = list_entry(i, yaffs_Object, hashLink);
1479 if (in->objectId == number) {
1481 /* Don't tell the VFS about this one if it is defered free */
1482 if (in->deferedFree)
1494 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1495 yaffs_ObjectType type)
1498 yaffs_Object *theObject;
1501 number = yaffs_CreateNewObjectNumber(dev);
1504 theObject = yaffs_AllocateEmptyObject(dev);
1507 theObject->fake = 0;
1508 theObject->renameAllowed = 1;
1509 theObject->unlinkAllowed = 1;
1510 theObject->objectId = number;
1511 yaffs_HashObject(theObject);
1512 theObject->variantType = type;
1513 #ifdef CONFIG_YAFFS_WINCE
1514 yfsd_WinFileTimeNow(theObject->win_atime);
1515 theObject->win_ctime[0] = theObject->win_mtime[0] =
1516 theObject->win_atime[0];
1517 theObject->win_ctime[1] = theObject->win_mtime[1] =
1518 theObject->win_atime[1];
1522 theObject->yst_atime = theObject->yst_mtime =
1523 theObject->yst_ctime = Y_CURRENT_TIME;
1526 case YAFFS_OBJECT_TYPE_FILE:
1527 theObject->variant.fileVariant.fileSize = 0;
1528 theObject->variant.fileVariant.scannedFileSize = 0;
1529 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1530 theObject->variant.fileVariant.topLevel = 0;
1531 theObject->variant.fileVariant.top =
1532 yaffs_GetTnode(dev);
1534 case YAFFS_OBJECT_TYPE_DIRECTORY:
1535 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1538 case YAFFS_OBJECT_TYPE_SYMLINK:
1539 case YAFFS_OBJECT_TYPE_HARDLINK:
1540 case YAFFS_OBJECT_TYPE_SPECIAL:
1541 /* No action required */
1543 case YAFFS_OBJECT_TYPE_UNKNOWN:
1544 /* todo this should not happen */
1552 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1554 yaffs_ObjectType type)
1556 yaffs_Object *theObject = NULL;
1559 theObject = yaffs_FindObjectByNumber(dev, number);
1563 theObject = yaffs_CreateNewObject(dev, number, type);
1571 static YCHAR *yaffs_CloneString(const YCHAR * str)
1573 YCHAR *newStr = NULL;
1576 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1577 yaffs_strcpy(newStr, str);
1585 * Mknod (create) a new object.
1586 * equivalentObject only has meaning for a hard link;
1587 * aliasString only has meaning for a sumlink.
1588 * rdev only has meaning for devices (a subset of special objects)
1591 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1592 yaffs_Object * parent,
1597 yaffs_Object * equivalentObject,
1598 const YCHAR * aliasString, __u32 rdev)
1602 yaffs_Device *dev = parent->myDev;
1604 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1605 if (yaffs_FindObjectByName(parent, name)) {
1609 in = yaffs_CreateNewObject(dev, -1, type);
1614 in->variantType = type;
1616 in->yst_mode = mode;
1618 #ifdef CONFIG_YAFFS_WINCE
1619 yfsd_WinFileTimeNow(in->win_atime);
1620 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1621 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1624 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1626 in->yst_rdev = rdev;
1630 in->nDataChunks = 0;
1632 yaffs_SetObjectName(in, name);
1635 yaffs_AddObjectToDirectory(parent, in);
1637 in->myDev = parent->myDev;
1640 case YAFFS_OBJECT_TYPE_SYMLINK:
1641 in->variant.symLinkVariant.alias =
1642 yaffs_CloneString(aliasString);
1644 case YAFFS_OBJECT_TYPE_HARDLINK:
1645 in->variant.hardLinkVariant.equivalentObject =
1647 in->variant.hardLinkVariant.equivalentObjectId =
1648 equivalentObject->objectId;
1649 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1651 case YAFFS_OBJECT_TYPE_FILE:
1652 case YAFFS_OBJECT_TYPE_DIRECTORY:
1653 case YAFFS_OBJECT_TYPE_SPECIAL:
1654 case YAFFS_OBJECT_TYPE_UNKNOWN:
1659 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1660 /* Could not create the object header, fail the creation */
1661 yaffs_DestroyObject(in);
1670 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1671 __u32 mode, __u32 uid, __u32 gid)
1673 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1674 uid, gid, NULL, NULL, 0);
1677 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1678 __u32 mode, __u32 uid, __u32 gid)
1680 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1681 mode, uid, gid, NULL, NULL, 0);
1684 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1685 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1687 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1688 uid, gid, NULL, NULL, rdev);
1691 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1692 __u32 mode, __u32 uid, __u32 gid,
1693 const YCHAR * alias)
1695 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1696 uid, gid, NULL, alias, 0);
1699 /* yaffs_Link returns the object id of the equivalent object.*/
1700 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1701 yaffs_Object * equivalentObject)
1703 /* Get the real object in case we were fed a hard link as an equivalent object */
1704 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1706 if (yaffs_MknodObject
1707 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1708 equivalentObject, NULL, 0)) {
1709 return equivalentObject;
1716 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1717 const YCHAR * newName, int force, int shadows)
1722 yaffs_Object *existingTarget;
1724 if (newDir == NULL) {
1725 newDir = obj->parent; /* use the old directory */
1728 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1729 T(YAFFS_TRACE_ALWAYS,
1731 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1736 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1737 if (obj->myDev->isYaffs2) {
1738 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1740 unlinkOp = (newDir == obj->myDev->unlinkedDir
1741 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1744 deleteOp = (newDir == obj->myDev->deletedDir);
1746 existingTarget = yaffs_FindObjectByName(newDir, newName);
1748 /* If the object is a file going into the unlinked directory,
1749 * then it is OK to just stuff it in since duplicate names are allowed.
1750 * else only proceed if the new name does not exist and if we're putting
1751 * it into a directory.
1758 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1759 yaffs_SetObjectName(obj, newName);
1762 yaffs_AddObjectToDirectory(newDir, obj);
1767 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1768 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1775 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1776 yaffs_Object * newDir, const YCHAR * newName)
1779 yaffs_Object *existingTarget;
1782 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1783 /* Special case for case insemsitive systems (eg. WinCE).
1784 * While look-up is case insensitive, the name isn't.
1785 * Therefore we might want to change x.txt to X.txt
1787 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1792 obj = yaffs_FindObjectByName(oldDir, oldName);
1793 /* Check new name to long. */
1794 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1795 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1798 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1799 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1803 if (obj && obj->renameAllowed) {
1805 /* Now do the handling for an existing target, if there is one */
1807 existingTarget = yaffs_FindObjectByName(newDir, newName);
1808 if (existingTarget &&
1809 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1810 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1811 /* There is a target that is a non-empty directory, so we fail */
1812 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1813 } else if (existingTarget && existingTarget != obj) {
1814 /* Nuke the target first, using shadowing,
1815 * but only if it isn't the same object
1817 yaffs_ChangeObjectName(obj, newDir, newName, force,
1818 existingTarget->objectId);
1819 yaffs_UnlinkObject(existingTarget);
1822 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1827 /*------------------------- Block Management and Page Allocation ----------------*/
1829 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1831 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1833 dev->allocationBlock = -1; /* force it to get a new one */
1835 /* Todo we're assuming the malloc will pass. */
1836 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1837 if(!dev->blockInfo){
1838 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1839 dev->blockInfoAlt = 1;
1842 dev->blockInfoAlt = 0;
1844 /* Set up dynamic blockinfo stuff. */
1845 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; // round up bytes
1846 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1847 if(!dev->chunkBits){
1848 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1849 dev->chunkBitsAlt = 1;
1852 dev->chunkBitsAlt = 0;
1854 if (dev->blockInfo && dev->chunkBits) {
1855 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1856 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1864 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1866 if(dev->blockInfoAlt)
1867 YFREE_ALT(dev->blockInfo);
1869 YFREE(dev->blockInfo);
1870 dev->blockInfoAlt = 0;
1872 dev->blockInfo = NULL;
1874 if(dev->chunkBitsAlt)
1875 YFREE_ALT(dev->chunkBits);
1877 YFREE(dev->chunkBits);
1878 dev->chunkBitsAlt = 0;
1879 dev->chunkBits = NULL;
1882 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1883 yaffs_BlockInfo * bi)
1890 return 1; /* disqualification only applies to yaffs2. */
1892 if (!bi->hasShrinkHeader)
1893 return 1; /* can gc */
1895 /* Find the oldest dirty sequence number if we don't know it and save it
1896 * so we don't have to keep recomputing it.
1898 if (!dev->oldestDirtySequence) {
1899 seq = dev->sequenceNumber;
1901 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1903 b = yaffs_GetBlockInfo(dev, i);
1904 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1905 (b->pagesInUse - b->softDeletions) <
1906 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1907 seq = b->sequenceNumber;
1910 dev->oldestDirtySequence = seq;
1913 /* Can't do gc of this block if there are any blocks older than this one that have
1916 return (bi->sequenceNumber <= dev->oldestDirtySequence);
1922 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1923 * for garbage collection.
1926 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1930 int b = dev->currentDirtyChecker;
1937 yaffs_BlockInfo *bi;
1938 static int nonAggressiveSkip = 0;
1940 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1942 * else (we're doing a leasurely gc), then we only bother to do this if the
1943 * block has only a few pages in use.
1946 nonAggressiveSkip--;
1948 if (!aggressive && (nonAggressiveSkip > 0)) {
1953 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1957 dev->internalEndBlock - dev->internalStartBlock + 1;
1960 dev->internalEndBlock - dev->internalStartBlock + 1;
1961 iterations = iterations / 16;
1962 if (iterations > 200) {
1967 for (i = 0, prioritised = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
1969 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1970 b = dev->internalStartBlock;
1973 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1974 T(YAFFS_TRACE_ERROR,
1975 (TSTR("**>> Block %d is not valid" TENDSTR), b));
1979 bi = yaffs_GetBlockInfo(dev, b);
1982 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
1989 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1990 (bi->gcPrioritise || (bi->pagesInUse - bi->softDeletions)) < pagesInUse &&
1991 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1993 pagesInUse = (bi->pagesInUse - bi->softDeletions);
1994 if(bi->gcPrioritise)
1995 prioritised = 1; /* Trick it into selecting this one */
1999 dev->currentDirtyChecker = b;
2003 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2004 dev->nChunksPerBlock - pagesInUse,prioritised));
2007 dev->oldestDirtySequence = 0;
2010 nonAggressiveSkip = 4;
2016 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2018 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2022 /* If the block is still healthy erase it and mark as clean.
2023 * If the block has had a data failure, then retire it.
2025 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2027 if (!bi->needsRetiring) {
2028 yaffs_InvalidateCheckpoint(dev);
2029 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2031 dev->nErasureFailures++;
2032 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2033 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2037 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2039 for (i = 0; i < dev->nChunksPerBlock; i++) {
2040 if (!yaffs_CheckChunkErased
2041 (dev, blockNo * dev->nChunksPerBlock + i)) {
2042 T(YAFFS_TRACE_ERROR,
2044 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2045 TENDSTR), blockNo, i));
2051 /* Clean it up... */
2052 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2053 dev->nErasedBlocks++;
2055 bi->softDeletions = 0;
2056 bi->hasShrinkHeader = 0;
2057 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2058 bi->gcPrioritise = 0;
2059 yaffs_ClearChunkBits(dev, blockNo);
2061 T(YAFFS_TRACE_ERASE,
2062 (TSTR("Erased block %d" TENDSTR), blockNo));
2064 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2066 yaffs_RetireBlock(dev, blockNo);
2067 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2068 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2072 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2076 yaffs_BlockInfo *bi;
2078 if (dev->nErasedBlocks < 1) {
2079 /* Hoosterman we've got a problem.
2080 * Can't get space to gc
2082 T(YAFFS_TRACE_ERROR,
2083 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2088 /* Find an empty block. */
2090 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2091 dev->allocationBlockFinder++;
2092 if (dev->allocationBlockFinder < dev->internalStartBlock
2093 || dev->allocationBlockFinder > dev->internalEndBlock) {
2094 dev->allocationBlockFinder = dev->internalStartBlock;
2097 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2099 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2100 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2101 dev->sequenceNumber++;
2102 bi->sequenceNumber = dev->sequenceNumber;
2103 dev->nErasedBlocks--;
2104 T(YAFFS_TRACE_ALLOCATE,
2105 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2106 dev->allocationBlockFinder, dev->sequenceNumber,
2107 dev->nErasedBlocks));
2108 return dev->allocationBlockFinder;
2112 T(YAFFS_TRACE_ALWAYS,
2114 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2115 TENDSTR), dev->nErasedBlocks));
2121 // Check if there's space to allocate...
2122 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2123 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2126 int reservedBlocks = dev->nReservedBlocks;
2127 int checkpointBlocks;
2129 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2130 if(checkpointBlocks < 0)
2131 checkpointBlocks = 0;
2133 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2135 return (dev->nFreeChunks > reservedChunks);
2138 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2141 yaffs_BlockInfo *bi;
2143 if (dev->allocationBlock < 0) {
2144 /* Get next block to allocate off */
2145 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2146 dev->allocationPage = 0;
2149 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2150 /* Not enough space to allocate unless we're allowed to use the reserve. */
2154 if (dev->nErasedBlocks < dev->nReservedBlocks
2155 && dev->allocationPage == 0) {
2156 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2159 /* Next page please.... */
2160 if (dev->allocationBlock >= 0) {
2161 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2163 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2164 dev->allocationPage;
2166 yaffs_SetChunkBit(dev, dev->allocationBlock,
2167 dev->allocationPage);
2169 dev->allocationPage++;
2173 /* If the block is full set the state to full */
2174 if (dev->allocationPage >= dev->nChunksPerBlock) {
2175 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2176 dev->allocationBlock = -1;
2185 T(YAFFS_TRACE_ERROR,
2186 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2191 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2195 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2197 if (dev->allocationBlock > 0) {
2198 n += (dev->nChunksPerBlock - dev->allocationPage);
2205 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2211 int retVal = YAFFS_OK;
2214 int isCheckpointBlock;
2216 int chunksBefore = yaffs_GetErasedChunks(dev);
2219 yaffs_ExtendedTags tags;
2221 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2223 yaffs_Object *object;
2225 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2227 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2229 T(YAFFS_TRACE_TRACING,
2230 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2231 bi->pagesInUse, bi->hasShrinkHeader));
2233 /*yaffs_VerifyFreeChunks(dev); */
2235 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2237 /* Take off the number of soft deleted entries because
2238 * they're going to get really deleted during GC.
2240 dev->nFreeChunks -= bi->softDeletions;
2244 if (isCheckpointBlock ||
2245 !yaffs_StillSomeChunkBits(dev, block)) {
2246 T(YAFFS_TRACE_TRACING,
2248 ("Collecting block %d that has no chunks in use" TENDSTR),
2250 yaffs_BlockBecameDirty(dev, block);
2253 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2255 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2256 chunkInBlock < dev->nChunksPerBlock
2257 && yaffs_StillSomeChunkBits(dev, block);
2258 chunkInBlock++, oldChunk++) {
2259 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2261 /* This page is in use and might need to be copied off */
2265 yaffs_InitialiseTags(&tags);
2267 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2271 yaffs_FindObjectByNumber(dev,
2274 T(YAFFS_TRACE_GC_DETAIL,
2276 ("Collecting page %d, %d %d %d " TENDSTR),
2277 chunkInBlock, tags.objectId, tags.chunkId,
2281 T(YAFFS_TRACE_ERROR,
2283 ("page %d in gc has no object "
2284 TENDSTR), oldChunk));
2287 if (object && object->deleted
2288 && tags.chunkId != 0) {
2289 /* Data chunk in a deleted file, throw it away
2290 * It's a soft deleted data chunk,
2291 * No need to copy this, just forget about it and
2292 * fix up the object.
2295 object->nDataChunks--;
2297 if (object->nDataChunks <= 0) {
2298 /* remeber to clean up the object */
2299 dev->gcCleanupList[cleanups] =
2305 /* Todo object && object->deleted && object->nDataChunks == 0 */
2307 /* Deleted object header with no data chunks.
2308 * Can be discarded and the file deleted.
2310 object->chunkId = 0;
2311 yaffs_FreeTnode(object->myDev,
2314 object->variant.fileVariant.top = NULL;
2315 yaffs_DoGenericObjectDeletion(object);
2317 } else if (object) {
2318 /* It's either a data chunk in a live file or
2319 * an ObjectHeader, so we're interested in it.
2320 * NB Need to keep the ObjectHeaders of deleted files
2321 * until the whole file has been deleted off
2323 tags.serialNumber++;
2327 if (tags.chunkId == 0) {
2328 /* It is an object Id,
2329 * We need to nuke the shrinkheader flags first
2330 * We no longer want the shrinkHeader flag since its work is done
2331 * and if it is left in place it will mess up scanning.
2332 * Also, clear out any shadowing stuff
2335 yaffs_ObjectHeader *oh;
2336 oh = (yaffs_ObjectHeader *)buffer;
2338 oh->shadowsObject = -1;
2339 tags.extraShadows = 0;
2340 tags.extraIsShrinkHeader = 0;
2344 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2347 retVal = YAFFS_FAIL;
2350 /* Ok, now fix up the Tnodes etc. */
2352 if (tags.chunkId == 0) {
2354 object->chunkId = newChunk;
2355 object->serial = tags.serialNumber;
2357 /* It's a data chunk */
2358 yaffs_PutChunkIntoFile
2366 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2371 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2374 /* Do any required cleanups */
2375 for (i = 0; i < cleanups; i++) {
2376 /* Time to delete the file too */
2378 yaffs_FindObjectByNumber(dev,
2379 dev->gcCleanupList[i]);
2381 yaffs_FreeTnode(dev,
2382 object->variant.fileVariant.
2384 object->variant.fileVariant.top = NULL;
2387 ("yaffs: About to finally delete object %d"
2388 TENDSTR), object->objectId));
2389 yaffs_DoGenericObjectDeletion(object);
2390 object->myDev->nDeletedFiles--;
2397 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2400 ("gc did not increase free chunks before %d after %d"
2401 TENDSTR), chunksBefore, chunksAfter));
2409 /* New garbage collector
2410 * If we're very low on erased blocks then we do aggressive garbage collection
2411 * otherwise we do "leasurely" garbage collection.
2412 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2413 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2415 * The idea is to help clear out space in a more spread-out manner.
2416 * Dunno if it really does anything useful.
2418 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2422 int gcOk = YAFFS_OK;
2425 int checkpointBlockAdjust;
2427 if (dev->isDoingGC) {
2428 /* Bail out so we don't get recursive gc */
2432 /* This loop should pass the first time.
2433 * We'll only see looping here if the erase of the collected block fails.
2439 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2440 if(checkpointBlockAdjust < 0)
2441 checkpointBlockAdjust = 0;
2443 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2444 /* We need a block soon...*/
2447 /* We're in no hurry */
2451 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2454 dev->garbageCollections++;
2456 dev->passiveGarbageCollections++;
2461 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2462 dev->nErasedBlocks, aggressive));
2464 gcOk = yaffs_GarbageCollectBlock(dev, block);
2467 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2470 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2471 TENDSTR), dev->nErasedBlocks, maxTries, block));
2473 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2476 return aggressive ? gcOk : YAFFS_OK;
2479 /*------------------------- TAGS --------------------------------*/
2481 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2484 return (tags->chunkId == chunkInObject &&
2485 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2490 /*-------------------- Data file manipulation -----------------*/
2492 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2493 yaffs_ExtendedTags * tags)
2495 /*Get the Tnode, then get the level 0 offset chunk offset */
2498 yaffs_ExtendedTags localTags;
2501 yaffs_Device *dev = in->myDev;
2504 /* Passed a NULL, so use our own tags space */
2508 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2511 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2514 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2520 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2521 yaffs_ExtendedTags * tags)
2523 /* Get the Tnode, then get the level 0 offset chunk offset */
2526 yaffs_ExtendedTags localTags;
2528 yaffs_Device *dev = in->myDev;
2532 /* Passed a NULL, so use our own tags space */
2536 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2540 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2543 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2546 /* Delete the entry in the filestructure (if found) */
2548 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2551 /*T(("No level 0 found for %d\n", chunkInInode)); */
2555 /* T(("Could not find %d to delete\n",chunkInInode)); */
2560 #ifdef YAFFS_PARANOID
2562 static int yaffs_CheckFileSanity(yaffs_Object * in)
2570 yaffs_Tags localTags;
2571 yaffs_Tags *tags = &localTags;
2575 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2576 /* T(("Object not a file\n")); */
2580 objId = in->objectId;
2581 fSize = in->variant.fileVariant.fileSize;
2583 (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2585 for (chunk = 1; chunk <= nChunks; chunk++) {
2586 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2591 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2593 if (yaffs_CheckChunkBits
2594 (dev, theChunk / dev->nChunksPerBlock,
2595 theChunk % dev->nChunksPerBlock)) {
2597 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2601 (tags, in->objectId, chunk, chunkDeleted)) {
2611 /* T(("No level 0 found for %d\n", chunk)); */
2615 return failed ? YAFFS_FAIL : YAFFS_OK;
2620 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2621 int chunkInNAND, int inScan)
2623 /* NB inScan is zero unless scanning.
2624 * For forward scanning, inScan is > 0;
2625 * for backward scanning inScan is < 0
2629 yaffs_Device *dev = in->myDev;
2631 yaffs_ExtendedTags existingTags;
2632 yaffs_ExtendedTags newTags;
2633 unsigned existingSerial, newSerial;
2635 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2636 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2637 * If it is not during Scanning then something went wrong!
2640 T(YAFFS_TRACE_ERROR,
2642 ("yaffs tragedy:attempt to put data chunk into a non-file"
2647 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2651 tn = yaffs_AddOrFindLevel0Tnode(dev,
2652 &in->variant.fileVariant,
2659 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2662 /* If we're scanning then we need to test for duplicates
2663 * NB This does not need to be efficient since it should only ever
2664 * happen when the power fails during a write, then only one
2665 * chunk should ever be affected.
2667 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2668 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2671 if (existingChunk != 0) {
2672 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2673 * thus we have to do a FindChunkInFile to get the real chunk id.
2675 * We have a duplicate now we need to decide which one to use:
2677 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2678 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2679 * YAFFS1: Get both sets of tags and compare serial numbers.
2683 /* Only do this for forward scanning */
2684 yaffs_ReadChunkWithTagsFromNAND(dev,
2688 /* Do a proper find */
2690 yaffs_FindChunkInFile(in, chunkInInode,
2694 if (existingChunk <= 0) {
2695 /*Hoosterman - how did this happen? */
2697 T(YAFFS_TRACE_ERROR,
2699 ("yaffs tragedy: existing chunk < 0 in scan"
2704 /* NB The deleted flags should be false, otherwise the chunks will
2705 * not be loaded during a scan
2708 newSerial = newTags.serialNumber;
2709 existingSerial = existingTags.serialNumber;
2712 (in->myDev->isYaffs2 ||
2713 existingChunk <= 0 ||
2714 ((existingSerial + 1) & 3) == newSerial)) {
2715 /* Forward scanning.
2717 * Delete the old one and drop through to update the tnode
2719 yaffs_DeleteChunk(dev, existingChunk, 1,
2722 /* Backward scanning or we want to use the existing one
2724 * Delete the new one and return early so that the tnode isn't changed
2726 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2734 if (existingChunk == 0) {
2738 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2743 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2746 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2748 if (chunkInNAND >= 0) {
2749 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2752 T(YAFFS_TRACE_NANDACCESS,
2753 (TSTR("Chunk %d not found zero instead" TENDSTR),
2755 /* get sane (zero) data if you read a hole */
2756 memset(buffer, 0, in->myDev->nBytesPerChunk);
2762 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2766 yaffs_ExtendedTags tags;
2767 yaffs_BlockInfo *bi;
2773 block = chunkId / dev->nChunksPerBlock;
2774 page = chunkId % dev->nChunksPerBlock;
2776 bi = yaffs_GetBlockInfo(dev, block);
2778 T(YAFFS_TRACE_DELETION,
2779 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2782 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2784 yaffs_InitialiseTags(&tags);
2786 tags.chunkDeleted = 1;
2788 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2789 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2791 dev->nUnmarkedDeletions++;
2794 /* Pull out of the management area.
2795 * If the whole block became dirty, this will kick off an erasure.
2797 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2798 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2799 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2800 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2803 yaffs_ClearChunkBit(dev, block, page);
2807 if (bi->pagesInUse == 0 &&
2808 !bi->hasShrinkHeader &&
2809 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2810 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2811 yaffs_BlockBecameDirty(dev, block);
2815 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2820 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2821 const __u8 * buffer, int nBytes,
2824 /* Find old chunk Need to do this to get serial number
2825 * Write new one and patch into tree.
2826 * Invalidate old tags.
2830 yaffs_ExtendedTags prevTags;
2833 yaffs_ExtendedTags newTags;
2835 yaffs_Device *dev = in->myDev;
2837 yaffs_CheckGarbageCollection(dev);
2839 /* Get the previous chunk at this location in the file if it exists */
2840 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2842 /* Set up new tags */
2843 yaffs_InitialiseTags(&newTags);
2845 newTags.chunkId = chunkInInode;
2846 newTags.objectId = in->objectId;
2847 newTags.serialNumber =
2848 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2849 newTags.byteCount = nBytes;
2852 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2855 if (newChunkId >= 0) {
2856 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2858 if (prevChunkId >= 0) {
2859 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2863 yaffs_CheckFileSanity(in);
2869 /* UpdateObjectHeader updates the header on NAND for an object.
2870 * If name is not NULL, then that new name is used.
2872 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2873 int isShrink, int shadows)
2876 yaffs_BlockInfo *bi;
2878 yaffs_Device *dev = in->myDev;
2884 yaffs_ExtendedTags newTags;
2886 __u8 *buffer = NULL;
2887 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2889 yaffs_ObjectHeader *oh = NULL;
2891 if (!in->fake || force) {
2893 yaffs_CheckGarbageCollection(dev);
2895 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2896 oh = (yaffs_ObjectHeader *) buffer;
2898 prevChunkId = in->chunkId;
2900 if (prevChunkId >= 0) {
2901 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2903 memcpy(oldName, oh->name, sizeof(oh->name));
2906 memset(buffer, 0xFF, dev->nBytesPerChunk);
2908 oh->type = in->variantType;
2909 oh->yst_mode = in->yst_mode;
2910 oh->shadowsObject = shadows;
2912 #ifdef CONFIG_YAFFS_WINCE
2913 oh->win_atime[0] = in->win_atime[0];
2914 oh->win_ctime[0] = in->win_ctime[0];
2915 oh->win_mtime[0] = in->win_mtime[0];
2916 oh->win_atime[1] = in->win_atime[1];
2917 oh->win_ctime[1] = in->win_ctime[1];
2918 oh->win_mtime[1] = in->win_mtime[1];
2920 oh->yst_uid = in->yst_uid;
2921 oh->yst_gid = in->yst_gid;
2922 oh->yst_atime = in->yst_atime;
2923 oh->yst_mtime = in->yst_mtime;
2924 oh->yst_ctime = in->yst_ctime;
2925 oh->yst_rdev = in->yst_rdev;
2928 oh->parentObjectId = in->parent->objectId;
2930 oh->parentObjectId = 0;
2933 if (name && *name) {
2934 memset(oh->name, 0, sizeof(oh->name));
2935 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2936 } else if (prevChunkId) {
2937 memcpy(oh->name, oldName, sizeof(oh->name));
2939 memset(oh->name, 0, sizeof(oh->name));
2942 oh->isShrink = isShrink;
2944 switch (in->variantType) {
2945 case YAFFS_OBJECT_TYPE_UNKNOWN:
2946 /* Should not happen */
2948 case YAFFS_OBJECT_TYPE_FILE:
2950 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2951 || oh->parentObjectId ==
2952 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2953 fileVariant.fileSize;
2955 case YAFFS_OBJECT_TYPE_HARDLINK:
2956 oh->equivalentObjectId =
2957 in->variant.hardLinkVariant.equivalentObjectId;
2959 case YAFFS_OBJECT_TYPE_SPECIAL:
2962 case YAFFS_OBJECT_TYPE_DIRECTORY:
2965 case YAFFS_OBJECT_TYPE_SYMLINK:
2966 yaffs_strncpy(oh->alias,
2967 in->variant.symLinkVariant.alias,
2968 YAFFS_MAX_ALIAS_LENGTH);
2969 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2974 yaffs_InitialiseTags(&newTags);
2976 newTags.chunkId = 0;
2977 newTags.objectId = in->objectId;
2978 newTags.serialNumber = in->serial;
2980 /* Add extra info for file header */
2982 newTags.extraHeaderInfoAvailable = 1;
2983 newTags.extraParentObjectId = oh->parentObjectId;
2984 newTags.extraFileLength = oh->fileSize;
2985 newTags.extraIsShrinkHeader = oh->isShrink;
2986 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2987 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2988 newTags.extraObjectType = in->variantType;
2990 /* Create new chunk in NAND */
2992 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2993 (prevChunkId >= 0) ? 1 : 0);
2995 if (newChunkId >= 0) {
2997 in->chunkId = newChunkId;
2999 if (prevChunkId >= 0) {
3000 yaffs_DeleteChunk(dev, prevChunkId, 1,
3004 if(!yaffs_ObjectHasCachedWriteData(in))
3007 /* If this was a shrink, then mark the block that the chunk lives on */
3009 bi = yaffs_GetBlockInfo(in->myDev,
3010 newChunkId /in->myDev-> nChunksPerBlock);
3011 bi->hasShrinkHeader = 1;
3016 retVal = newChunkId;
3021 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3026 /*------------------------ Short Operations Cache ----------------------------------------
3027 * In many situations where there is no high level buffering (eg WinCE) a lot of
3028 * reads might be short sequential reads, and a lot of writes may be short
3029 * sequential writes. eg. scanning/writing a jpeg file.
3030 * In these cases, a short read/write cache can provide a huge perfomance benefit
3031 * with dumb-as-a-rock code.
3032 * In Linux, the page cache provides read buffering aand the short op cache provides write
3035 * There are a limited number (~10) of cache chunks per device so that we don't
3036 * need a very intelligent search.
3039 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3041 yaffs_Device *dev = obj->myDev;
3043 yaffs_ChunkCache *cache;
3044 int nCaches = obj->myDev->nShortOpCaches;
3047 for(i = 0; i < nCaches; i++){
3048 if (dev->srCache[i].object == obj &&
3049 dev->srCache[i].dirty)
3058 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3060 yaffs_Device *dev = obj->myDev;
3061 int lowest = -99; /* Stop compiler whining. */
3063 yaffs_ChunkCache *cache;
3064 int chunkWritten = 0;
3065 int nCaches = obj->myDev->nShortOpCaches;
3071 /* Find the dirty cache for this object with the lowest chunk id. */
3072 for (i = 0; i < nCaches; i++) {
3073 if (dev->srCache[i].object == obj &&
3074 dev->srCache[i].dirty) {
3076 || dev->srCache[i].chunkId <
3078 cache = &dev->srCache[i];
3079 lowest = cache->chunkId;
3084 if (cache && !cache->locked) {
3085 /* Write it out and free it up */
3088 yaffs_WriteChunkDataToObject(cache->object,
3094 cache->object = NULL;
3097 } while (cache && chunkWritten > 0);
3100 /* Hoosterman, disk full while writing cache out. */
3101 T(YAFFS_TRACE_ERROR,
3102 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3109 /*yaffs_FlushEntireDeviceCache(dev)
3114 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3117 int nCaches = dev->nShortOpCaches;
3120 /* Find a dirty object in the cache and flush it...
3121 * until there are no further dirty objects.
3125 for( i = 0; i < nCaches && !obj; i++) {
3126 if (dev->srCache[i].object &&
3127 dev->srCache[i].dirty)
3128 obj = dev->srCache[i].object;
3132 yaffs_FlushFilesChunkCache(obj);
3139 /* Grab us a cache chunk for use.
3140 * First look for an empty one.
3141 * Then look for the least recently used non-dirty one.
3142 * Then look for the least recently used dirty one...., flush and look again.
3144 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3150 if (dev->nShortOpCaches > 0) {
3151 for (i = 0; i < dev->nShortOpCaches; i++) {
3152 if (!dev->srCache[i].object)
3153 return &dev->srCache[i];
3159 usage = 0; /* just to stop the compiler grizzling */
3161 for (i = 0; i < dev->nShortOpCaches; i++) {
3162 if (!dev->srCache[i].dirty &&
3163 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3165 usage = dev->srCache[i].lastUse;
3171 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3178 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3180 yaffs_ChunkCache *cache;
3181 yaffs_Object *theObj;
3186 if (dev->nShortOpCaches > 0) {
3187 /* Try find a non-dirty one... */
3189 cache = yaffs_GrabChunkCacheWorker(dev);
3192 /* They were all dirty, find the last recently used object and flush
3193 * its cache, then find again.
3194 * NB what's here is not very accurate, we actually flush the object
3195 * the last recently used page.
3198 /* With locking we can't assume we can use entry zero */
3205 for (i = 0; i < dev->nShortOpCaches; i++) {
3206 if (dev->srCache[i].object &&
3207 !dev->srCache[i].locked &&
3208 (dev->srCache[i].lastUse < usage || !cache))
3210 usage = dev->srCache[i].lastUse;
3211 theObj = dev->srCache[i].object;
3212 cache = &dev->srCache[i];
3217 if (!cache || cache->dirty) {
3218 /* Flush and try again */
3219 yaffs_FlushFilesChunkCache(theObj);
3220 cache = yaffs_GrabChunkCacheWorker(dev);
3230 /* Find a cached chunk */
3231 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3234 yaffs_Device *dev = obj->myDev;
3236 if (dev->nShortOpCaches > 0) {
3237 for (i = 0; i < dev->nShortOpCaches; i++) {
3238 if (dev->srCache[i].object == obj &&
3239 dev->srCache[i].chunkId == chunkId) {
3242 return &dev->srCache[i];
3249 /* Mark the chunk for the least recently used algorithym */
3250 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3254 if (dev->nShortOpCaches > 0) {
3255 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3256 /* Reset the cache usages */
3258 for (i = 1; i < dev->nShortOpCaches; i++) {
3259 dev->srCache[i].lastUse = 0;
3266 cache->lastUse = dev->srLastUse;
3274 /* Invalidate a single cache page.
3275 * Do this when a whole page gets written,
3276 * ie the short cache for this page is no longer valid.
3278 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3280 if (object->myDev->nShortOpCaches > 0) {
3281 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3284 cache->object = NULL;
3289 /* Invalidate all the cache pages associated with this object
3290 * Do this whenever ther file is deleted or resized.
3292 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3295 yaffs_Device *dev = in->myDev;
3297 if (dev->nShortOpCaches > 0) {
3298 /* Invalidate it. */
3299 for (i = 0; i < dev->nShortOpCaches; i++) {
3300 if (dev->srCache[i].object == in) {
3301 dev->srCache[i].object = NULL;
3307 /*--------------------- Checkpointing --------------------*/
3310 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3312 yaffs_CheckpointValidity cp;
3313 cp.structType = sizeof(cp);
3314 cp.magic = YAFFS_MAGIC;
3316 cp.head = (head) ? 1 : 0;
3318 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3322 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3324 yaffs_CheckpointValidity cp;
3327 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3330 ok = (cp.structType == sizeof(cp)) &&
3331 (cp.magic == YAFFS_MAGIC) &&
3332 (cp.version == 1) &&
3333 (cp.head == ((head) ? 1 : 0));
3337 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3340 cp->nErasedBlocks = dev->nErasedBlocks;
3341 cp->allocationBlock = dev->allocationBlock;
3342 cp->allocationPage = dev->allocationPage;
3343 cp->nFreeChunks = dev->nFreeChunks;
3345 cp->nDeletedFiles = dev->nDeletedFiles;
3346 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3347 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3348 cp->sequenceNumber = dev->sequenceNumber;
3349 cp->oldestDirtySequence = dev->oldestDirtySequence;
3353 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3354 yaffs_CheckpointDevice *cp)
3356 dev->nErasedBlocks = cp->nErasedBlocks;
3357 dev->allocationBlock = cp->allocationBlock;
3358 dev->allocationPage = cp->allocationPage;
3359 dev->nFreeChunks = cp->nFreeChunks;
3361 dev->nDeletedFiles = cp->nDeletedFiles;
3362 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3363 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3364 dev->sequenceNumber = cp->sequenceNumber;
3365 dev->oldestDirtySequence = cp->oldestDirtySequence;
3369 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3371 yaffs_CheckpointDevice cp;
3373 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3377 /* Write device runtime values*/
3378 yaffs_DeviceToCheckpointDevice(&cp,dev);
3379 cp.structType = sizeof(cp);
3381 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3383 /* Write block info */
3385 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3386 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3389 /* Write chunk bits */
3391 nBytes = nBlocks * dev->chunkBitmapStride;
3392 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3398 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3400 yaffs_CheckpointDevice cp;
3402 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3406 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3410 if(cp.structType != sizeof(cp))
3414 yaffs_CheckpointDeviceToDevice(dev,&cp);
3416 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3418 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3422 nBytes = nBlocks * dev->chunkBitmapStride;
3424 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3429 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3433 cp->objectId = obj->objectId;
3434 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3435 cp->chunkId = obj->chunkId;
3436 cp->variantType = obj->variantType;
3437 cp->deleted = obj->deleted;
3438 cp->softDeleted = obj->softDeleted;
3439 cp->unlinked = obj->unlinked;
3440 cp->fake = obj->fake;
3441 cp->renameAllowed = obj->renameAllowed;
3442 cp->unlinkAllowed = obj->unlinkAllowed;
3443 cp->serial = obj->serial;
3444 cp->nDataChunks = obj->nDataChunks;
3446 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3447 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3448 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3449 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3452 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3455 yaffs_Object *parent;
3457 obj->objectId = cp->objectId;
3460 parent = yaffs_FindOrCreateObjectByNumber(
3463 YAFFS_OBJECT_TYPE_DIRECTORY);
3468 yaffs_AddObjectToDirectory(parent, obj);
3470 obj->chunkId = cp->chunkId;
3471 obj->variantType = cp->variantType;
3472 obj->deleted = cp->deleted;
3473 obj->softDeleted = cp->softDeleted;
3474 obj->unlinked = cp->unlinked;
3475 obj->fake = cp->fake;
3476 obj->renameAllowed = cp->renameAllowed;
3477 obj->unlinkAllowed = cp->unlinkAllowed;
3478 obj->serial = cp->serial;
3479 obj->nDataChunks = cp->nDataChunks;
3481 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3482 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3483 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3484 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3486 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3487 obj->lazyLoaded = 1;
3492 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3493 __u32 level, int chunkOffset)
3496 yaffs_Device *dev = in->myDev;
3498 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3503 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3504 if (tn->internal[i]) {
3505 ok = yaffs_CheckpointTnodeWorker(in,
3508 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3511 } else if (level == 0) {
3512 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3513 /* printf("write tnode at %d\n",baseOffset); */
3514 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3516 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3524 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3526 __u32 endMarker = ~0;
3529 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3530 ok = yaffs_CheckpointTnodeWorker(obj,
3531 obj->variant.fileVariant.top,
3532 obj->variant.fileVariant.topLevel,
3535 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3542 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3546 yaffs_Device *dev = obj->myDev;
3547 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3550 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3552 while(ok && (~baseChunk)){
3553 /* Read level 0 tnode */
3555 /* printf("read tnode at %d\n",baseChunk); */
3556 tn = yaffs_GetTnodeRaw(dev);
3558 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3559 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3564 ok = yaffs_AddOrFindLevel0Tnode(dev,
3571 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3579 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3582 yaffs_CheckpointObject cp;
3585 struct list_head *lh;
3588 /* Iterate through the objects in each hash entry,
3589 * dumping them to the checkpointing stream.
3592 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3593 list_for_each(lh, &dev->objectBucket[i].list) {
3595 obj = list_entry(lh, yaffs_Object, hashLink);
3596 if (!obj->deferedFree) {
3597 yaffs_ObjectToCheckpointObject(&cp,obj);
3598 cp.structType = sizeof(cp);
3599 /* printf("Write out object %d type %d\n",obj->objectId,obj->variantType); */
3600 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3602 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3603 ok = yaffs_WriteCheckpointTnodes(obj);
3610 /* Dump end of list */
3611 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3612 cp.structType = sizeof(cp);
3615 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3620 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3623 yaffs_CheckpointObject cp;
3626 yaffs_Object *hardList = NULL;
3628 while(ok && !done) {
3629 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3630 if(cp.structType != sizeof(cp)) {
3631 /* printf("structure parsing failed\n"); */
3635 if(ok && cp.objectId == ~0)
3638 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Read object %d parent %d type %d" TENDSTR),
3639 cp.objectId,cp.parentId,cp.variantType));
3640 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3642 yaffs_CheckpointObjectToObject(obj,&cp);
3643 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3644 ok = yaffs_ReadCheckpointTnodes(obj);
3645 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3646 obj->hardLinks.next =
3647 (struct list_head *)
3657 yaffs_HardlinkFixup(dev,hardList);
3662 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3667 ok = yaffs_CheckpointOpen(dev,1);
3670 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3672 ok = yaffs_WriteCheckpointDevice(dev);
3674 ok = yaffs_WriteCheckpointObjects(dev);
3676 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3678 if(!yaffs_CheckpointClose(dev))
3682 dev->isCheckpointed = 1;
3684 dev->isCheckpointed = 0;
3686 return dev->isCheckpointed;
3689 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3693 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3696 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3698 ok = yaffs_ReadCheckpointDevice(dev);
3700 ok = yaffs_ReadCheckpointObjects(dev);
3702 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3706 if(!yaffs_CheckpointClose(dev))
3710 dev->isCheckpointed = 1;
3712 dev->isCheckpointed = 0;
3718 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3720 if(dev->isCheckpointed ||
3721 dev->blocksInCheckpoint > 0){
3722 dev->isCheckpointed = 0;
3723 yaffs_CheckpointInvalidateStream(dev);
3724 if(dev->superBlock && dev->markSuperBlockDirty)
3725 dev->markSuperBlockDirty(dev->superBlock);
3730 int yaffs_CheckpointSave(yaffs_Device *dev)
3732 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3734 if(!dev->isCheckpointed)
3735 yaffs_WriteCheckpointData(dev);
3737 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3739 return dev->isCheckpointed;
3742 int yaffs_CheckpointRestore(yaffs_Device *dev)
3745 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3747 retval = yaffs_ReadCheckpointData(dev);
3749 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3754 /*--------------------- File read/write ------------------------
3755 * Read and write have very similar structures.
3756 * In general the read/write has three parts to it
3757 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3758 * Some complete chunks
3759 * An incomplete chunk to end off with
3761 * Curve-balls: the first chunk might also be the last chunk.
3764 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3773 yaffs_ChunkCache *cache;
3780 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3781 start = offset % dev->nBytesPerChunk;
3783 /* OK now check for the curveball where the start and end are in
3786 if ((start + n) < dev->nBytesPerChunk) {
3789 nToCopy = dev->nBytesPerChunk - start;
3792 cache = yaffs_FindChunkCache(in, chunk);
3794 /* If the chunk is already in the cache or it is less than a whole chunk
3795 * then use the cache (if there is caching)
3796 * else bypass the cache.
3798 if (cache || nToCopy != dev->nBytesPerChunk) {
3799 if (dev->nShortOpCaches > 0) {
3801 /* If we can't find the data in the cache, then load it up. */
3804 cache = yaffs_GrabChunkCache(in->myDev);
3806 cache->chunkId = chunk;
3809 yaffs_ReadChunkDataFromObject(in, chunk,
3815 yaffs_UseChunkCache(dev, cache, 0);
3819 #ifdef CONFIG_YAFFS_WINCE
3820 yfsd_UnlockYAFFS(TRUE);
3822 memcpy(buffer, &cache->data[start], nToCopy);
3824 #ifdef CONFIG_YAFFS_WINCE
3825 yfsd_LockYAFFS(TRUE);
3829 /* Read into the local buffer then copy..*/
3832 yaffs_GetTempBuffer(dev, __LINE__);
3833 yaffs_ReadChunkDataFromObject(in, chunk,
3835 #ifdef CONFIG_YAFFS_WINCE
3836 yfsd_UnlockYAFFS(TRUE);
3838 memcpy(buffer, &localBuffer[start], nToCopy);
3840 #ifdef CONFIG_YAFFS_WINCE
3841 yfsd_LockYAFFS(TRUE);
3843 yaffs_ReleaseTempBuffer(dev, localBuffer,
3848 #ifdef CONFIG_YAFFS_WINCE
3849 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3851 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3852 * This is because we otherwise screw up WinCE's memory mapper
3854 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3856 #ifdef CONFIG_YAFFS_WINCE
3857 yfsd_UnlockYAFFS(TRUE);
3859 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3861 #ifdef CONFIG_YAFFS_WINCE
3862 yfsd_LockYAFFS(TRUE);
3863 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3867 /* A full chunk. Read directly into the supplied buffer. */
3868 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3882 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3883 int nBytes, int writeThrough)
3892 int startOfWrite = offset;
3893 int chunkWritten = 0;
3900 while (n > 0 && chunkWritten >= 0) {
3901 chunk = offset / dev->nBytesPerChunk + 1;
3902 start = offset % dev->nBytesPerChunk;
3904 /* OK now check for the curveball where the start and end are in
3908 if ((start + n) < dev->nBytesPerChunk) {
3911 /* Now folks, to calculate how many bytes to write back....
3912 * If we're overwriting and not writing to then end of file then
3913 * we need to write back as much as was there before.
3917 in->variant.fileVariant.fileSize -
3918 ((chunk - 1) * dev->nBytesPerChunk);
3920 if (nBytesRead > dev->nBytesPerChunk) {
3921 nBytesRead = dev->nBytesPerChunk;
3926 (start + n)) ? nBytesRead : (start + n);
3929 nToCopy = dev->nBytesPerChunk - start;
3930 nToWriteBack = dev->nBytesPerChunk;
3933 if (nToCopy != dev->nBytesPerChunk) {
3934 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3935 if (dev->nShortOpCaches > 0) {
3936 yaffs_ChunkCache *cache;
3937 /* If we can't find the data in the cache, then load the cache */
3938 cache = yaffs_FindChunkCache(in, chunk);
3941 && yaffs_CheckSpaceForAllocation(in->
3943 cache = yaffs_GrabChunkCache(in->myDev);
3945 cache->chunkId = chunk;
3948 yaffs_ReadChunkDataFromObject(in, chunk,
3954 !yaffs_CheckSpaceForAllocation(in->myDev)){
3955 /* Drop the cache if it was a read cache item and
3956 * no space check has been made for it.
3962 yaffs_UseChunkCache(dev, cache, 1);
3964 #ifdef CONFIG_YAFFS_WINCE
3965 yfsd_UnlockYAFFS(TRUE);
3968 memcpy(&cache->data[start], buffer,
3971 #ifdef CONFIG_YAFFS_WINCE
3972 yfsd_LockYAFFS(TRUE);
3975 cache->nBytes = nToWriteBack;
3979 yaffs_WriteChunkDataToObject
3982 cache->data, cache->nBytes,
3988 chunkWritten = -1; /* fail the write */
3991 /* An incomplete start or end chunk (or maybe both start and end chunk)
3992 * Read into the local buffer then copy, then copy over and write back.
3996 yaffs_GetTempBuffer(dev, __LINE__);
3998 yaffs_ReadChunkDataFromObject(in, chunk,
4001 #ifdef CONFIG_YAFFS_WINCE
4002 yfsd_UnlockYAFFS(TRUE);
4005 memcpy(&localBuffer[start], buffer, nToCopy);
4007 #ifdef CONFIG_YAFFS_WINCE
4008 yfsd_LockYAFFS(TRUE);
4011 yaffs_WriteChunkDataToObject(in, chunk,
4016 yaffs_ReleaseTempBuffer(dev, localBuffer,
4023 #ifdef CONFIG_YAFFS_WINCE
4024 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4025 * This is because we otherwise screw up WinCE's memory mapper
4027 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4028 #ifdef CONFIG_YAFFS_WINCE
4029 yfsd_UnlockYAFFS(TRUE);
4031 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
4032 #ifdef CONFIG_YAFFS_WINCE
4033 yfsd_LockYAFFS(TRUE);
4036 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4037 dev->nBytesPerChunk,
4039 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4041 /* A full chunk. Write directly from the supplied buffer. */
4043 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4044 dev->nBytesPerChunk,
4047 /* Since we've overwritten the cached data, we better invalidate it. */
4048 yaffs_InvalidateChunkCache(in, chunk);
4051 if (chunkWritten >= 0) {
4060 /* Update file object */
4062 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4063 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4072 /* ---------------------- File resizing stuff ------------------ */
4074 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4077 yaffs_Device *dev = in->myDev;
4078 int oldFileSize = in->variant.fileVariant.fileSize;
4080 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
4082 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
4083 dev->nBytesPerChunk;
4087 /* Delete backwards so that we don't end up with holes if
4088 * power is lost part-way through the operation.
4090 for (i = lastDel; i >= startDel; i--) {
4091 /* NB this could be optimised somewhat,
4092 * eg. could retrieve the tags and write them without
4093 * using yaffs_DeleteChunk
4096 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4099 (dev->internalStartBlock * dev->nChunksPerBlock)
4101 ((dev->internalEndBlock +
4102 1) * dev->nChunksPerBlock)) {
4103 T(YAFFS_TRACE_ALWAYS,
4104 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4108 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4115 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
4118 int oldFileSize = in->variant.fileVariant.fileSize;
4119 int sizeOfPartialChunk;
4120 yaffs_Device *dev = in->myDev;
4122 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
4124 yaffs_FlushFilesChunkCache(in);
4125 yaffs_InvalidateWholeChunkCache(in);
4127 yaffs_CheckGarbageCollection(dev);
4129 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4130 return yaffs_GetFileSize(in);
4133 if (newSize == oldFileSize) {
4137 if (newSize < oldFileSize) {
4139 yaffs_PruneResizedChunks(in, newSize);
4141 if (sizeOfPartialChunk != 0) {
4142 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
4143 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4145 /* Got to read and rewrite the last chunk with its new size and zero pad */
4146 yaffs_ReadChunkDataFromObject(in, lastChunk,
4149 memset(localBuffer + sizeOfPartialChunk, 0,
4150 dev->nBytesPerChunk - sizeOfPartialChunk);
4152 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4153 sizeOfPartialChunk, 1);
4155 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4158 in->variant.fileVariant.fileSize = newSize;
4160 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4162 /* Write a new object header.
4163 * show we've shrunk the file, if need be
4164 * Do this only if the file is not in the deleted directories.
4166 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4167 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4168 yaffs_UpdateObjectHeader(in, NULL, 0,
4169 (newSize < oldFileSize) ? 1 : 0, 0);
4175 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4177 obj = yaffs_GetEquivalentObject(obj);
4179 switch (obj->variantType) {
4180 case YAFFS_OBJECT_TYPE_FILE:
4181 return obj->variant.fileVariant.fileSize;
4182 case YAFFS_OBJECT_TYPE_SYMLINK:
4183 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4191 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4195 yaffs_FlushFilesChunkCache(in);
4197 #ifdef CONFIG_YAFFS_WINCE
4198 yfsd_WinFileTimeNow(in->win_mtime);
4201 in->yst_mtime = Y_CURRENT_TIME;
4207 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4208 0) ? YAFFS_OK : YAFFS_FAIL;
4217 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4220 /* First off, invalidate the file's data in the cache, without flushing. */
4221 yaffs_InvalidateWholeChunkCache(in);
4223 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4224 /* Move to the unlinked directory so we have a record that it was deleted. */
4225 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4229 yaffs_RemoveObjectFromDirectory(in);
4230 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4233 yaffs_FreeObject(in);
4238 /* yaffs_DeleteFile deletes the whole file data
4239 * and the inode associated with the file.
4240 * It does not delete the links associated with the file.
4242 static int yaffs_UnlinkFile(yaffs_Object * in)
4246 int immediateDeletion = 0;
4251 immediateDeletion = 1;
4255 if (in->inUse <= 0) {
4256 immediateDeletion = 1;
4260 if (immediateDeletion) {
4262 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4264 T(YAFFS_TRACE_TRACING,
4265 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4268 in->myDev->nDeletedFiles++;
4269 if (0 && in->myDev->isYaffs2) {
4270 yaffs_ResizeFile(in, 0);
4272 yaffs_SoftDeleteFile(in);
4275 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4283 int yaffs_DeleteFile(yaffs_Object * in)
4285 int retVal = YAFFS_OK;
4287 if (in->nDataChunks > 0) {
4288 /* Use soft deletion if there is data in the file */
4289 if (!in->unlinked) {
4290 retVal = yaffs_UnlinkFile(in);
4292 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4294 in->myDev->nDeletedFiles++;
4295 yaffs_SoftDeleteFile(in);
4297 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4299 /* The file has no data chunks so we toss it immediately */
4300 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4301 in->variant.fileVariant.top = NULL;
4302 yaffs_DoGenericObjectDeletion(in);
4308 static int yaffs_DeleteDirectory(yaffs_Object * in)
4310 /* First check that the directory is empty. */
4311 if (list_empty(&in->variant.directoryVariant.children)) {
4312 return yaffs_DoGenericObjectDeletion(in);
4319 static int yaffs_DeleteSymLink(yaffs_Object * in)
4321 YFREE(in->variant.symLinkVariant.alias);
4323 return yaffs_DoGenericObjectDeletion(in);
4326 static int yaffs_DeleteHardLink(yaffs_Object * in)
4328 /* remove this hardlink from the list assocaited with the equivalent
4331 list_del(&in->hardLinks);
4332 return yaffs_DoGenericObjectDeletion(in);
4335 static void yaffs_DestroyObject(yaffs_Object * obj)
4337 switch (obj->variantType) {
4338 case YAFFS_OBJECT_TYPE_FILE:
4339 yaffs_DeleteFile(obj);
4341 case YAFFS_OBJECT_TYPE_DIRECTORY:
4342 yaffs_DeleteDirectory(obj);
4344 case YAFFS_OBJECT_TYPE_SYMLINK:
4345 yaffs_DeleteSymLink(obj);
4347 case YAFFS_OBJECT_TYPE_HARDLINK:
4348 yaffs_DeleteHardLink(obj);
4350 case YAFFS_OBJECT_TYPE_SPECIAL:
4351 yaffs_DoGenericObjectDeletion(obj);
4353 case YAFFS_OBJECT_TYPE_UNKNOWN:
4354 break; /* should not happen. */
4358 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4361 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4362 return yaffs_DeleteHardLink(obj);
4363 } else if (!list_empty(&obj->hardLinks)) {
4364 /* Curve ball: We're unlinking an object that has a hardlink.
4366 * This problem arises because we are not strictly following
4367 * The Linux link/inode model.
4369 * We can't really delete the object.
4370 * Instead, we do the following:
4371 * - Select a hardlink.
4372 * - Unhook it from the hard links
4373 * - Unhook it from its parent directory (so that the rename can work)
4374 * - Rename the object to the hardlink's name.
4375 * - Delete the hardlink
4380 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4382 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4384 list_del_init(&hl->hardLinks);
4385 list_del_init(&hl->siblings);
4387 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4389 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4391 if (retVal == YAFFS_OK) {
4392 retVal = yaffs_DoGenericObjectDeletion(hl);
4397 switch (obj->variantType) {
4398 case YAFFS_OBJECT_TYPE_FILE:
4399 return yaffs_UnlinkFile(obj);
4401 case YAFFS_OBJECT_TYPE_DIRECTORY:
4402 return yaffs_DeleteDirectory(obj);
4404 case YAFFS_OBJECT_TYPE_SYMLINK:
4405 return yaffs_DeleteSymLink(obj);
4407 case YAFFS_OBJECT_TYPE_SPECIAL:
4408 return yaffs_DoGenericObjectDeletion(obj);
4410 case YAFFS_OBJECT_TYPE_HARDLINK:
4411 case YAFFS_OBJECT_TYPE_UNKNOWN:
4419 static int yaffs_UnlinkObject( yaffs_Object *obj)
4422 if (obj && obj->unlinkAllowed) {
4423 return yaffs_UnlinkWorker(obj);
4429 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4433 obj = yaffs_FindObjectByName(dir, name);
4434 return yaffs_UnlinkObject(obj);
4437 /*----------------------- Initialisation Scanning ---------------------- */
4439 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4440 int backwardScanning)
4444 if (!backwardScanning) {
4445 /* Handle YAFFS1 forward scanning case
4446 * For YAFFS1 we always do the deletion
4450 /* Handle YAFFS2 case (backward scanning)
4451 * If the shadowed object exists then ignore.
4453 if (yaffs_FindObjectByNumber(dev, objId)) {
4458 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4459 * We put it in unlinked dir to be cleaned up after the scanning
4462 yaffs_FindOrCreateObjectByNumber(dev, objId,
4463 YAFFS_OBJECT_TYPE_FILE);
4464 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4465 obj->variant.fileVariant.shrinkSize = 0;
4466 obj->valid = 1; /* So that we don't read any other info for this file */
4476 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4483 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4485 in = yaffs_FindObjectByNumber(dev,
4486 hl->variant.hardLinkVariant.
4487 equivalentObjectId);
4490 /* Add the hardlink pointers */
4491 hl->variant.hardLinkVariant.equivalentObject = in;
4492 list_add(&hl->hardLinks, &in->hardLinks);
4494 /* Todo Need to report/handle this better.
4495 * Got a problem... hardlink to a non-existant object
4497 hl->variant.hardLinkVariant.equivalentObject = NULL;
4498 INIT_LIST_HEAD(&hl->hardLinks);
4510 static int ybicmp(const void *a, const void *b){
4511 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4512 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4513 register int ablock = ((yaffs_BlockIndex *)a)->block;
4514 register int bblock = ((yaffs_BlockIndex *)b)->block;
4516 return ablock - bblock;
4522 static int yaffs_Scan(yaffs_Device * dev)
4524 yaffs_ExtendedTags tags;
4529 int nBlocksToScan = 0;
4534 yaffs_BlockState state;
4535 yaffs_Object *hardList = NULL;
4537 yaffs_BlockInfo *bi;
4539 yaffs_ObjectHeader *oh;
4541 yaffs_Object *parent;
4542 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4546 yaffs_BlockIndex *blockIndex = NULL;
4548 if (dev->isYaffs2) {
4550 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4554 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4557 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4558 dev->internalStartBlock, dev->internalEndBlock));
4560 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4562 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4564 if (dev->isYaffs2) {
4565 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4568 /* Scan all the blocks to determine their state */
4569 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4570 bi = yaffs_GetBlockInfo(dev, blk);
4571 yaffs_ClearChunkBits(dev, blk);
4573 bi->softDeletions = 0;
4575 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4577 bi->blockState = state;
4578 bi->sequenceNumber = sequenceNumber;
4580 T(YAFFS_TRACE_SCAN_DEBUG,
4581 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4582 state, sequenceNumber));
4584 if (state == YAFFS_BLOCK_STATE_DEAD) {
4585 T(YAFFS_TRACE_BAD_BLOCKS,
4586 (TSTR("block %d is bad" TENDSTR), blk));
4587 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4588 T(YAFFS_TRACE_SCAN_DEBUG,
4589 (TSTR("Block empty " TENDSTR)));
4590 dev->nErasedBlocks++;
4591 dev->nFreeChunks += dev->nChunksPerBlock;
4592 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4594 /* Determine the highest sequence number */
4595 if (dev->isYaffs2 &&
4596 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4597 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4599 blockIndex[nBlocksToScan].seq = sequenceNumber;
4600 blockIndex[nBlocksToScan].block = blk;
4604 if (sequenceNumber >= dev->sequenceNumber) {
4605 dev->sequenceNumber = sequenceNumber;
4607 } else if (dev->isYaffs2) {
4608 /* TODO: Nasty sequence number! */
4611 ("Block scanning block %d has bad sequence number %d"
4612 TENDSTR), blk, sequenceNumber));
4619 * Dungy old bubble sort for now...
4621 if (dev->isYaffs2) {
4622 yaffs_BlockIndex temp;
4626 for (i = 0; i < nBlocksToScan; i++)
4627 for (j = i + 1; j < nBlocksToScan; j++)
4628 if (blockIndex[i].seq > blockIndex[j].seq) {
4629 temp = blockIndex[j];
4630 blockIndex[j] = blockIndex[i];
4631 blockIndex[i] = temp;
4635 /* Now scan the blocks looking at the data. */
4636 if (dev->isYaffs2) {
4638 endIterator = nBlocksToScan - 1;
4639 T(YAFFS_TRACE_SCAN_DEBUG,
4640 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4642 startIterator = dev->internalStartBlock;
4643 endIterator = dev->internalEndBlock;
4646 /* For each block.... */
4647 for (blockIterator = startIterator; blockIterator <= endIterator;
4650 if (dev->isYaffs2) {
4651 /* get the block to scan in the correct order */
4652 blk = blockIndex[blockIterator].block;
4654 blk = blockIterator;
4657 bi = yaffs_GetBlockInfo(dev, blk);
4658 state = bi->blockState;
4662 /* For each chunk in each block that needs scanning....*/
4663 for (c = 0; c < dev->nChunksPerBlock &&
4664 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4665 /* Read the tags and decide what to do */
4666 chunk = blk * dev->nChunksPerBlock + c;
4668 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4671 /* Let's have a good look at this chunk... */
4673 if (!dev->isYaffs2 && tags.chunkDeleted) {
4679 /*T((" %d %d deleted\n",blk,c)); */
4680 } else if (!tags.chunkUsed) {
4681 /* An unassigned chunk in the block
4682 * This means that either the block is empty or
4683 * this is the one being allocated from
4687 /* We're looking at the first chunk in the block so the block is unused */
4688 state = YAFFS_BLOCK_STATE_EMPTY;
4689 dev->nErasedBlocks++;
4691 /* this is the block being allocated from */
4694 (" Allocating from %d %d" TENDSTR),
4696 state = YAFFS_BLOCK_STATE_ALLOCATING;
4697 dev->allocationBlock = blk;
4698 dev->allocationPage = c;
4699 dev->allocationBlockFinder = blk;
4700 /* Set it to here to encourage the allocator to go forth from here. */
4702 /* Yaffs2 sanity check:
4703 * This should be the one with the highest sequence number
4706 && (dev->sequenceNumber !=
4707 bi->sequenceNumber)) {
4708 T(YAFFS_TRACE_ALWAYS,
4710 ("yaffs: Allocation block %d was not highest sequence id:"
4711 " block seq = %d, dev seq = %d"
4712 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4716 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4717 } else if (tags.chunkId > 0) {
4718 /* chunkId > 0 so it is a data chunk... */
4719 unsigned int endpos;
4721 yaffs_SetChunkBit(dev, blk, c);
4724 in = yaffs_FindOrCreateObjectByNumber(dev,
4727 YAFFS_OBJECT_TYPE_FILE);
4728 /* PutChunkIntoFile checks for a clash (two data chunks with
4729 * the same chunkId).
4731 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4734 (tags.chunkId - 1) * dev->nBytesPerChunk +
4736 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4737 && in->variant.fileVariant.scannedFileSize <
4739 in->variant.fileVariant.
4740 scannedFileSize = endpos;
4741 if (!dev->useHeaderFileSize) {
4742 in->variant.fileVariant.
4744 in->variant.fileVariant.
4749 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4751 /* chunkId == 0, so it is an ObjectHeader.
4752 * Thus, we read in the object header and make the object
4754 yaffs_SetChunkBit(dev, blk, c);
4757 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4761 oh = (yaffs_ObjectHeader *) chunkData;
4763 in = yaffs_FindObjectByNumber(dev,
4765 if (in && in->variantType != oh->type) {
4766 /* This should not happen, but somehow
4767 * Wev'e ended up with an objectId that has been reused but not yet
4768 * deleted, and worse still it has changed type. Delete the old object.
4771 yaffs_DestroyObject(in);
4776 in = yaffs_FindOrCreateObjectByNumber(dev,
4781 if (oh->shadowsObject > 0) {
4782 yaffs_HandleShadowedObject(dev,
4789 /* We have already filled this one. We have a duplicate and need to resolve it. */
4791 unsigned existingSerial = in->serial;
4792 unsigned newSerial = tags.serialNumber;
4794 if (dev->isYaffs2 ||
4795 ((existingSerial + 1) & 3) ==
4797 /* Use new one - destroy the exisiting one */
4798 yaffs_DeleteChunk(dev,
4803 /* Use existing - destroy this one. */
4804 yaffs_DeleteChunk(dev, chunk, 1,
4810 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4811 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4812 /* We only load some info, don't fiddle with directory structure */
4814 in->variantType = oh->type;
4816 in->yst_mode = oh->yst_mode;
4817 #ifdef CONFIG_YAFFS_WINCE
4818 in->win_atime[0] = oh->win_atime[0];
4819 in->win_ctime[0] = oh->win_ctime[0];
4820 in->win_mtime[0] = oh->win_mtime[0];
4821 in->win_atime[1] = oh->win_atime[1];
4822 in->win_ctime[1] = oh->win_ctime[1];
4823 in->win_mtime[1] = oh->win_mtime[1];
4825 in->yst_uid = oh->yst_uid;
4826 in->yst_gid = oh->yst_gid;
4827 in->yst_atime = oh->yst_atime;
4828 in->yst_mtime = oh->yst_mtime;
4829 in->yst_ctime = oh->yst_ctime;
4830 in->yst_rdev = oh->yst_rdev;
4832 in->chunkId = chunk;
4834 } else if (!in->valid) {
4835 /* we need to load this info */
4838 in->variantType = oh->type;
4840 in->yst_mode = oh->yst_mode;
4841 #ifdef CONFIG_YAFFS_WINCE
4842 in->win_atime[0] = oh->win_atime[0];
4843 in->win_ctime[0] = oh->win_ctime[0];
4844 in->win_mtime[0] = oh->win_mtime[0];
4845 in->win_atime[1] = oh->win_atime[1];
4846 in->win_ctime[1] = oh->win_ctime[1];
4847 in->win_mtime[1] = oh->win_mtime[1];
4849 in->yst_uid = oh->yst_uid;
4850 in->yst_gid = oh->yst_gid;
4851 in->yst_atime = oh->yst_atime;
4852 in->yst_mtime = oh->yst_mtime;
4853 in->yst_ctime = oh->yst_ctime;
4854 in->yst_rdev = oh->yst_rdev;
4856 in->chunkId = chunk;
4858 yaffs_SetObjectName(in, oh->name);
4861 /* directory stuff...
4866 yaffs_FindOrCreateObjectByNumber
4867 (dev, oh->parentObjectId,
4868 YAFFS_OBJECT_TYPE_DIRECTORY);
4869 if (parent->variantType ==
4870 YAFFS_OBJECT_TYPE_UNKNOWN) {
4871 /* Set up as a directory */
4872 parent->variantType =
4873 YAFFS_OBJECT_TYPE_DIRECTORY;
4874 INIT_LIST_HEAD(&parent->variant.
4877 } else if (parent->variantType !=
4878 YAFFS_OBJECT_TYPE_DIRECTORY)
4880 /* Hoosterman, another problem....
4881 * We're trying to use a non-directory as a directory
4884 T(YAFFS_TRACE_ERROR,
4886 ("yaffs tragedy: attempting to use non-directory as"
4887 " a directory in scan. Put in lost+found."
4889 parent = dev->lostNFoundDir;
4892 yaffs_AddObjectToDirectory(parent, in);
4894 if (0 && (parent == dev->deletedDir ||
4895 parent == dev->unlinkedDir)) {
4896 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
4897 dev->nDeletedFiles++;
4899 /* Note re hardlinks.
4900 * Since we might scan a hardlink before its equivalent object is scanned
4901 * we put them all in a list.
4902 * After scanning is complete, we should have all the objects, so we run through this
4903 * list and fix up all the chains.
4906 switch (in->variantType) {
4907 case YAFFS_OBJECT_TYPE_UNKNOWN:
4908 /* Todo got a problem */
4910 case YAFFS_OBJECT_TYPE_FILE:
4913 /* Prune back the shrunken chunks */
4914 yaffs_PruneResizedChunks
4916 /* Mark the block as having a shrinkHeader */
4917 bi->hasShrinkHeader = 1;
4920 if (dev->useHeaderFileSize)
4922 in->variant.fileVariant.
4927 case YAFFS_OBJECT_TYPE_HARDLINK:
4928 in->variant.hardLinkVariant.
4929 equivalentObjectId =
4930 oh->equivalentObjectId;
4931 in->hardLinks.next =
4932 (struct list_head *)
4936 case YAFFS_OBJECT_TYPE_DIRECTORY:
4939 case YAFFS_OBJECT_TYPE_SPECIAL:
4942 case YAFFS_OBJECT_TYPE_SYMLINK:
4943 in->variant.symLinkVariant.
4945 yaffs_CloneString(oh->alias);
4949 if (parent == dev->deletedDir) {
4950 yaffs_DestroyObject(in);
4951 bi->hasShrinkHeader = 1;
4957 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4958 /* If we got this far while scanning, then the block is fully allocated.*/
4959 state = YAFFS_BLOCK_STATE_FULL;
4962 bi->blockState = state;
4964 /* Now let's see if it was dirty */
4965 if (bi->pagesInUse == 0 &&
4966 !bi->hasShrinkHeader &&
4967 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4968 yaffs_BlockBecameDirty(dev, blk);
4978 /* Ok, we've done all the scanning.
4979 * Fix up the hard link chains.
4980 * We should now have scanned all the objects, now it's time to add these
4984 yaffs_HardlinkFixup(dev,hardList);
4986 /* Handle the unlinked files. Since they were left in an unlinked state we should
4990 struct list_head *i;
4991 struct list_head *n;
4994 /* Soft delete all the unlinked files */
4995 list_for_each_safe(i, n,
4996 &dev->unlinkedDir->variant.directoryVariant.
4999 l = list_entry(i, yaffs_Object, siblings);
5000 yaffs_DestroyObject(l);
5005 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5007 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5012 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5015 yaffs_ObjectHeader *oh;
5016 yaffs_Device *dev = in->myDev;
5020 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5022 yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,NULL);
5023 oh = (yaffs_ObjectHeader *) chunkData;
5025 in->yst_mode = oh->yst_mode;
5026 #ifdef CONFIG_YAFFS_WINCE
5027 in->win_atime[0] = oh->win_atime[0];
5028 in->win_ctime[0] = oh->win_ctime[0];
5029 in->win_mtime[0] = oh->win_mtime[0];
5030 in->win_atime[1] = oh->win_atime[1];
5031 in->win_ctime[1] = oh->win_ctime[1];
5032 in->win_mtime[1] = oh->win_mtime[1];
5034 in->yst_uid = oh->yst_uid;
5035 in->yst_gid = oh->yst_gid;
5036 in->yst_atime = oh->yst_atime;
5037 in->yst_mtime = oh->yst_mtime;
5038 in->yst_ctime = oh->yst_ctime;
5039 in->yst_rdev = oh->yst_rdev;
5042 yaffs_SetObjectName(in, oh->name);
5044 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5045 in->variant.symLinkVariant.alias =
5046 yaffs_CloneString(oh->alias);
5048 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5052 static int yaffs_ScanBackwards(yaffs_Device * dev)
5054 yaffs_ExtendedTags tags;
5059 int nBlocksToScan = 0;
5064 yaffs_BlockState state;
5065 yaffs_Object *hardList = NULL;
5066 yaffs_BlockInfo *bi;
5068 yaffs_ObjectHeader *oh;
5070 yaffs_Object *parent;
5071 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5077 int foundChunksInBlock;
5078 int equivalentObjectId;
5081 yaffs_BlockIndex *blockIndex = NULL;
5082 int altBlockIndex = 0;
5084 if (!dev->isYaffs2) {
5086 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5092 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5093 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5096 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5098 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5101 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5107 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5111 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5113 /* Scan all the blocks to determine their state */
5114 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5115 bi = yaffs_GetBlockInfo(dev, blk);
5116 yaffs_ClearChunkBits(dev, blk);
5118 bi->softDeletions = 0;
5120 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5122 bi->blockState = state;
5123 bi->sequenceNumber = sequenceNumber;
5125 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5126 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5128 T(YAFFS_TRACE_SCAN_DEBUG,
5129 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5130 state, sequenceNumber));
5133 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5134 /* todo .. fix free space ? */
5136 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5137 T(YAFFS_TRACE_BAD_BLOCKS,
5138 (TSTR("block %d is bad" TENDSTR), blk));
5139 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5140 T(YAFFS_TRACE_SCAN_DEBUG,
5141 (TSTR("Block empty " TENDSTR)));
5142 dev->nErasedBlocks++;
5143 dev->nFreeChunks += dev->nChunksPerBlock;
5144 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5146 /* Determine the highest sequence number */
5147 if (dev->isYaffs2 &&
5148 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5149 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5151 blockIndex[nBlocksToScan].seq = sequenceNumber;
5152 blockIndex[nBlocksToScan].block = blk;
5156 if (sequenceNumber >= dev->sequenceNumber) {
5157 dev->sequenceNumber = sequenceNumber;
5159 } else if (dev->isYaffs2) {
5160 /* TODO: Nasty sequence number! */
5163 ("Block scanning block %d has bad sequence number %d"
5164 TENDSTR), blk, sequenceNumber));
5171 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5177 /* Sort the blocks */
5178 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5180 /* Use qsort now. */
5181 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5185 /* Dungy old bubble sort... */
5187 yaffs_BlockIndex temp;
5191 for (i = 0; i < nBlocksToScan; i++)
5192 for (j = i + 1; j < nBlocksToScan; j++)
5193 if (blockIndex[i].seq > blockIndex[j].seq) {
5194 temp = blockIndex[j];
5195 blockIndex[j] = blockIndex[i];
5196 blockIndex[i] = temp;
5203 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5205 /* Now scan the blocks looking at the data. */
5207 endIterator = nBlocksToScan - 1;
5208 T(YAFFS_TRACE_SCAN_DEBUG,
5209 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5211 /* For each block.... backwards */
5212 for (blockIterator = endIterator; blockIterator >= startIterator;
5214 /* Cooperative multitasking! This loop can run for so
5215 long that watchdog timers expire. */
5218 /* get the block to scan in the correct order */
5219 blk = blockIndex[blockIterator].block;
5221 bi = yaffs_GetBlockInfo(dev, blk);
5222 state = bi->blockState;
5226 /* For each chunk in each block that needs scanning.... */
5227 foundChunksInBlock = 0;
5228 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5229 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5230 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5231 /* Scan backwards...
5232 * Read the tags and decide what to do
5234 chunk = blk * dev->nChunksPerBlock + c;
5236 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5239 /* Let's have a good look at this chunk... */
5241 if (!tags.chunkUsed) {
5242 /* An unassigned chunk in the block.
5243 * If there are used chunks after this one, then
5244 * it is a chunk that was skipped due to failing the erased
5245 * check. Just skip it so that it can be deleted.
5246 * But, more typically, We get here when this is an unallocated
5247 * chunk and his means that either the block is empty or
5248 * this is the one being allocated from
5251 if(foundChunksInBlock)
5253 /* This is a chunk that was skipped due to failing the erased check */
5255 } else if (c == 0) {
5256 /* We're looking at the first chunk in the block so the block is unused */
5257 state = YAFFS_BLOCK_STATE_EMPTY;
5258 dev->nErasedBlocks++;
5260 /* this is the block being allocated from */
5262 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5265 (" Allocating from %d %d"
5268 state = YAFFS_BLOCK_STATE_ALLOCATING;
5269 dev->allocationBlock = blk;
5270 dev->allocationPage = c;
5271 dev->allocationBlockFinder = blk;
5272 /* Set it to here to encourage the allocator to
5273 * go forth from here.
5276 /* Yaffs2 sanity check:
5277 * This should be the one with the highest sequence number
5280 && (dev->sequenceNumber !=
5281 bi->sequenceNumber)) {
5282 T(YAFFS_TRACE_ALWAYS,
5284 ("yaffs: Allocation block %d was not highest sequence "
5285 "id: block seq = %d, dev seq = %d"
5288 dev->sequenceNumber));
5293 } else if (tags.chunkId > 0) {
5294 /* chunkId > 0 so it is a data chunk... */
5295 unsigned int endpos;
5297 (tags.chunkId - 1) * dev->nBytesPerChunk;
5299 foundChunksInBlock = 1;
5302 yaffs_SetChunkBit(dev, blk, c);
5305 in = yaffs_FindOrCreateObjectByNumber(dev,
5308 YAFFS_OBJECT_TYPE_FILE);
5309 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5311 in->variant.fileVariant.shrinkSize) {
5312 /* This has not been invalidated by a resize */
5313 yaffs_PutChunkIntoFile(in, tags.chunkId,
5316 /* File size is calculated by looking at the data chunks if we have not
5317 * seen an object header yet. Stop this practice once we find an object header.
5321 1) * dev->nBytesPerChunk +
5324 if (!in->valid && /* have not got an object header yet */
5325 in->variant.fileVariant.
5326 scannedFileSize < endpos) {
5327 in->variant.fileVariant.
5328 scannedFileSize = endpos;
5329 in->variant.fileVariant.
5331 in->variant.fileVariant.
5336 /* This chunk has been invalidated by a resize, so delete */
5337 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5341 /* chunkId == 0, so it is an ObjectHeader.
5342 * Thus, we read in the object header and make the object
5344 foundChunksInBlock = 1;
5346 yaffs_SetChunkBit(dev, blk, c);
5352 if (tags.extraHeaderInfoAvailable) {
5353 in = yaffs_FindOrCreateObjectByNumber
5354 (dev, tags.objectId,
5355 tags.extraObjectType);
5359 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5362 tags.extraShadows ||
5364 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5365 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5368 /* If we don't have valid info then we need to read the chunk
5369 * TODO In future we can probably defer reading the chunk and
5370 * living with invalid data until needed.
5373 yaffs_ReadChunkWithTagsFromNAND(dev,
5378 oh = (yaffs_ObjectHeader *) chunkData;
5381 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5386 /* TODO Hoosterman we have a problem! */
5387 T(YAFFS_TRACE_ERROR,
5389 ("yaffs tragedy: Could not make object for object %d "
5390 "at chunk %d during scan"
5391 TENDSTR), tags.objectId, chunk));
5396 /* We have already filled this one.
5397 * We have a duplicate that will be discarded, but
5398 * we first have to suck out resize info if it is a file.
5401 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5403 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5404 (tags.extraHeaderInfoAvailable &&
5405 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5408 (oh) ? oh->fileSize : tags.
5410 __u32 parentObjectId =
5412 parentObjectId : tags.
5413 extraParentObjectId;
5415 (oh) ? oh->isShrink : tags.
5416 extraIsShrinkHeader;
5418 /* If it is deleted (unlinked at start also means deleted)
5419 * we treat the file size as being zeroed at this point.
5421 if (parentObjectId ==
5422 YAFFS_OBJECTID_DELETED
5423 || parentObjectId ==
5424 YAFFS_OBJECTID_UNLINKED) {
5430 in->variant.fileVariant.
5431 shrinkSize > thisSize) {
5432 in->variant.fileVariant.
5438 bi->hasShrinkHeader = 1;
5442 /* Use existing - destroy this one. */
5443 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5448 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5450 YAFFS_OBJECTID_LOSTNFOUND)) {
5451 /* We only load some info, don't fiddle with directory structure */
5455 in->variantType = oh->type;
5457 in->yst_mode = oh->yst_mode;
5458 #ifdef CONFIG_YAFFS_WINCE
5459 in->win_atime[0] = oh->win_atime[0];
5460 in->win_ctime[0] = oh->win_ctime[0];
5461 in->win_mtime[0] = oh->win_mtime[0];
5462 in->win_atime[1] = oh->win_atime[1];
5463 in->win_ctime[1] = oh->win_ctime[1];
5464 in->win_mtime[1] = oh->win_mtime[1];
5466 in->yst_uid = oh->yst_uid;
5467 in->yst_gid = oh->yst_gid;
5468 in->yst_atime = oh->yst_atime;
5469 in->yst_mtime = oh->yst_mtime;
5470 in->yst_ctime = oh->yst_ctime;
5471 in->yst_rdev = oh->yst_rdev;
5475 in->variantType = tags.extraObjectType;
5479 in->chunkId = chunk;
5481 } else if (!in->valid) {
5482 /* we need to load this info */
5485 in->chunkId = chunk;
5488 in->variantType = oh->type;
5490 in->yst_mode = oh->yst_mode;
5491 #ifdef CONFIG_YAFFS_WINCE
5492 in->win_atime[0] = oh->win_atime[0];
5493 in->win_ctime[0] = oh->win_ctime[0];
5494 in->win_mtime[0] = oh->win_mtime[0];
5495 in->win_atime[1] = oh->win_atime[1];
5496 in->win_ctime[1] = oh->win_ctime[1];
5497 in->win_mtime[1] = oh->win_mtime[1];
5499 in->yst_uid = oh->yst_uid;
5500 in->yst_gid = oh->yst_gid;
5501 in->yst_atime = oh->yst_atime;
5502 in->yst_mtime = oh->yst_mtime;
5503 in->yst_ctime = oh->yst_ctime;
5504 in->yst_rdev = oh->yst_rdev;
5507 if (oh->shadowsObject > 0)
5508 yaffs_HandleShadowedObject(dev,
5514 yaffs_SetObjectName(in, oh->name);
5516 yaffs_FindOrCreateObjectByNumber
5517 (dev, oh->parentObjectId,
5518 YAFFS_OBJECT_TYPE_DIRECTORY);
5520 fileSize = oh->fileSize;
5521 isShrink = oh->isShrink;
5522 equivalentObjectId = oh->equivalentObjectId;
5526 in->variantType = tags.extraObjectType;
5528 yaffs_FindOrCreateObjectByNumber
5529 (dev, tags.extraParentObjectId,
5530 YAFFS_OBJECT_TYPE_DIRECTORY);
5531 fileSize = tags.extraFileLength;
5532 isShrink = tags.extraIsShrinkHeader;
5533 equivalentObjectId = tags.extraEquivalentObjectId;
5539 /* directory stuff...
5543 if (parent->variantType ==
5544 YAFFS_OBJECT_TYPE_UNKNOWN) {
5545 /* Set up as a directory */
5546 parent->variantType =
5547 YAFFS_OBJECT_TYPE_DIRECTORY;
5548 INIT_LIST_HEAD(&parent->variant.
5551 } else if (parent->variantType !=
5552 YAFFS_OBJECT_TYPE_DIRECTORY)
5554 /* Hoosterman, another problem....
5555 * We're trying to use a non-directory as a directory
5558 T(YAFFS_TRACE_ERROR,
5560 ("yaffs tragedy: attempting to use non-directory as"
5561 " a directory in scan. Put in lost+found."
5563 parent = dev->lostNFoundDir;
5566 yaffs_AddObjectToDirectory(parent, in);
5568 itsUnlinked = (parent == dev->deletedDir) ||
5569 (parent == dev->unlinkedDir);
5572 /* Mark the block as having a shrinkHeader */
5573 bi->hasShrinkHeader = 1;
5576 /* Note re hardlinks.
5577 * Since we might scan a hardlink before its equivalent object is scanned
5578 * we put them all in a list.
5579 * After scanning is complete, we should have all the objects, so we run
5580 * through this list and fix up all the chains.
5583 switch (in->variantType) {
5584 case YAFFS_OBJECT_TYPE_UNKNOWN:
5585 /* Todo got a problem */
5587 case YAFFS_OBJECT_TYPE_FILE:
5589 if (in->variant.fileVariant.
5590 scannedFileSize < fileSize) {
5591 /* This covers the case where the file size is greater
5592 * than where the data is
5593 * This will happen if the file is resized to be larger
5594 * than its current data extents.
5596 in->variant.fileVariant.fileSize = fileSize;
5597 in->variant.fileVariant.scannedFileSize =
5598 in->variant.fileVariant.fileSize;
5602 in->variant.fileVariant.shrinkSize > fileSize) {
5603 in->variant.fileVariant.shrinkSize = fileSize;
5607 case YAFFS_OBJECT_TYPE_HARDLINK:
5609 in->variant.hardLinkVariant.equivalentObjectId =
5611 in->hardLinks.next =
5612 (struct list_head *) hardList;
5616 case YAFFS_OBJECT_TYPE_DIRECTORY:
5619 case YAFFS_OBJECT_TYPE_SPECIAL:
5622 case YAFFS_OBJECT_TYPE_SYMLINK:
5624 in->variant.symLinkVariant.alias =
5625 yaffs_CloneString(oh->
5634 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5635 /* If we got this far while scanning, then the block is fully allocated. */
5636 state = YAFFS_BLOCK_STATE_FULL;
5639 bi->blockState = state;
5641 /* Now let's see if it was dirty */
5642 if (bi->pagesInUse == 0 &&
5643 !bi->hasShrinkHeader &&
5644 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5645 yaffs_BlockBecameDirty(dev, blk);
5651 YFREE_ALT(blockIndex);
5655 /* Ok, we've done all the scanning.
5656 * Fix up the hard link chains.
5657 * We should now have scanned all the objects, now it's time to add these
5660 yaffs_HardlinkFixup(dev,hardList);
5664 * Sort out state of unlinked and deleted objects.
5667 struct list_head *i;
5668 struct list_head *n;
5672 /* Soft delete all the unlinked files */
5673 list_for_each_safe(i, n,
5674 &dev->unlinkedDir->variant.directoryVariant.
5677 l = list_entry(i, yaffs_Object, siblings);
5678 yaffs_DestroyObject(l);
5682 /* Soft delete all the deletedDir files */
5683 list_for_each_safe(i, n,
5684 &dev->deletedDir->variant.directoryVariant.
5687 l = list_entry(i, yaffs_Object, siblings);
5688 yaffs_DestroyObject(l);
5694 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5696 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5701 /*------------------------------ Directory Functions ----------------------------- */
5703 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5705 yaffs_Device *dev = obj->myDev;
5707 if(dev && dev->removeObjectCallback)
5708 dev->removeObjectCallback(obj);
5710 list_del_init(&obj->siblings);
5715 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5720 T(YAFFS_TRACE_ALWAYS,
5722 ("tragedy: Trying to add an object to a null pointer directory"
5726 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5727 T(YAFFS_TRACE_ALWAYS,
5729 ("tragedy: Trying to add an object to a non-directory"
5734 if (obj->siblings.prev == NULL) {
5735 /* Not initialised */
5736 INIT_LIST_HEAD(&obj->siblings);
5738 } else if (!list_empty(&obj->siblings)) {
5739 /* If it is holed up somewhere else, un hook it */
5740 yaffs_RemoveObjectFromDirectory(obj);
5743 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5744 obj->parent = directory;
5746 if (directory == obj->myDev->unlinkedDir
5747 || directory == obj->myDev->deletedDir) {
5749 obj->myDev->nUnlinkedFiles++;
5750 obj->renameAllowed = 0;
5754 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5759 struct list_head *i;
5760 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5769 T(YAFFS_TRACE_ALWAYS,
5771 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5775 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5776 T(YAFFS_TRACE_ALWAYS,
5778 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5782 sum = yaffs_CalcNameSum(name);
5784 list_for_each(i, &directory->variant.directoryVariant.children) {
5786 l = list_entry(i, yaffs_Object, siblings);
5788 yaffs_CheckObjectDetailsLoaded(l);
5790 /* Special case for lost-n-found */
5791 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5792 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5795 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5797 /* LostnFound cunk called Objxxx
5800 yaffs_GetObjectName(l, buffer,
5801 YAFFS_MAX_NAME_LENGTH);
5802 if (yaffs_strcmp(name, buffer) == 0) {
5815 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5816 int (*fn) (yaffs_Object *))
5818 struct list_head *i;
5822 T(YAFFS_TRACE_ALWAYS,
5824 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5828 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5829 T(YAFFS_TRACE_ALWAYS,
5831 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5835 list_for_each(i, &theDir->variant.directoryVariant.children) {
5837 l = list_entry(i, yaffs_Object, siblings);
5849 /* GetEquivalentObject dereferences any hard links to get to the
5853 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5855 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5856 /* We want the object id of the equivalent object, not this one */
5857 obj = obj->variant.hardLinkVariant.equivalentObject;
5863 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5865 memset(name, 0, buffSize * sizeof(YCHAR));
5867 yaffs_CheckObjectDetailsLoaded(obj);
5869 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5870 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5871 } else if (obj->chunkId <= 0) {
5873 /* make up a name */
5874 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5876 yaffs_strncpy(name, locName, buffSize - 1);
5879 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5880 else if (obj->shortName[0]) {
5881 yaffs_strcpy(name, obj->shortName);
5885 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5887 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5889 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5891 if (obj->chunkId >= 0) {
5892 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5893 obj->chunkId, buffer,
5896 yaffs_strncpy(name, oh->name, buffSize - 1);
5898 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5901 return yaffs_strlen(name);
5904 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5907 /* Dereference any hard linking */
5908 obj = yaffs_GetEquivalentObject(obj);
5910 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5911 return obj->variant.fileVariant.fileSize;
5913 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5914 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5916 /* Only a directory should drop through to here */
5917 return obj->myDev->nBytesPerChunk;
5921 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5924 struct list_head *i;
5926 if (!obj->unlinked) {
5927 count++; /* the object itself */
5929 list_for_each(i, &obj->hardLinks) {
5930 count++; /* add the hard links; */
5936 int yaffs_GetObjectInode(yaffs_Object * obj)
5938 obj = yaffs_GetEquivalentObject(obj);
5940 return obj->objectId;
5943 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5945 obj = yaffs_GetEquivalentObject(obj);
5947 switch (obj->variantType) {
5948 case YAFFS_OBJECT_TYPE_FILE:
5951 case YAFFS_OBJECT_TYPE_DIRECTORY:
5954 case YAFFS_OBJECT_TYPE_SYMLINK:
5957 case YAFFS_OBJECT_TYPE_HARDLINK:
5960 case YAFFS_OBJECT_TYPE_SPECIAL:
5961 if (S_ISFIFO(obj->yst_mode))
5963 if (S_ISCHR(obj->yst_mode))
5965 if (S_ISBLK(obj->yst_mode))
5967 if (S_ISSOCK(obj->yst_mode))
5975 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5977 obj = yaffs_GetEquivalentObject(obj);
5978 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5979 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5981 return yaffs_CloneString(_Y(""));
5985 #ifndef CONFIG_YAFFS_WINCE
5987 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5989 unsigned int valid = attr->ia_valid;
5991 if (valid & ATTR_MODE)
5992 obj->yst_mode = attr->ia_mode;
5993 if (valid & ATTR_UID)
5994 obj->yst_uid = attr->ia_uid;
5995 if (valid & ATTR_GID)
5996 obj->yst_gid = attr->ia_gid;
5998 if (valid & ATTR_ATIME)
5999 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6000 if (valid & ATTR_CTIME)
6001 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6002 if (valid & ATTR_MTIME)
6003 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6005 if (valid & ATTR_SIZE)
6006 yaffs_ResizeFile(obj, attr->ia_size);
6008 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6013 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6015 unsigned int valid = 0;
6017 attr->ia_mode = obj->yst_mode;
6019 attr->ia_uid = obj->yst_uid;
6021 attr->ia_gid = obj->yst_gid;
6024 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6025 valid |= ATTR_ATIME;
6026 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6027 valid |= ATTR_CTIME;
6028 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6029 valid |= ATTR_MTIME;
6031 attr->ia_size = yaffs_GetFileSize(obj);
6034 attr->ia_valid = valid;
6043 int yaffs_DumpObject(yaffs_Object * obj)
6047 yaffs_GetObjectName(obj, name, 256);
6049 T(YAFFS_TRACE_ALWAYS,
6051 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6052 " chunk %d type %d size %d\n"
6053 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6054 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6055 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6061 /*---------------------------- Initialisation code -------------------------------------- */
6063 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6066 /* Common functions, gotta have */
6067 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6070 #ifdef CONFIG_YAFFS_YAFFS2
6072 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6073 if (dev->writeChunkWithTagsToNAND &&
6074 dev->readChunkWithTagsFromNAND &&
6075 !dev->writeChunkToNAND &&
6076 !dev->readChunkFromNAND &&
6077 dev->markNANDBlockBad && dev->queryNANDBlock)
6081 /* Can use the "spare" style interface for yaffs1 */
6082 if (!dev->isYaffs2 &&
6083 !dev->writeChunkWithTagsToNAND &&
6084 !dev->readChunkWithTagsFromNAND &&
6085 dev->writeChunkToNAND &&
6086 dev->readChunkFromNAND &&
6087 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6094 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6096 /* Initialise the unlinked, deleted, root and lost and found directories */
6098 dev->lostNFoundDir = dev->rootDir = NULL;
6099 dev->unlinkedDir = dev->deletedDir = NULL;
6102 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6104 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6107 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6108 YAFFS_ROOT_MODE | S_IFDIR);
6109 dev->lostNFoundDir =
6110 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6111 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6112 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6115 int yaffs_GutsInitialise(yaffs_Device * dev)
6121 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6123 /* Check stuff that must be set */
6126 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6130 dev->internalStartBlock = dev->startBlock;
6131 dev->internalEndBlock = dev->endBlock;
6132 dev->blockOffset = 0;
6133 dev->chunkOffset = 0;
6134 dev->nFreeChunks = 0;
6136 if (dev->startBlock == 0) {
6137 dev->internalStartBlock = dev->startBlock + 1;
6138 dev->internalEndBlock = dev->endBlock + 1;
6139 dev->blockOffset = 1;
6140 dev->chunkOffset = dev->nChunksPerBlock;
6143 /* Check geometry parameters. */
6145 if ((dev->isYaffs2 && dev->nBytesPerChunk < 1024) ||
6146 (!dev->isYaffs2 && dev->nBytesPerChunk != 512) ||
6147 dev->nChunksPerBlock < 2 ||
6148 dev->nReservedBlocks < 2 ||
6149 dev->internalStartBlock <= 0 ||
6150 dev->internalEndBlock <= 0 ||
6151 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6153 T(YAFFS_TRACE_ALWAYS,
6155 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6156 TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6160 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6161 T(YAFFS_TRACE_ALWAYS,
6162 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6166 /* Got the right mix of functions? */
6167 if (!yaffs_CheckDevFunctions(dev)) {
6168 /* Function missing */
6169 T(YAFFS_TRACE_ALWAYS,
6171 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6176 /* This is really a compilation check. */
6177 if (!yaffs_CheckStructures()) {
6178 T(YAFFS_TRACE_ALWAYS,
6179 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6183 if (dev->isMounted) {
6184 T(YAFFS_TRACE_ALWAYS,
6185 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6189 /* Finished with most checks. One or two more checks happen later on too. */
6195 /* OK now calculate a few things for the device
6196 * Calculate chunkGroupBits.
6197 * We need to find the next power of 2 > than internalEndBlock
6200 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6202 for (bits = extraBits = 0; x > 1; bits++) {
6211 /* Set up tnode width if wide tnodes are enabled. */
6212 if(!dev->wideTnodesDisabled){
6213 /* bits must be even so that we end up with 32-bit words */
6217 dev->tnodeWidth = 16;
6219 dev->tnodeWidth = bits;
6222 dev->tnodeWidth = 16;
6224 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6226 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6227 * so if the bitwidth of the
6228 * chunk range we're using is greater than 16 we need
6229 * to figure out chunk shift and chunkGroupSize
6232 if (bits <= dev->tnodeWidth)
6233 dev->chunkGroupBits = 0;
6235 dev->chunkGroupBits = bits - dev->tnodeWidth;
6238 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6240 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6241 /* We have a problem because the soft delete won't work if
6242 * the chunk group size > chunks per block.
6243 * This can be remedied by using larger "virtual blocks".
6245 T(YAFFS_TRACE_ALWAYS,
6246 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6251 /* OK, we've finished verifying the device, lets continue with initialisation */
6253 /* More device initialisation */
6254 dev->garbageCollections = 0;
6255 dev->passiveGarbageCollections = 0;
6256 dev->currentDirtyChecker = 0;
6257 dev->bufferedBlock = -1;
6258 dev->doingBufferedBlockRewrite = 0;
6259 dev->nDeletedFiles = 0;
6260 dev->nBackgroundDeletions = 0;
6261 dev->nUnlinkedFiles = 0;
6263 dev->eccUnfixed = 0;
6264 dev->tagsEccFixed = 0;
6265 dev->tagsEccUnfixed = 0;
6266 dev->nErasureFailures = 0;
6267 dev->nErasedBlocks = 0;
6270 /* Initialise temporary buffers and caches. */
6273 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6274 dev->tempBuffer[i].line = 0; /* not in use */
6275 dev->tempBuffer[i].buffer =
6276 YMALLOC_DMA(dev->nBytesPerChunk);
6280 if (dev->nShortOpCaches > 0) {
6283 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6284 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6288 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6290 for (i = 0; i < dev->nShortOpCaches; i++) {
6291 dev->srCache[i].object = NULL;
6292 dev->srCache[i].lastUse = 0;
6293 dev->srCache[i].dirty = 0;
6294 dev->srCache[i].data = YMALLOC_DMA(dev->nBytesPerChunk);
6301 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6303 if (dev->isYaffs2) {
6304 dev->useHeaderFileSize = 1;
6307 yaffs_InitialiseBlocks(dev);
6308 yaffs_InitialiseTnodes(dev);
6309 yaffs_InitialiseObjects(dev);
6311 yaffs_CreateInitialDirectories(dev);
6314 /* Now scan the flash. */
6315 if (dev->isYaffs2) {
6316 if(yaffs_CheckpointRestore(dev)) {
6317 T(YAFFS_TRACE_ALWAYS,
6318 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6321 /* Clean up the mess caused by an aborted checkpoint load
6322 * and scan backwards.
6324 yaffs_DeinitialiseBlocks(dev);
6325 yaffs_DeinitialiseTnodes(dev);
6326 yaffs_DeinitialiseObjects(dev);
6327 yaffs_InitialiseBlocks(dev);
6328 yaffs_InitialiseTnodes(dev);
6329 yaffs_InitialiseObjects(dev);
6330 yaffs_CreateInitialDirectories(dev);
6332 yaffs_ScanBackwards(dev);
6337 /* Zero out stats */
6338 dev->nPageReads = 0;
6339 dev->nPageWrites = 0;
6340 dev->nBlockErasures = 0;
6342 dev->nRetriedWrites = 0;
6344 dev->nRetiredBlocks = 0;
6346 yaffs_VerifyFreeChunks(dev);
6348 T(YAFFS_TRACE_TRACING,
6349 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6354 void yaffs_Deinitialise(yaffs_Device * dev)
6356 if (dev->isMounted) {
6359 yaffs_DeinitialiseBlocks(dev);
6360 yaffs_DeinitialiseTnodes(dev);
6361 yaffs_DeinitialiseObjects(dev);
6362 if (dev->nShortOpCaches > 0) {
6364 for (i = 0; i < dev->nShortOpCaches; i++) {
6365 YFREE(dev->srCache[i].data);
6368 YFREE(dev->srCache);
6371 YFREE(dev->gcCleanupList);
6373 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6374 YFREE(dev->tempBuffer[i].buffer);
6382 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6387 yaffs_BlockInfo *blk;
6389 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6391 blk = yaffs_GetBlockInfo(dev, b);
6393 switch (blk->blockState) {
6394 case YAFFS_BLOCK_STATE_EMPTY:
6395 case YAFFS_BLOCK_STATE_ALLOCATING:
6396 case YAFFS_BLOCK_STATE_COLLECTING:
6397 case YAFFS_BLOCK_STATE_FULL:
6399 (dev->nChunksPerBlock - blk->pagesInUse +
6400 blk->softDeletions);
6411 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6413 /* This is what we report to the outside world */
6416 int nDirtyCacheChunks;
6417 int blocksForCheckpoint;
6420 nFree = dev->nFreeChunks;
6422 nFree = yaffs_CountFreeChunks(dev);
6425 nFree += dev->nDeletedFiles;
6427 /* Now count the number of dirty chunks in the cache and subtract those */
6431 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6432 if (dev->srCache[i].dirty)
6433 nDirtyCacheChunks++;
6437 nFree -= nDirtyCacheChunks;
6439 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6441 /* Now we figure out how much to reserve for the checkpoint and report that... */
6442 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6443 if(blocksForCheckpoint < 0)
6444 blocksForCheckpoint = 0;
6446 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6455 static int yaffs_freeVerificationFailures;
6457 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6459 int counted = yaffs_CountFreeChunks(dev);
6461 int difference = dev->nFreeChunks - counted;
6464 T(YAFFS_TRACE_ALWAYS,
6465 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6466 dev->nFreeChunks, counted, difference));
6467 yaffs_freeVerificationFailures++;
6471 /*---------------------------------------- YAFFS test code ----------------------*/
6473 #define yaffs_CheckStruct(structure,syze, name) \
6474 if(sizeof(structure) != syze) \
6476 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6477 name,syze,sizeof(structure))); \
6478 return YAFFS_FAIL; \
6481 static int yaffs_CheckStructures(void)
6483 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6484 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6485 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6486 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6487 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6489 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")