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.24 2005-12-07 21:49:18 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
26 #ifdef CONFIG_YAFFS_WINCE
27 void yfsd_LockYAFFS(BOOL fsLockOnly);
28 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
31 #define YAFFS_PASSIVE_GC_CHUNKS 2
33 #include "yaffs_ecc.h"
37 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev,
40 yaffs_ExtendedTags * tags);
41 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
44 yaffs_ExtendedTags * tags);
45 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo);
46 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
48 yaffs_BlockState * state,
49 unsigned *sequenceNumber);
50 /* Robustification (if it ever comes about...) */
51 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
52 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND);
53 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
55 const yaffs_ExtendedTags * tags);
56 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
57 const yaffs_ExtendedTags * tags);
59 /* Other local prototypes */
60 static int yaffs_UnlinkObject( yaffs_Object *obj);
62 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
64 yaffs_ExtendedTags * tags,
66 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
67 int chunkInNAND, int inScan);
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
70 yaffs_ObjectType type);
71 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
73 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
74 int force, int isShrink, int shadows);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
78 int chunkOffset, int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
83 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
84 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
87 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
90 static int yaffs_UnlinkWorker(yaffs_Object * obj);
91 static void yaffs_DestroyObject(yaffs_Object * obj);
93 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
96 loff_t yaffs_GetFileSize(yaffs_Object * obj);
98 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
100 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
113 * Start of real code.
122 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
124 yaffs_ExtendedTags * tags)
126 chunkInNAND -= dev->chunkOffset;
128 if (dev->readChunkWithTagsFromNAND)
129 return dev->readChunkWithTagsFromNAND(dev, chunkInNAND, buffer,
132 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,
138 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
141 yaffs_ExtendedTags * tags)
143 chunkInNAND -= dev->chunkOffset;
146 tags->sequenceNumber = dev->sequenceNumber;
148 if (!yaffs_ValidateTags(tags)) {
150 (TSTR("Writing uninitialised tags" TENDSTR)));
154 (TSTR("Writing chunk %d tags %d %d" TENDSTR), chunkInNAND,
155 tags->objectId, tags->chunkId));
157 T(YAFFS_TRACE_ERROR, (TSTR("Writing with no tags" TENDSTR)));
161 if (dev->writeChunkWithTagsToNAND)
162 return dev->writeChunkWithTagsToNAND(dev, chunkInNAND, buffer,
165 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,
171 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo)
173 blockNo -= dev->blockOffset;
175 if (dev->markNANDBlockBad)
176 return dev->markNANDBlockBad(dev, blockNo);
178 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev, blockNo);
180 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
182 yaffs_BlockState * state,
183 unsigned *sequenceNumber)
185 blockNo -= dev->blockOffset;
187 if (dev->queryNANDBlock)
188 return dev->queryNANDBlock(dev, blockNo, state, sequenceNumber);
190 return yaffs_TagsCompatabilityQueryNANDBlock(dev, blockNo,
195 static int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,
200 blockInNAND -= dev->blockOffset;
202 dev->nBlockErasures++;
203 result = dev->eraseBlockInNAND(dev, blockInNAND);
205 /* If at first we don't succeed, try again *once*.*/
207 result = dev->eraseBlockInNAND(dev, blockInNAND);
211 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
213 return dev->initialiseNAND(dev);
217 * Temporary buffer manipulations.
220 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
223 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
224 if (dev->tempBuffer[i].line == 0) {
225 dev->tempBuffer[i].line = lineNo;
226 if ((i + 1) > dev->maxTemp) {
227 dev->maxTemp = i + 1;
228 for (j = 0; j <= i; j++)
229 dev->tempBuffer[j].maxLine =
230 dev->tempBuffer[j].line;
233 return dev->tempBuffer[i].buffer;
237 T(YAFFS_TRACE_BUFFERS,
238 (TSTR("Out of temp buffers at line %d, other held by lines:"),
240 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
243 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
246 * If we got here then we have to allocate an unmanaged one
250 dev->unmanagedTempAllocations++;
251 return YMALLOC(dev->nBytesPerChunk);
255 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
259 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
260 if (dev->tempBuffer[i].buffer == buffer) {
261 dev->tempBuffer[i].line = 0;
267 /* assume it is an unmanaged one. */
268 T(YAFFS_TRACE_BUFFERS,
269 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
272 dev->unmanagedTempDeallocations++;
278 * Chunk bitmap manipulations
281 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
283 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
285 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
289 return dev->chunkBits +
290 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
293 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
295 __u8 *blkBits = yaffs_BlockBits(dev, blk);
297 memset(blkBits, 0, dev->chunkBitmapStride);
300 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
302 __u8 *blkBits = yaffs_BlockBits(dev, blk);
304 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
307 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
309 __u8 *blkBits = yaffs_BlockBits(dev, blk);
311 blkBits[chunk / 8] |= (1 << (chunk & 7));
314 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
316 __u8 *blkBits = yaffs_BlockBits(dev, blk);
317 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
320 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
322 __u8 *blkBits = yaffs_BlockBits(dev, blk);
324 for (i = 0; i < dev->chunkBitmapStride; i++) {
333 * Simple hash function. Needs to have a reasonable spread
336 static Y_INLINE int yaffs_HashFunction(int n)
338 return (n % YAFFS_NOBJECT_BUCKETS);
342 * Access functions to useful fake objects
345 yaffs_Object *yaffs_Root(yaffs_Device * dev)
350 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
352 return dev->lostNFoundDir;
357 * Erased NAND checking functions
360 int yaffs_CheckFF(__u8 * buffer, int nBytes)
362 /* Horrible, slow implementation */
371 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
375 int retval = YAFFS_OK;
376 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
377 yaffs_ExtendedTags tags;
379 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
381 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
382 T(YAFFS_TRACE_NANDACCESS,
383 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
387 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
393 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
395 yaffs_ExtendedTags * tags,
404 chunk = yaffs_AllocateChunk(dev, useReserve);
408 /* First check this chunk is erased... */
409 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
410 writeOk = yaffs_CheckChunkErased(dev, chunk);
415 ("**>> yaffs chunk %d was not erased"
419 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
426 * Copy the data into the robustification buffer.
427 * NB We do this at the end to prevent duplicates in the case of a write error.
430 yaffs_HandleWriteChunkOk(dev, chunk, data,
433 yaffs_HandleWriteChunkError(dev, chunk);
437 } while (chunk >= 0 && !writeOk);
441 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
443 dev->nRetriedWrites += (attempts - 1);
450 * Block retiring for handling a broken block.
453 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
456 yaffs_MarkBlockBad(dev, blockInNAND);
458 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
459 YAFFS_BLOCK_STATE_DEAD;
461 dev->nRetiredBlocks++;
465 * Functions for robustisizing TODO
469 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
471 const yaffs_ExtendedTags * tags)
475 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
476 const yaffs_ExtendedTags * tags)
480 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
482 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
484 /* Mark the block for retirement */
485 yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
486 /* Delete the chunk */
487 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
491 /*---------------- Name handling functions ------------*/
493 static __u16 yaffs_CalcNameSum(const YCHAR * name)
498 YUCHAR *bname = (YUCHAR *) name;
500 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
502 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
503 sum += yaffs_toupper(*bname) * i;
514 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
516 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
517 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
518 yaffs_strcpy(obj->shortName, name);
520 obj->shortName[0] = _Y('\0');
523 obj->sum = yaffs_CalcNameSum(name);
526 /*-------------------- TNODES -------------------
528 * List of spare tnodes
529 * The list is hooked together using the first pointer
533 /* yaffs_CreateTnodes creates a bunch more tnodes and
534 * adds them to the tnode free list.
535 * Don't use this function directly
538 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
542 yaffs_Tnode *newTnodes;
544 yaffs_Tnode *current;
546 yaffs_TnodeList *tnl;
551 /* Calculate the tnode size in bytes for variable width tnode support.
552 * Must be a multiple of 32-bits */
553 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
555 /* make these things */
557 mem = newTnodes = YMALLOC(nTnodes * tnodeSize);
561 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
565 /* Hook them into the free list */
567 for (i = 0; i < nTnodes - 1; i++) {
568 newTnodes[i].internal[0] = &newTnodes[i + 1];
569 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
570 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
574 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
575 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
576 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
578 dev->freeTnodes = newTnodes;
580 /* New hookup for wide tnodes */
581 for(i = 0; i < nTnodes -1; i++) {
582 current = (yaffs_Tnode *) &mem[i * tnodeSize];
583 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
584 current->internal[0] = next;
587 current = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
588 current->internal[0] = dev->freeTnodes;
589 dev->freeTnodes = (yaffs_Tnode *)mem;
594 dev->nFreeTnodes += nTnodes;
595 dev->nTnodesCreated += nTnodes;
597 /* Now add this bunch of tnodes to a list for freeing up.
598 * NB If we can't add this to the management list it isn't fatal
599 * but it just means we can't free this bunch of tnodes later.
602 tnl = YMALLOC(sizeof(yaffs_TnodeList));
606 ("yaffs: Could not add tnodes to management list" TENDSTR)));
609 tnl->tnodes = newTnodes;
610 tnl->next = dev->allocatedTnodeList;
611 dev->allocatedTnodeList = tnl;
614 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
619 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
621 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
623 yaffs_Tnode *tn = NULL;
625 /* If there are none left make more */
626 if (!dev->freeTnodes) {
627 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
630 if (dev->freeTnodes) {
631 tn = dev->freeTnodes;
632 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
633 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
634 /* Hoosterman, this thing looks like it isn't in the list */
635 T(YAFFS_TRACE_ALWAYS,
636 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
639 dev->freeTnodes = dev->freeTnodes->internal[0];
642 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
648 /* FreeTnode frees up a tnode and puts it back on the free list */
649 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
652 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
653 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
654 /* Hoosterman, this thing looks like it is already in the list */
655 T(YAFFS_TRACE_ALWAYS,
656 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
658 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
660 tn->internal[0] = dev->freeTnodes;
661 dev->freeTnodes = tn;
666 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
668 /* Free the list of allocated tnodes */
669 yaffs_TnodeList *tmp;
671 while (dev->allocatedTnodeList) {
672 tmp = dev->allocatedTnodeList->next;
674 YFREE(dev->allocatedTnodeList->tnodes);
675 YFREE(dev->allocatedTnodeList);
676 dev->allocatedTnodeList = tmp;
680 dev->freeTnodes = NULL;
681 dev->nFreeTnodes = 0;
684 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
686 dev->allocatedTnodeList = NULL;
687 dev->freeTnodes = NULL;
688 dev->nFreeTnodes = 0;
689 dev->nTnodesCreated = 0;
694 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
696 __u32 *map = (__u32 *)tn;
702 pos &= YAFFS_TNODES_LEVEL0_MASK;
703 val >>= dev->chunkGroupBits;
705 bitInMap = pos * dev->tnodeWidth;
706 wordInMap = bitInMap /32;
707 bitInWord = bitInMap & (32 -1);
709 mask = dev->tnodeMask << bitInWord;
711 map[wordInMap] &= ~mask;
712 map[wordInMap] |= (mask & (val << bitInWord));
714 if(dev->tnodeWidth > (32-bitInWord)) {
715 bitInWord = (32 - bitInWord);
717 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
718 map[wordInMap] &= ~mask;
719 map[wordInMap] |= (mask & (val >> bitInWord));
723 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
725 __u32 *map = (__u32 *)tn;
731 pos &= YAFFS_TNODES_LEVEL0_MASK;
733 bitInMap = pos * dev->tnodeWidth;
734 wordInMap = bitInMap /32;
735 bitInWord = bitInMap & (32 -1);
737 val = map[wordInMap] >> bitInWord;
739 if(dev->tnodeWidth > (32-bitInWord)) {
740 bitInWord = (32 - bitInWord);
742 val |= (map[wordInMap] << bitInWord);
745 val &= dev->tnodeMask;
746 val <<= dev->chunkGroupBits;
751 /* ------------------- End of individual tnode manipulation -----------------*/
753 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
754 * The look up tree is represented by the top tnode and the number of topLevel
755 * in the tree. 0 means only the level 0 tnode is in the tree.
758 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
759 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
760 yaffs_FileStructure * fStruct,
764 yaffs_Tnode *tn = fStruct->top;
766 int requiredTallness;
767 int level = fStruct->topLevel;
769 /* Check sane level and chunk Id */
770 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
774 if (chunkId > YAFFS_MAX_CHUNK_ID) {
778 /* First check we're tall enough (ie enough topLevel) */
780 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
781 requiredTallness = 0;
783 i >>= YAFFS_TNODES_INTERNAL_BITS;
787 if (requiredTallness > fStruct->topLevel) {
788 /* Not tall enough, so we can't find it, return NULL. */
792 /* Traverse down to level 0 */
793 while (level > 0 && tn) {
796 ( YAFFS_TNODES_LEVEL0_BITS +
798 YAFFS_TNODES_INTERNAL_BITS)
800 YAFFS_TNODES_INTERNAL_MASK];
808 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
809 * This happens in two steps:
810 * 1. If the tree isn't tall enough, then make it taller.
811 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
813 * Used when modifying the tree.
816 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
817 yaffs_FileStructure * fStruct,
823 int requiredTallness;
830 /* Check sane level and page Id */
831 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
835 if (chunkId > YAFFS_MAX_CHUNK_ID) {
839 /* First check we're tall enough (ie enough topLevel) */
841 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
842 requiredTallness = 0;
844 x >>= YAFFS_TNODES_INTERNAL_BITS;
849 if (requiredTallness > fStruct->topLevel) {
850 /* Not tall enough,gotta make the tree taller */
851 for (i = fStruct->topLevel; i < requiredTallness; i++) {
853 tn = yaffs_GetTnode(dev);
856 tn->internal[0] = fStruct->top;
860 (TSTR("yaffs: no more tnodes" TENDSTR)));
864 fStruct->topLevel = requiredTallness;
867 /* Traverse down to level 0, adding anything we need */
869 l = fStruct->topLevel;
871 while (l > 0 && tn) {
873 ( YAFFS_TNODES_LEVEL0_BITS +
874 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
875 YAFFS_TNODES_INTERNAL_MASK;
878 if (!tn->internal[x])
879 tn->internal[x] = yaffs_GetTnode(dev);
881 tn = tn->internal[x];
889 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
890 yaffs_ExtendedTags * tags, int objectId,
895 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
896 if (yaffs_CheckChunkBit
897 (dev, theChunk / dev->nChunksPerBlock,
898 theChunk % dev->nChunksPerBlock)) {
899 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
901 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
913 /* DeleteWorker scans backwards through the tnode tree and deletes all the
914 * chunks and tnodes in the file
915 * Returns 1 if the tree was deleted.
916 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
919 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
920 int chunkOffset, int *limit)
925 yaffs_ExtendedTags tags;
927 yaffs_Device *dev = in->myDev;
934 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
936 if (tn->internal[i]) {
937 if (limit && (*limit) < 0) {
941 yaffs_DeleteWorker(in,
949 YAFFS_TNODES_INTERNAL_BITS)
957 tn->internal[i] = NULL;
962 return (allDone) ? 1 : 0;
963 } else if (level == 0) {
966 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
968 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
973 YAFFS_TNODES_LEVEL0_BITS) + i;
976 yaffs_FindChunkInGroup(dev,
982 if (foundChunk > 0) {
983 yaffs_DeleteChunk(dev,
996 yaffs_PutLevel0Tnode(dev,tn,i,0);
1000 return (i < 0) ? 1 : 0;
1010 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1013 yaffs_BlockInfo *theBlock;
1015 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1017 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1019 theBlock->softDeletions++;
1024 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1025 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1027 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1030 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1031 __u32 level, int chunkOffset)
1036 yaffs_Device *dev = in->myDev;
1041 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1043 if (tn->internal[i]) {
1045 yaffs_SoftDeleteWorker(in,
1051 YAFFS_TNODES_INTERNAL_BITS)
1054 yaffs_FreeTnode(dev,
1057 tn->internal[i] = NULL;
1059 /* Hoosterman... how could this happen? */
1063 return (allDone) ? 1 : 0;
1064 } else if (level == 0) {
1066 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1067 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1069 /* Note this does not find the real chunk, only the chunk group.
1070 * We make an assumption that a chunk group is not larger than
1073 yaffs_SoftDeleteChunk(dev, theChunk);
1074 yaffs_PutLevel0Tnode(dev,tn,i,0);
1088 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1091 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1092 if (obj->nDataChunks <= 0) {
1093 /* Empty file with no duplicate object headers, just delete it immediately */
1094 yaffs_FreeTnode(obj->myDev,
1095 obj->variant.fileVariant.top);
1096 obj->variant.fileVariant.top = NULL;
1097 T(YAFFS_TRACE_TRACING,
1098 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1100 yaffs_DoGenericObjectDeletion(obj);
1102 yaffs_SoftDeleteWorker(obj,
1103 obj->variant.fileVariant.top,
1104 obj->variant.fileVariant.
1106 obj->softDeleted = 1;
1111 /* Pruning removes any part of the file structure tree that is beyond the
1112 * bounds of the file (ie that does not point to chunks).
1114 * A file should only get pruned when its size is reduced.
1116 * Before pruning, the chunks must be pulled from the tree and the
1117 * level 0 tnode entries must be zeroed out.
1118 * Could also use this for file deletion, but that's probably better handled
1119 * by a special case.
1122 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1123 __u32 level, int del0)
1131 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1132 if (tn->internal[i] && level > 0) {
1134 yaffs_PruneWorker(dev, tn->internal[i],
1136 (i == 0) ? del0 : 1);
1139 if (tn->internal[i]) {
1144 if (hasData == 0 && del0) {
1145 /* Free and return NULL */
1147 yaffs_FreeTnode(dev, tn);
1157 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1158 yaffs_FileStructure * fStruct)
1165 if (fStruct->topLevel > 0) {
1167 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1169 /* Now we have a tree with all the non-zero branches NULL but the height
1170 * is the same as it was.
1171 * Let's see if we can trim internal tnodes to shorten the tree.
1172 * We can do this if only the 0th element in the tnode is in use
1173 * (ie all the non-zero are NULL)
1176 while (fStruct->topLevel && !done) {
1180 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1181 if (tn->internal[i]) {
1187 fStruct->top = tn->internal[0];
1188 fStruct->topLevel--;
1189 yaffs_FreeTnode(dev, tn);
1199 /*-------------------- End of File Structure functions.-------------------*/
1201 /* yaffs_CreateFreeObjects creates a bunch more objects and
1202 * adds them to the object free list.
1204 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1207 yaffs_Object *newObjects;
1208 yaffs_ObjectList *list;
1213 /* make these things */
1214 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1217 T(YAFFS_TRACE_ALLOCATE,
1218 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1222 /* Hook them into the free list */
1223 for (i = 0; i < nObjects - 1; i++) {
1224 newObjects[i].siblings.next =
1225 (struct list_head *)(&newObjects[i + 1]);
1228 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1229 dev->freeObjects = newObjects;
1230 dev->nFreeObjects += nObjects;
1231 dev->nObjectsCreated += nObjects;
1233 /* Now add this bunch of Objects to a list for freeing up. */
1235 list = YMALLOC(sizeof(yaffs_ObjectList));
1237 T(YAFFS_TRACE_ALLOCATE,
1238 (TSTR("Could not add objects to management list" TENDSTR)));
1240 list->objects = newObjects;
1241 list->next = dev->allocatedObjectList;
1242 dev->allocatedObjectList = list;
1249 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1250 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1252 yaffs_Object *tn = NULL;
1254 /* If there are none left make more */
1255 if (!dev->freeObjects) {
1256 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1259 if (dev->freeObjects) {
1260 tn = dev->freeObjects;
1262 (yaffs_Object *) (dev->freeObjects->siblings.next);
1263 dev->nFreeObjects--;
1265 /* Now sweeten it up... */
1267 memset(tn, 0, sizeof(yaffs_Object));
1270 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1271 INIT_LIST_HEAD(&(tn->hardLinks));
1272 INIT_LIST_HEAD(&(tn->hashLink));
1273 INIT_LIST_HEAD(&tn->siblings);
1275 /* Add it to the lost and found directory.
1276 * NB Can't put root or lostNFound in lostNFound so
1277 * check if lostNFound exists first
1279 if (dev->lostNFoundDir) {
1280 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1287 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1292 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1294 obj->fake = 1; /* it is fake so it has no NAND presence... */
1295 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1296 obj->unlinkAllowed = 0; /* ... or unlink it */
1299 obj->yst_mode = mode;
1301 obj->chunkId = 0; /* Not a valid chunk. */
1308 static void yaffs_UnhashObject(yaffs_Object * tn)
1311 yaffs_Device *dev = tn->myDev;
1313 /* If it is still linked into the bucket list, free from the list */
1314 if (!list_empty(&tn->hashLink)) {
1315 list_del_init(&tn->hashLink);
1316 bucket = yaffs_HashFunction(tn->objectId);
1317 dev->objectBucket[bucket].count--;
1322 /* FreeObject frees up a Object and puts it back on the free list */
1323 static void yaffs_FreeObject(yaffs_Object * tn)
1326 yaffs_Device *dev = tn->myDev;
1330 /* We're still hooked up to a cached inode.
1331 * Don't delete now, but mark for later deletion
1333 tn->deferedFree = 1;
1338 yaffs_UnhashObject(tn);
1340 /* Link into the free list. */
1341 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1342 dev->freeObjects = tn;
1343 dev->nFreeObjects++;
1348 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1350 if (obj->deferedFree) {
1351 yaffs_FreeObject(obj);
1357 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1359 /* Free the list of allocated Objects */
1361 yaffs_ObjectList *tmp;
1363 while (dev->allocatedObjectList) {
1364 tmp = dev->allocatedObjectList->next;
1365 YFREE(dev->allocatedObjectList->objects);
1366 YFREE(dev->allocatedObjectList);
1368 dev->allocatedObjectList = tmp;
1371 dev->freeObjects = NULL;
1372 dev->nFreeObjects = 0;
1375 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1379 dev->allocatedObjectList = NULL;
1380 dev->freeObjects = NULL;
1381 dev->nFreeObjects = 0;
1383 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1384 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1385 dev->objectBucket[i].count = 0;
1390 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1395 int lowest = 999999;
1397 /* First let's see if we can find one that's empty. */
1399 for (i = 0; i < 10 && lowest > 0; i++) {
1401 x %= YAFFS_NOBJECT_BUCKETS;
1402 if (dev->objectBucket[x].count < lowest) {
1403 lowest = dev->objectBucket[x].count;
1409 /* If we didn't find an empty list, then try
1410 * looking a bit further for a short one
1413 for (i = 0; i < 10 && lowest > 3; i++) {
1415 x %= YAFFS_NOBJECT_BUCKETS;
1416 if (dev->objectBucket[x].count < lowest) {
1417 lowest = dev->objectBucket[x].count;
1426 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1428 int bucket = yaffs_FindNiceObjectBucket(dev);
1430 /* Now find an object value that has not already been taken
1431 * by scanning the list.
1435 struct list_head *i;
1437 __u32 n = (__u32) bucket;
1439 /* yaffs_CheckObjectHashSanity(); */
1443 n += YAFFS_NOBJECT_BUCKETS;
1444 if (1 || dev->objectBucket[bucket].count > 0) {
1445 list_for_each(i, &dev->objectBucket[bucket].list) {
1446 /* If there is already one in the list */
1448 && list_entry(i, yaffs_Object,
1449 hashLink)->objectId == n) {
1460 static void yaffs_HashObject(yaffs_Object * in)
1462 int bucket = yaffs_HashFunction(in->objectId);
1463 yaffs_Device *dev = in->myDev;
1465 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1466 dev->objectBucket[bucket].count++;
1470 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1472 int bucket = yaffs_HashFunction(number);
1473 struct list_head *i;
1476 list_for_each(i, &dev->objectBucket[bucket].list) {
1477 /* Look if it is in the list */
1479 in = list_entry(i, yaffs_Object, hashLink);
1480 if (in->objectId == number) {
1482 /* Don't tell the VFS about this one if it is defered free */
1483 if (in->deferedFree)
1495 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1496 yaffs_ObjectType type)
1499 yaffs_Object *theObject;
1502 number = yaffs_CreateNewObjectNumber(dev);
1505 theObject = yaffs_AllocateEmptyObject(dev);
1508 theObject->fake = 0;
1509 theObject->renameAllowed = 1;
1510 theObject->unlinkAllowed = 1;
1511 theObject->objectId = number;
1512 yaffs_HashObject(theObject);
1513 theObject->variantType = type;
1514 #ifdef CONFIG_YAFFS_WINCE
1515 yfsd_WinFileTimeNow(theObject->win_atime);
1516 theObject->win_ctime[0] = theObject->win_mtime[0] =
1517 theObject->win_atime[0];
1518 theObject->win_ctime[1] = theObject->win_mtime[1] =
1519 theObject->win_atime[1];
1523 theObject->yst_atime = theObject->yst_mtime =
1524 theObject->yst_ctime = Y_CURRENT_TIME;
1527 case YAFFS_OBJECT_TYPE_FILE:
1528 theObject->variant.fileVariant.fileSize = 0;
1529 theObject->variant.fileVariant.scannedFileSize = 0;
1530 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1531 theObject->variant.fileVariant.topLevel = 0;
1532 theObject->variant.fileVariant.top =
1533 yaffs_GetTnode(dev);
1535 case YAFFS_OBJECT_TYPE_DIRECTORY:
1536 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1539 case YAFFS_OBJECT_TYPE_SYMLINK:
1540 case YAFFS_OBJECT_TYPE_HARDLINK:
1541 case YAFFS_OBJECT_TYPE_SPECIAL:
1542 /* No action required */
1544 case YAFFS_OBJECT_TYPE_UNKNOWN:
1545 /* todo this should not happen */
1553 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1555 yaffs_ObjectType type)
1557 yaffs_Object *theObject = NULL;
1560 theObject = yaffs_FindObjectByNumber(dev, number);
1564 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);
1794 if (obj && obj->renameAllowed) {
1796 /* Now do the handling for an existing target, if there is one */
1798 existingTarget = yaffs_FindObjectByName(newDir, newName);
1799 if (existingTarget &&
1800 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1801 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1802 /* There is a target that is a non-empty directory, so we fail */
1803 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1804 } else if (existingTarget && existingTarget != obj) {
1805 /* Nuke the target first, using shadowing,
1806 * but only if it isn't the same object
1808 yaffs_ChangeObjectName(obj, newDir, newName, force,
1809 existingTarget->objectId);
1810 yaffs_UnlinkObject(existingTarget);
1813 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1818 /*------------------------- Block Management and Page Allocation ----------------*/
1820 static int yaffs_InitialiseBlocks(yaffs_Device * dev, int nBlocks)
1822 dev->allocationBlock = -1; /* force it to get a new one */
1824 /* Todo we're assuming the malloc will pass. */
1825 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1826 if(!dev->blockInfo){
1827 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1828 dev->blockInfoAlt = 1;
1831 dev->blockInfoAlt = 0;
1833 /* Set up dynamic blockinfo stuff. */
1834 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8;
1835 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1836 if(!dev->chunkBits){
1837 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1838 dev->chunkBitsAlt = 1;
1841 dev->chunkBitsAlt = 0;
1843 if (dev->blockInfo && dev->chunkBits) {
1844 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1845 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1853 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1855 if(dev->blockInfoAlt)
1856 YFREE_ALT(dev->blockInfo);
1858 YFREE(dev->blockInfo);
1859 dev->blockInfoAlt = 0;
1861 dev->blockInfo = NULL;
1863 if(dev->chunkBitsAlt)
1864 YFREE_ALT(dev->chunkBits);
1866 YFREE(dev->chunkBits);
1867 dev->chunkBitsAlt = 0;
1868 dev->chunkBits = NULL;
1871 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1872 yaffs_BlockInfo * bi)
1879 return 1; /* disqualification only applies to yaffs2. */
1881 if (!bi->hasShrinkHeader)
1882 return 1; /* can gc */
1884 /* Find the oldest dirty sequence number if we don't know it and save it
1885 * so we don't have to keep recomputing it.
1887 if (!dev->oldestDirtySequence) {
1888 seq = dev->sequenceNumber;
1890 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1892 b = yaffs_GetBlockInfo(dev, i);
1893 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1894 (b->pagesInUse - b->softDeletions) <
1895 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1896 seq = b->sequenceNumber;
1899 dev->oldestDirtySequence = seq;
1902 /* Can't do gc of this block if there are any blocks older than this one that have
1905 return (bi->sequenceNumber <= dev->oldestDirtySequence);
1911 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1912 * for garbage collection.
1915 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1919 int b = dev->currentDirtyChecker;
1925 yaffs_BlockInfo *bi;
1926 static int nonAggressiveSkip = 0;
1928 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1930 * else (we're doing a leasurely gc), then we only bother to do this if the
1931 * block has only a few pages in use.
1934 nonAggressiveSkip--;
1936 if (!aggressive && (nonAggressiveSkip > 0)) {
1941 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1945 dev->internalEndBlock - dev->internalStartBlock + 1;
1948 dev->internalEndBlock - dev->internalStartBlock + 1;
1949 iterations = iterations / 16;
1950 if (iterations > 200) {
1955 for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1957 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1958 b = dev->internalStartBlock;
1961 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1962 T(YAFFS_TRACE_ERROR,
1963 (TSTR("**>> Block %d is not valid" TENDSTR), b));
1967 bi = yaffs_GetBlockInfo(dev, b);
1969 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1970 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1971 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1973 pagesInUse = (bi->pagesInUse - bi->softDeletions);
1977 dev->currentDirtyChecker = b;
1981 (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1982 dev->nChunksPerBlock - pagesInUse));
1985 dev->oldestDirtySequence = 0;
1988 nonAggressiveSkip = 4;
1994 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1996 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2000 /* If the block is still healthy erase it and mark as clean.
2001 * If the block has had a data failure, then retire it.
2003 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2005 if (!bi->needsRetiring) {
2006 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2008 dev->nErasureFailures++;
2009 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2010 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2014 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2016 for (i = 0; i < dev->nChunksPerBlock; i++) {
2017 if (!yaffs_CheckChunkErased
2018 (dev, blockNo * dev->nChunksPerBlock + i)) {
2019 T(YAFFS_TRACE_ERROR,
2021 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2022 TENDSTR), blockNo, i));
2028 /* Clean it up... */
2029 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2030 dev->nErasedBlocks++;
2032 bi->softDeletions = 0;
2033 bi->hasShrinkHeader = 0;
2034 yaffs_ClearChunkBits(dev, blockNo);
2036 T(YAFFS_TRACE_ERASE,
2037 (TSTR("Erased block %d" TENDSTR), blockNo));
2039 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2041 yaffs_RetireBlock(dev, blockNo);
2042 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2043 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2047 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2051 yaffs_BlockInfo *bi;
2053 if (dev->nErasedBlocks < 1) {
2054 /* Hoosterman we've got a problem.
2055 * Can't get space to gc
2057 T(YAFFS_TRACE_ERROR,
2058 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2063 /* Find an empty block. */
2065 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2066 dev->allocationBlockFinder++;
2067 if (dev->allocationBlockFinder < dev->internalStartBlock
2068 || dev->allocationBlockFinder > dev->internalEndBlock) {
2069 dev->allocationBlockFinder = dev->internalStartBlock;
2072 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2074 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2075 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2076 dev->sequenceNumber++;
2077 bi->sequenceNumber = dev->sequenceNumber;
2078 dev->nErasedBlocks--;
2079 T(YAFFS_TRACE_ALLOCATE,
2080 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2081 dev->allocationBlockFinder, dev->sequenceNumber,
2082 dev->nErasedBlocks));
2083 return dev->allocationBlockFinder;
2087 T(YAFFS_TRACE_ALWAYS,
2089 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2090 TENDSTR), dev->nErasedBlocks));
2097 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2099 int reservedChunks = (dev->nReservedBlocks * dev->nChunksPerBlock);
2100 return (dev->nFreeChunks > reservedChunks);
2103 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2106 yaffs_BlockInfo *bi;
2108 if (dev->allocationBlock < 0) {
2109 /* Get next block to allocate off */
2110 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2111 dev->allocationPage = 0;
2114 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2115 /* Not enough space to allocate unless we're allowed to use the reserve. */
2119 if (dev->nErasedBlocks < dev->nReservedBlocks
2120 && dev->allocationPage == 0) {
2121 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2124 /* Next page please.... */
2125 if (dev->allocationBlock >= 0) {
2126 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2128 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2129 dev->allocationPage;
2131 yaffs_SetChunkBit(dev, dev->allocationBlock,
2132 dev->allocationPage);
2134 dev->allocationPage++;
2138 /* If the block is full set the state to full */
2139 if (dev->allocationPage >= dev->nChunksPerBlock) {
2140 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2141 dev->allocationBlock = -1;
2147 T(YAFFS_TRACE_ERROR,
2148 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2153 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2157 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2159 if (dev->allocationBlock > 0) {
2160 n += (dev->nChunksPerBlock - dev->allocationPage);
2167 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2173 int retVal = YAFFS_OK;
2177 int chunksBefore = yaffs_GetErasedChunks(dev);
2180 yaffs_ExtendedTags tags;
2182 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2184 yaffs_Object *object;
2186 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2188 T(YAFFS_TRACE_TRACING,
2189 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2190 bi->pagesInUse, bi->hasShrinkHeader));
2192 /*yaffs_VerifyFreeChunks(dev); */
2194 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2196 /* Take off the number of soft deleted entries because
2197 * they're going to get really deleted during GC.
2199 dev->nFreeChunks -= bi->softDeletions;
2203 if (!yaffs_StillSomeChunkBits(dev, block)) {
2204 T(YAFFS_TRACE_TRACING,
2206 ("Collecting block %d that has no chunks in use" TENDSTR),
2208 yaffs_BlockBecameDirty(dev, block);
2211 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2213 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2214 chunkInBlock < dev->nChunksPerBlock
2215 && yaffs_StillSomeChunkBits(dev, block);
2216 chunkInBlock++, oldChunk++) {
2217 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2219 /* This page is in use and might need to be copied off */
2223 yaffs_InitialiseTags(&tags);
2225 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2229 yaffs_FindObjectByNumber(dev,
2232 T(YAFFS_TRACE_GC_DETAIL,
2234 ("Collecting page %d, %d %d %d " TENDSTR),
2235 chunkInBlock, tags.objectId, tags.chunkId,
2239 T(YAFFS_TRACE_ERROR,
2241 ("page %d in gc has no object "
2242 TENDSTR), oldChunk));
2245 if (object && object->deleted
2246 && tags.chunkId != 0) {
2247 /* Data chunk in a deleted file, throw it away
2248 * It's a soft deleted data chunk,
2249 * No need to copy this, just forget about it and
2250 * fix up the object.
2253 object->nDataChunks--;
2255 if (object->nDataChunks <= 0) {
2256 /* remeber to clean up the object */
2257 dev->gcCleanupList[cleanups] =
2263 /* Todo object && object->deleted && object->nDataChunks == 0 */
2265 /* Deleted object header with no data chunks.
2266 * Can be discarded and the file deleted.
2268 object->chunkId = 0;
2269 yaffs_FreeTnode(object->myDev,
2272 object->variant.fileVariant.top = NULL;
2273 yaffs_DoGenericObjectDeletion(object);
2275 } else if (object) {
2276 /* It's either a data chunk in a live file or
2277 * an ObjectHeader, so we're interested in it.
2278 * NB Need to keep the ObjectHeaders of deleted files
2279 * until the whole file has been deleted off
2281 tags.serialNumber++;
2285 if (tags.chunkId == 0) {
2286 /* It is an object Id,
2287 * We need to nuke the shrinkheader flags first
2288 * We no longer want the shrinkHeader flag since its work is done
2289 * and if it is left in place it will mess up scanning.
2290 * Also, clear out any shadowing stuff
2293 yaffs_ObjectHeader *oh;
2294 oh = (yaffs_ObjectHeader *)buffer;
2296 oh->shadowsObject = -1;
2297 tags.extraShadows = 0;
2298 tags.extraIsShrinkHeader = 0;
2302 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2305 retVal = YAFFS_FAIL;
2308 /* Ok, now fix up the Tnodes etc. */
2310 if (tags.chunkId == 0) {
2312 object->chunkId = newChunk;
2313 object->serial = tags.serialNumber;
2315 /* It's a data chunk */
2316 yaffs_PutChunkIntoFile
2324 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2329 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2332 /* Do any required cleanups */
2333 for (i = 0; i < cleanups; i++) {
2334 /* Time to delete the file too */
2336 yaffs_FindObjectByNumber(dev,
2337 dev->gcCleanupList[i]);
2339 yaffs_FreeTnode(dev,
2340 object->variant.fileVariant.
2342 object->variant.fileVariant.top = NULL;
2345 ("yaffs: About to finally delete object %d"
2346 TENDSTR), object->objectId));
2347 yaffs_DoGenericObjectDeletion(object);
2354 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2357 ("gc did not increase free chunks before %d after %d"
2358 TENDSTR), chunksBefore, chunksAfter));
2366 /* New garbage collector
2367 * If we're very low on erased blocks then we do aggressive garbage collection
2368 * otherwise we do "leasurely" garbage collection.
2369 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2370 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2372 * The idea is to help clear out space in a more spread-out manner.
2373 * Dunno if it really does anything useful.
2375 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2379 int gcOk = YAFFS_OK;
2382 if (dev->isDoingGC) {
2383 /* Bail out so we don't get recursive gc */
2387 /* This loop should pass the first time.
2388 * We'll only see looping here if the erase of the collected block fails.
2393 if (dev->nErasedBlocks < dev->nReservedBlocks) {
2394 /* We need a block soon...*/
2397 /* We're in no hurry */
2401 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2404 dev->garbageCollections++;
2406 dev->passiveGarbageCollections++;
2411 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2412 dev->nErasedBlocks, aggressive));
2414 gcOk = yaffs_GarbageCollectBlock(dev, block);
2417 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2420 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2421 TENDSTR), dev->nErasedBlocks, maxTries, block));
2423 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2426 return aggressive ? gcOk : YAFFS_OK;
2429 /*------------------------- TAGS --------------------------------*/
2431 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2434 return (tags->chunkId == chunkInObject &&
2435 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2440 /*-------------------- Data file manipulation -----------------*/
2442 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2443 yaffs_ExtendedTags * tags)
2445 /*Get the Tnode, then get the level 0 offset chunk offset */
2448 yaffs_ExtendedTags localTags;
2451 yaffs_Device *dev = in->myDev;
2454 /* Passed a NULL, so use our own tags space */
2458 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2461 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2464 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2470 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2471 yaffs_ExtendedTags * tags)
2473 /* Get the Tnode, then get the level 0 offset chunk offset */
2476 yaffs_ExtendedTags localTags;
2478 yaffs_Device *dev = in->myDev;
2482 /* Passed a NULL, so use our own tags space */
2486 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2490 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2493 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2496 /* Delete the entry in the filestructure (if found) */
2498 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2501 /*T(("No level 0 found for %d\n", chunkInInode)); */
2505 /* T(("Could not find %d to delete\n",chunkInInode)); */
2510 #ifdef YAFFS_PARANOID
2512 static int yaffs_CheckFileSanity(yaffs_Object * in)
2520 yaffs_Tags localTags;
2521 yaffs_Tags *tags = &localTags;
2525 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2526 /* T(("Object not a file\n")); */
2530 objId = in->objectId;
2531 fSize = in->variant.fileVariant.fileSize;
2533 (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2535 for (chunk = 1; chunk <= nChunks; chunk++) {
2536 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2541 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2543 if (yaffs_CheckChunkBits
2544 (dev, theChunk / dev->nChunksPerBlock,
2545 theChunk % dev->nChunksPerBlock)) {
2547 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2551 (tags, in->objectId, chunk, chunkDeleted)) {
2561 /* T(("No level 0 found for %d\n", chunk)); */
2565 return failed ? YAFFS_FAIL : YAFFS_OK;
2570 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2571 int chunkInNAND, int inScan)
2573 /* NB inScan is zero unless scanning.
2574 * For forward scanning, inScan is > 0;
2575 * for backward scanning inScan is < 0
2579 yaffs_Device *dev = in->myDev;
2581 yaffs_ExtendedTags existingTags;
2582 yaffs_ExtendedTags newTags;
2583 unsigned existingSerial, newSerial;
2585 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2586 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2587 * If it is not during Scanning then something went wrong!
2590 T(YAFFS_TRACE_ERROR,
2592 ("yaffs tragedy:attempt to put data chunk into a non-file"
2597 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2601 tn = yaffs_AddOrFindLevel0Tnode(dev, &in->variant.fileVariant,
2607 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2610 /* If we're scanning then we need to test for duplicates
2611 * NB This does not need to be efficient since it should only ever
2612 * happen when the power fails during a write, then only one
2613 * chunk should ever be affected.
2615 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2616 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2619 if (existingChunk != 0) {
2620 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2621 * thus we have to do a FindChunkInFile to get the real chunk id.
2623 * We have a duplicate now we need to decide which one to use:
2625 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2626 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2627 * YAFFS1: Get both sets of tags and compare serial numbers.
2631 /* Only do this for forward scanning */
2632 yaffs_ReadChunkWithTagsFromNAND(dev,
2636 /* Do a proper find */
2638 yaffs_FindChunkInFile(in, chunkInInode,
2642 if (existingChunk <= 0) {
2643 /*Hoosterman - how did this happen? */
2645 T(YAFFS_TRACE_ERROR,
2647 ("yaffs tragedy: existing chunk < 0 in scan"
2652 /* NB The deleted flags should be false, otherwise the chunks will
2653 * not be loaded during a scan
2656 newSerial = newTags.serialNumber;
2657 existingSerial = existingTags.serialNumber;
2660 (in->myDev->isYaffs2 ||
2661 existingChunk <= 0 ||
2662 ((existingSerial + 1) & 3) == newSerial)) {
2663 /* Forward scanning.
2665 * Delete the old one and drop through to update the tnode
2667 yaffs_DeleteChunk(dev, existingChunk, 1,
2670 /* Backward scanning or we want to use the existing one
2672 * Delete the new one and return early so that the tnode isn't changed
2674 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2682 if (existingChunk == 0) {
2686 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2691 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2694 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2696 if (chunkInNAND >= 0) {
2697 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2700 T(YAFFS_TRACE_NANDACCESS,
2701 (TSTR("Chunk %d not found zero instead" TENDSTR),
2703 /* get sane (zero) data if you read a hole */
2704 memset(buffer, 0, in->myDev->nBytesPerChunk);
2710 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2714 yaffs_ExtendedTags tags;
2715 yaffs_BlockInfo *bi;
2721 block = chunkId / dev->nChunksPerBlock;
2722 page = chunkId % dev->nChunksPerBlock;
2724 bi = yaffs_GetBlockInfo(dev, block);
2726 T(YAFFS_TRACE_DELETION,
2727 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2730 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2732 yaffs_InitialiseTags(&tags);
2734 tags.chunkDeleted = 1;
2736 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2737 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2739 dev->nUnmarkedDeletions++;
2742 /* Pull out of the management area.
2743 * If the whole block became dirty, this will kick off an erasure.
2745 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2746 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2747 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2748 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2751 yaffs_ClearChunkBit(dev, block, page);
2755 if (bi->pagesInUse == 0 &&
2756 !bi->hasShrinkHeader &&
2757 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2758 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2759 yaffs_BlockBecameDirty(dev, block);
2763 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2768 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2769 const __u8 * buffer, int nBytes,
2772 /* Find old chunk Need to do this to get serial number
2773 * Write new one and patch into tree.
2774 * Invalidate old tags.
2778 yaffs_ExtendedTags prevTags;
2781 yaffs_ExtendedTags newTags;
2783 yaffs_Device *dev = in->myDev;
2785 yaffs_CheckGarbageCollection(dev);
2787 /* Get the previous chunk at this location in the file if it exists */
2788 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2790 /* Set up new tags */
2791 yaffs_InitialiseTags(&newTags);
2793 newTags.chunkId = chunkInInode;
2794 newTags.objectId = in->objectId;
2795 newTags.serialNumber =
2796 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2797 newTags.byteCount = nBytes;
2800 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2803 if (newChunkId >= 0) {
2804 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2806 if (prevChunkId >= 0) {
2807 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2811 yaffs_CheckFileSanity(in);
2817 /* UpdateObjectHeader updates the header on NAND for an object.
2818 * If name is not NULL, then that new name is used.
2820 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2821 int isShrink, int shadows)
2824 yaffs_BlockInfo *bi;
2826 yaffs_Device *dev = in->myDev;
2832 yaffs_ExtendedTags newTags;
2834 __u8 *buffer = NULL;
2835 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2837 yaffs_ObjectHeader *oh = NULL;
2839 if (!in->fake || force) {
2841 yaffs_CheckGarbageCollection(dev);
2843 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2844 oh = (yaffs_ObjectHeader *) buffer;
2846 prevChunkId = in->chunkId;
2848 if (prevChunkId >= 0) {
2849 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2851 memcpy(oldName, oh->name, sizeof(oh->name));
2854 memset(buffer, 0xFF, dev->nBytesPerChunk);
2856 oh->type = in->variantType;
2857 oh->yst_mode = in->yst_mode;
2858 oh->shadowsObject = shadows;
2860 #ifdef CONFIG_YAFFS_WINCE
2861 oh->win_atime[0] = in->win_atime[0];
2862 oh->win_ctime[0] = in->win_ctime[0];
2863 oh->win_mtime[0] = in->win_mtime[0];
2864 oh->win_atime[1] = in->win_atime[1];
2865 oh->win_ctime[1] = in->win_ctime[1];
2866 oh->win_mtime[1] = in->win_mtime[1];
2868 oh->yst_uid = in->yst_uid;
2869 oh->yst_gid = in->yst_gid;
2870 oh->yst_atime = in->yst_atime;
2871 oh->yst_mtime = in->yst_mtime;
2872 oh->yst_ctime = in->yst_ctime;
2873 oh->yst_rdev = in->yst_rdev;
2876 oh->parentObjectId = in->parent->objectId;
2878 oh->parentObjectId = 0;
2881 if (name && *name) {
2882 memset(oh->name, 0, sizeof(oh->name));
2883 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2884 } else if (prevChunkId) {
2885 memcpy(oh->name, oldName, sizeof(oh->name));
2887 memset(oh->name, 0, sizeof(oh->name));
2890 oh->isShrink = isShrink;
2892 switch (in->variantType) {
2893 case YAFFS_OBJECT_TYPE_UNKNOWN:
2894 /* Should not happen */
2896 case YAFFS_OBJECT_TYPE_FILE:
2898 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2899 || oh->parentObjectId ==
2900 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2901 fileVariant.fileSize;
2903 case YAFFS_OBJECT_TYPE_HARDLINK:
2904 oh->equivalentObjectId =
2905 in->variant.hardLinkVariant.equivalentObjectId;
2907 case YAFFS_OBJECT_TYPE_SPECIAL:
2910 case YAFFS_OBJECT_TYPE_DIRECTORY:
2913 case YAFFS_OBJECT_TYPE_SYMLINK:
2914 yaffs_strncpy(oh->alias,
2915 in->variant.symLinkVariant.alias,
2916 YAFFS_MAX_ALIAS_LENGTH);
2917 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2922 yaffs_InitialiseTags(&newTags);
2924 newTags.chunkId = 0;
2925 newTags.objectId = in->objectId;
2926 newTags.serialNumber = in->serial;
2928 /* Add extra info for file header */
2930 newTags.extraHeaderInfoAvailable = 1;
2931 newTags.extraParentObjectId = oh->parentObjectId;
2932 newTags.extraFileLength = oh->fileSize;
2933 newTags.extraIsShrinkHeader = oh->isShrink;
2934 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2935 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2936 newTags.extraObjectType = in->variantType;
2938 /* Create new chunk in NAND */
2940 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2941 (prevChunkId >= 0) ? 1 : 0);
2943 if (newChunkId >= 0) {
2945 in->chunkId = newChunkId;
2947 if (prevChunkId >= 0) {
2948 yaffs_DeleteChunk(dev, prevChunkId, 1,
2954 /* If this was a shrink, then mark the block that the chunk lives on */
2956 bi = yaffs_GetBlockInfo(in->myDev,
2957 newChunkId /in->myDev-> nChunksPerBlock);
2958 bi->hasShrinkHeader = 1;
2963 retVal = newChunkId;
2968 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2973 /*------------------------ Short Operations Cache ----------------------------------------
2974 * In many situations where there is no high level buffering (eg WinCE) a lot of
2975 * reads might be short sequential reads, and a lot of writes may be short
2976 * sequential writes. eg. scanning/writing a jpeg file.
2977 * In these cases, a short read/write cache can provide a huge perfomance benefit
2978 * with dumb-as-a-rock code.
2979 * In Linux, the page cache provides read buffering aand the short op cache provides write
2982 * There are a limited number (~10) of cache chunks per device so that we don't
2983 * need a very intelligent search.
2986 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2988 yaffs_Device *dev = obj->myDev;
2989 int lowest = -99; /* Stop compiler whining. */
2991 yaffs_ChunkCache *cache;
2992 int chunkWritten = 0;
2993 int nCaches = obj->myDev->nShortOpCaches;
2999 /* Find the dirty cache for this object with the lowest chunk id. */
3000 for (i = 0; i < nCaches; i++) {
3001 if (dev->srCache[i].object == obj &&
3002 dev->srCache[i].dirty) {
3004 || dev->srCache[i].chunkId <
3006 cache = &dev->srCache[i];
3007 lowest = cache->chunkId;
3012 if (cache && !cache->locked) {
3013 /* Write it out and free it up */
3016 yaffs_WriteChunkDataToObject(cache->object,
3022 cache->object = NULL;
3025 } while (cache && chunkWritten > 0);
3028 /* Hoosterman, disk full while writing cache out. */
3029 T(YAFFS_TRACE_ERROR,
3030 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3037 /* Grab us a cache chunk for use.
3038 * First look for an empty one.
3039 * Then look for the least recently used non-dirty one.
3040 * Then look for the least recently used dirty one...., flush and look again.
3042 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3048 if (dev->nShortOpCaches > 0) {
3049 for (i = 0; i < dev->nShortOpCaches; i++) {
3050 if (!dev->srCache[i].object)
3051 return &dev->srCache[i];
3057 usage = 0; /* just to stop the compiler grizzling */
3059 for (i = 0; i < dev->nShortOpCaches; i++) {
3060 if (!dev->srCache[i].dirty &&
3061 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3063 usage = dev->srCache[i].lastUse;
3069 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3076 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3078 yaffs_ChunkCache *cache;
3079 yaffs_Object *theObj;
3084 if (dev->nShortOpCaches > 0) {
3085 /* Try find a non-dirty one... */
3087 cache = yaffs_GrabChunkCacheWorker(dev);
3090 /* They were all dirty, find the last recently used object and flush
3091 * its cache, then find again.
3092 * NB what's here is not very accurate, we actually flush the object
3093 * the last recently used page.
3096 /* With locking we can't assume we can use entry zero */
3103 for (i = 0; i < dev->nShortOpCaches; i++) {
3104 if (dev->srCache[i].object &&
3105 !dev->srCache[i].locked &&
3106 (dev->srCache[i].lastUse < usage || !cache))
3108 usage = dev->srCache[i].lastUse;
3109 theObj = dev->srCache[i].object;
3110 cache = &dev->srCache[i];
3115 if (!cache || cache->dirty) {
3116 /* Flush and try again */
3117 yaffs_FlushFilesChunkCache(theObj);
3118 cache = yaffs_GrabChunkCacheWorker(dev);
3128 /* Find a cached chunk */
3129 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3132 yaffs_Device *dev = obj->myDev;
3134 if (dev->nShortOpCaches > 0) {
3135 for (i = 0; i < dev->nShortOpCaches; i++) {
3136 if (dev->srCache[i].object == obj &&
3137 dev->srCache[i].chunkId == chunkId) {
3140 return &dev->srCache[i];
3147 /* Mark the chunk for the least recently used algorithym */
3148 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3152 if (dev->nShortOpCaches > 0) {
3153 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3154 /* Reset the cache usages */
3156 for (i = 1; i < dev->nShortOpCaches; i++) {
3157 dev->srCache[i].lastUse = 0;
3164 cache->lastUse = dev->srLastUse;
3172 /* Invalidate a single cache page.
3173 * Do this when a whole page gets written,
3174 * ie the short cache for this page is no longer valid.
3176 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3178 if (object->myDev->nShortOpCaches > 0) {
3179 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3182 cache->object = NULL;
3187 /* Invalidate all the cache pages associated with this object
3188 * Do this whenever ther file is deleted or resized.
3190 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3193 yaffs_Device *dev = in->myDev;
3195 if (dev->nShortOpCaches > 0) {
3196 /* Invalidate it. */
3197 for (i = 0; i < dev->nShortOpCaches; i++) {
3198 if (dev->srCache[i].object == in) {
3199 dev->srCache[i].object = NULL;
3205 /*--------------------- File read/write ------------------------
3206 * Read and write have very similar structures.
3207 * In general the read/write has three parts to it
3208 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3209 * Some complete chunks
3210 * An incomplete chunk to end off with
3212 * Curve-balls: the first chunk might also be the last chunk.
3215 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3224 yaffs_ChunkCache *cache;
3231 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3232 start = offset % dev->nBytesPerChunk;
3234 /* OK now check for the curveball where the start and end are in
3237 if ((start + n) < dev->nBytesPerChunk) {
3240 nToCopy = dev->nBytesPerChunk - start;
3243 cache = yaffs_FindChunkCache(in, chunk);
3245 /* If the chunk is already in the cache or it is less than a whole chunk
3246 * then use the cache (if there is caching)
3247 * else bypass the cache.
3249 if (cache || nToCopy != dev->nBytesPerChunk) {
3250 if (dev->nShortOpCaches > 0) {
3252 /* If we can't find the data in the cache, then load it up. */
3255 cache = yaffs_GrabChunkCache(in->myDev);
3257 cache->chunkId = chunk;
3260 yaffs_ReadChunkDataFromObject(in, chunk,
3266 yaffs_UseChunkCache(dev, cache, 0);
3270 #ifdef CONFIG_YAFFS_WINCE
3271 yfsd_UnlockYAFFS(TRUE);
3273 memcpy(buffer, &cache->data[start], nToCopy);
3275 #ifdef CONFIG_YAFFS_WINCE
3276 yfsd_LockYAFFS(TRUE);
3280 /* Read into the local buffer then copy..*/
3283 yaffs_GetTempBuffer(dev, __LINE__);
3284 yaffs_ReadChunkDataFromObject(in, chunk,
3286 #ifdef CONFIG_YAFFS_WINCE
3287 yfsd_UnlockYAFFS(TRUE);
3289 memcpy(buffer, &localBuffer[start], nToCopy);
3291 #ifdef CONFIG_YAFFS_WINCE
3292 yfsd_LockYAFFS(TRUE);
3294 yaffs_ReleaseTempBuffer(dev, localBuffer,
3299 #ifdef CONFIG_YAFFS_WINCE
3300 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3302 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3303 * This is because we otherwise screw up WinCE's memory mapper
3305 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3307 #ifdef CONFIG_YAFFS_WINCE
3308 yfsd_UnlockYAFFS(TRUE);
3310 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3312 #ifdef CONFIG_YAFFS_WINCE
3313 yfsd_LockYAFFS(TRUE);
3314 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3318 /* A full chunk. Read directly into the supplied buffer. */
3319 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3333 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3334 int nBytes, int writeThrough)
3343 int startOfWrite = offset;
3344 int chunkWritten = 0;
3351 while (n > 0 && chunkWritten >= 0) {
3352 chunk = offset / dev->nBytesPerChunk + 1;
3353 start = offset % dev->nBytesPerChunk;
3355 /* OK now check for the curveball where the start and end are in
3359 if ((start + n) < dev->nBytesPerChunk) {
3362 /* Now folks, to calculate how many bytes to write back....
3363 * If we're overwriting and not writing to then end of file then
3364 * we need to write back as much as was there before.
3368 in->variant.fileVariant.fileSize -
3369 ((chunk - 1) * dev->nBytesPerChunk);
3371 if (nBytesRead > dev->nBytesPerChunk) {
3372 nBytesRead = dev->nBytesPerChunk;
3377 (start + n)) ? nBytesRead : (start + n);
3380 nToCopy = dev->nBytesPerChunk - start;
3381 nToWriteBack = dev->nBytesPerChunk;
3384 if (nToCopy != dev->nBytesPerChunk) {
3385 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3386 if (dev->nShortOpCaches > 0) {
3387 yaffs_ChunkCache *cache;
3388 /* If we can't find the data in the cache, then load the cache */
3389 cache = yaffs_FindChunkCache(in, chunk);
3391 && yaffs_CheckSpaceForAllocation(in->
3393 cache = yaffs_GrabChunkCache(in->myDev);
3395 cache->chunkId = chunk;
3398 yaffs_ReadChunkDataFromObject(in, chunk,
3404 yaffs_UseChunkCache(dev, cache, 1);
3406 #ifdef CONFIG_YAFFS_WINCE
3407 yfsd_UnlockYAFFS(TRUE);
3410 memcpy(&cache->data[start], buffer,
3413 #ifdef CONFIG_YAFFS_WINCE
3414 yfsd_LockYAFFS(TRUE);
3417 cache->nBytes = nToWriteBack;
3421 yaffs_WriteChunkDataToObject
3424 cache->data, cache->nBytes,
3430 chunkWritten = -1; /* fail the write */
3433 /* An incomplete start or end chunk (or maybe both start and end chunk)
3434 * Read into the local buffer then copy, then copy over and write back.
3438 yaffs_GetTempBuffer(dev, __LINE__);
3440 yaffs_ReadChunkDataFromObject(in, chunk,
3443 #ifdef CONFIG_YAFFS_WINCE
3444 yfsd_UnlockYAFFS(TRUE);
3447 memcpy(&localBuffer[start], buffer, nToCopy);
3449 #ifdef CONFIG_YAFFS_WINCE
3450 yfsd_LockYAFFS(TRUE);
3453 yaffs_WriteChunkDataToObject(in, chunk,
3458 yaffs_ReleaseTempBuffer(dev, localBuffer,
3465 #ifdef CONFIG_YAFFS_WINCE
3466 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3467 * This is because we otherwise screw up WinCE's memory mapper
3469 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3470 #ifdef CONFIG_YAFFS_WINCE
3471 yfsd_UnlockYAFFS(TRUE);
3473 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3474 #ifdef CONFIG_YAFFS_WINCE
3475 yfsd_LockYAFFS(TRUE);
3478 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3479 dev->nBytesPerChunk,
3481 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3483 /* A full chunk. Write directly from the supplied buffer. */
3485 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3486 dev->nBytesPerChunk,
3489 /* Since we've overwritten the cached data, we better invalidate it. */
3490 yaffs_InvalidateChunkCache(in, chunk);
3493 if (chunkWritten >= 0) {
3502 /* Update file object */
3504 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3505 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3514 /* ---------------------- File resizing stuff ------------------ */
3516 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
3519 yaffs_Device *dev = in->myDev;
3520 int oldFileSize = in->variant.fileVariant.fileSize;
3522 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
3524 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
3525 dev->nBytesPerChunk;
3529 /* Delete backwards so that we don't end up with holes if
3530 * power is lost part-way through the operation.
3532 for (i = lastDel; i >= startDel; i--) {
3533 /* NB this could be optimised somewhat,
3534 * eg. could retrieve the tags and write them without
3535 * using yaffs_DeleteChunk
3538 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3541 (dev->internalStartBlock * dev->nChunksPerBlock)
3543 ((dev->internalEndBlock +
3544 1) * dev->nChunksPerBlock)) {
3545 T(YAFFS_TRACE_ALWAYS,
3546 (TSTR("Found daft chunkId %d for %d" TENDSTR),
3550 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3557 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
3560 int oldFileSize = in->variant.fileVariant.fileSize;
3561 int sizeOfPartialChunk;
3562 yaffs_Device *dev = in->myDev;
3564 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
3566 yaffs_FlushFilesChunkCache(in);
3567 yaffs_InvalidateWholeChunkCache(in);
3569 yaffs_CheckGarbageCollection(dev);
3571 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3572 return yaffs_GetFileSize(in);
3575 if (newSize == oldFileSize) {
3579 if (newSize < oldFileSize) {
3581 yaffs_PruneResizedChunks(in, newSize);
3583 if (sizeOfPartialChunk != 0) {
3584 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
3585 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3587 /* Got to read and rewrite the last chunk with its new size and zero pad */
3588 yaffs_ReadChunkDataFromObject(in, lastChunk,
3591 memset(localBuffer + sizeOfPartialChunk, 0,
3592 dev->nBytesPerChunk - sizeOfPartialChunk);
3594 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
3595 sizeOfPartialChunk, 1);
3597 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3600 in->variant.fileVariant.fileSize = newSize;
3602 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
3604 /* Write a new object header.
3605 * show we've shrunk the file, if need be
3606 * Do this only if the file is not in the deleted directories.
3608 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3609 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
3610 yaffs_UpdateObjectHeader(in, NULL, 0,
3611 (newSize < oldFileSize) ? 1 : 0, 0);
3617 loff_t yaffs_GetFileSize(yaffs_Object * obj)
3619 obj = yaffs_GetEquivalentObject(obj);
3621 switch (obj->variantType) {
3622 case YAFFS_OBJECT_TYPE_FILE:
3623 return obj->variant.fileVariant.fileSize;
3624 case YAFFS_OBJECT_TYPE_SYMLINK:
3625 return yaffs_strlen(obj->variant.symLinkVariant.alias);
3633 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
3637 yaffs_FlushFilesChunkCache(in);
3639 #ifdef CONFIG_YAFFS_WINCE
3640 yfsd_WinFileTimeNow(in->win_mtime);
3643 in->yst_mtime = Y_CURRENT_TIME;
3649 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
3650 0) ? YAFFS_OK : YAFFS_FAIL;
3659 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
3662 /* First off, invalidate the file's data in the cache, without flushing. */
3663 yaffs_InvalidateWholeChunkCache(in);
3665 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3666 /* Move to the unlinked directory so we have a record that it was deleted. */
3667 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
3671 yaffs_RemoveObjectFromDirectory(in);
3672 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
3675 yaffs_FreeObject(in);
3680 /* yaffs_DeleteFile deletes the whole file data
3681 * and the inode associated with the file.
3682 * It does not delete the links associated with the file.
3684 static int yaffs_UnlinkFile(yaffs_Object * in)
3688 int immediateDeletion = 0;
3693 immediateDeletion = 1;
3697 if (in->inUse <= 0) {
3698 immediateDeletion = 1;
3702 if (immediateDeletion) {
3704 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3706 T(YAFFS_TRACE_TRACING,
3707 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3710 in->myDev->nDeletedFiles++;
3711 if (0 && in->myDev->isYaffs2) {
3712 yaffs_ResizeFile(in, 0);
3714 yaffs_SoftDeleteFile(in);
3717 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3725 int yaffs_DeleteFile(yaffs_Object * in)
3727 int retVal = YAFFS_OK;
3729 if (in->nDataChunks > 0) {
3730 /* Use soft deletion if there is data in the file */
3731 if (!in->unlinked) {
3732 retVal = yaffs_UnlinkFile(in);
3734 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3736 in->myDev->nDeletedFiles++;
3737 yaffs_SoftDeleteFile(in);
3739 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3741 /* The file has no data chunks so we toss it immediately */
3742 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3743 in->variant.fileVariant.top = NULL;
3744 yaffs_DoGenericObjectDeletion(in);
3750 static int yaffs_DeleteDirectory(yaffs_Object * in)
3752 /* First check that the directory is empty. */
3753 if (list_empty(&in->variant.directoryVariant.children)) {
3754 return yaffs_DoGenericObjectDeletion(in);
3761 static int yaffs_DeleteSymLink(yaffs_Object * in)
3763 YFREE(in->variant.symLinkVariant.alias);
3765 return yaffs_DoGenericObjectDeletion(in);
3768 static int yaffs_DeleteHardLink(yaffs_Object * in)
3770 /* remove this hardlink from the list assocaited with the equivalent
3773 list_del(&in->hardLinks);
3774 return yaffs_DoGenericObjectDeletion(in);
3777 static void yaffs_DestroyObject(yaffs_Object * obj)
3779 switch (obj->variantType) {
3780 case YAFFS_OBJECT_TYPE_FILE:
3781 yaffs_DeleteFile(obj);
3783 case YAFFS_OBJECT_TYPE_DIRECTORY:
3784 yaffs_DeleteDirectory(obj);
3786 case YAFFS_OBJECT_TYPE_SYMLINK:
3787 yaffs_DeleteSymLink(obj);
3789 case YAFFS_OBJECT_TYPE_HARDLINK:
3790 yaffs_DeleteHardLink(obj);
3792 case YAFFS_OBJECT_TYPE_SPECIAL:
3793 yaffs_DoGenericObjectDeletion(obj);
3795 case YAFFS_OBJECT_TYPE_UNKNOWN:
3796 break; /* should not happen. */
3800 static int yaffs_UnlinkWorker(yaffs_Object * obj)
3803 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3804 return yaffs_DeleteHardLink(obj);
3805 } else if (!list_empty(&obj->hardLinks)) {
3806 /* Curve ball: We're unlinking an object that has a hardlink.
3808 * This problem arises because we are not strictly following
3809 * The Linux link/inode model.
3811 * We can't really delete the object.
3812 * Instead, we do the following:
3813 * - Select a hardlink.
3814 * - Unhook it from the hard links
3815 * - Unhook it from its parent directory (so that the rename can work)
3816 * - Rename the object to the hardlink's name.
3817 * - Delete the hardlink
3822 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3824 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
3826 list_del_init(&hl->hardLinks);
3827 list_del_init(&hl->siblings);
3829 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3831 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
3833 if (retVal == YAFFS_OK) {
3834 retVal = yaffs_DoGenericObjectDeletion(hl);
3839 switch (obj->variantType) {
3840 case YAFFS_OBJECT_TYPE_FILE:
3841 return yaffs_UnlinkFile(obj);
3843 case YAFFS_OBJECT_TYPE_DIRECTORY:
3844 return yaffs_DeleteDirectory(obj);
3846 case YAFFS_OBJECT_TYPE_SYMLINK:
3847 return yaffs_DeleteSymLink(obj);
3849 case YAFFS_OBJECT_TYPE_SPECIAL:
3850 return yaffs_DoGenericObjectDeletion(obj);
3852 case YAFFS_OBJECT_TYPE_HARDLINK:
3853 case YAFFS_OBJECT_TYPE_UNKNOWN:
3861 static int yaffs_UnlinkObject( yaffs_Object *obj)
3864 if (obj && obj->unlinkAllowed) {
3865 return yaffs_UnlinkWorker(obj);
3871 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
3875 obj = yaffs_FindObjectByName(dir, name);
3876 return yaffs_UnlinkObject(obj);
3879 /*----------------------- Initialisation Scanning ---------------------- */
3881 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
3882 int backwardScanning)
3886 if (!backwardScanning) {
3887 /* Handle YAFFS1 forward scanning case
3888 * For YAFFS1 we always do the deletion
3892 /* Handle YAFFS2 case (backward scanning)
3893 * If the shadowed object exists then ignore.
3895 if (yaffs_FindObjectByNumber(dev, objId)) {
3900 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
3901 * We put it in unlinked dir to be cleaned up after the scanning
3904 yaffs_FindOrCreateObjectByNumber(dev, objId,
3905 YAFFS_OBJECT_TYPE_FILE);
3906 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
3907 obj->variant.fileVariant.shrinkSize = 0;
3908 obj->valid = 1; /* So that we don't read any other info for this file */
3917 static int yaffs_Scan(yaffs_Device * dev)
3919 yaffs_ExtendedTags tags;
3924 int nBlocksToScan = 0;
3929 yaffs_BlockState state;
3930 yaffs_Object *hardList = NULL;
3932 yaffs_BlockInfo *bi;
3934 yaffs_ObjectHeader *oh;
3936 yaffs_Object *parent;
3937 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3941 yaffs_BlockIndex *blockIndex = NULL;
3944 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
3945 dev->internalStartBlock, dev->internalEndBlock));
3947 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
3949 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
3951 if (dev->isYaffs2) {
3952 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
3955 /* Scan all the blocks to determine their state */
3956 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
3957 bi = yaffs_GetBlockInfo(dev, blk);
3958 yaffs_ClearChunkBits(dev, blk);
3960 bi->softDeletions = 0;
3962 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
3964 bi->blockState = state;
3965 bi->sequenceNumber = sequenceNumber;
3967 T(YAFFS_TRACE_SCAN_DEBUG,
3968 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
3969 state, sequenceNumber));
3971 if (state == YAFFS_BLOCK_STATE_DEAD) {
3972 T(YAFFS_TRACE_BAD_BLOCKS,
3973 (TSTR("block %d is bad" TENDSTR), blk));
3974 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
3975 T(YAFFS_TRACE_SCAN_DEBUG,
3976 (TSTR("Block empty " TENDSTR)));
3977 dev->nErasedBlocks++;
3978 dev->nFreeChunks += dev->nChunksPerBlock;
3979 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3981 /* Determine the highest sequence number */
3982 if (dev->isYaffs2 &&
3983 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
3984 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
3986 blockIndex[nBlocksToScan].seq = sequenceNumber;
3987 blockIndex[nBlocksToScan].block = blk;
3991 if (sequenceNumber >= dev->sequenceNumber) {
3992 dev->sequenceNumber = sequenceNumber;
3994 } else if (dev->isYaffs2) {
3995 /* TODO: Nasty sequence number! */
3998 ("Block scanning block %d has bad sequence number %d"
3999 TENDSTR), blk, sequenceNumber));
4006 * Dungy old bubble sort for now...
4008 if (dev->isYaffs2) {
4009 yaffs_BlockIndex temp;
4013 for (i = 0; i < nBlocksToScan; i++)
4014 for (j = i + 1; j < nBlocksToScan; j++)
4015 if (blockIndex[i].seq > blockIndex[j].seq) {
4016 temp = blockIndex[j];
4017 blockIndex[j] = blockIndex[i];
4018 blockIndex[i] = temp;
4022 /* Now scan the blocks looking at the data. */
4023 if (dev->isYaffs2) {
4025 endIterator = nBlocksToScan - 1;
4026 T(YAFFS_TRACE_SCAN_DEBUG,
4027 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4029 startIterator = dev->internalStartBlock;
4030 endIterator = dev->internalEndBlock;
4033 /* For each block.... */
4034 for (blockIterator = startIterator; blockIterator <= endIterator;
4037 if (dev->isYaffs2) {
4038 /* get the block to scan in the correct order */
4039 blk = blockIndex[blockIterator].block;
4041 blk = blockIterator;
4044 bi = yaffs_GetBlockInfo(dev, blk);
4045 state = bi->blockState;
4049 /* For each chunk in each block that needs scanning....*/
4050 for (c = 0; c < dev->nChunksPerBlock &&
4051 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4052 /* Read the tags and decide what to do */
4053 chunk = blk * dev->nChunksPerBlock + c;
4055 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4058 /* Let's have a good look at this chunk... */
4060 if (!dev->isYaffs2 && tags.chunkDeleted) {
4066 /*T((" %d %d deleted\n",blk,c)); */
4067 } else if (!tags.chunkUsed) {
4068 /* An unassigned chunk in the block
4069 * This means that either the block is empty or
4070 * this is the one being allocated from
4074 /* We're looking at the first chunk in the block so the block is unused */
4075 state = YAFFS_BLOCK_STATE_EMPTY;
4076 dev->nErasedBlocks++;
4078 /* this is the block being allocated from */
4081 (" Allocating from %d %d" TENDSTR),
4083 state = YAFFS_BLOCK_STATE_ALLOCATING;
4084 dev->allocationBlock = blk;
4085 dev->allocationPage = c;
4086 dev->allocationBlockFinder = blk;
4087 /* Set it to here to encourage the allocator to go forth from here. */
4089 /* Yaffs2 sanity check:
4090 * This should be the one with the highest sequence number
4093 && (dev->sequenceNumber !=
4094 bi->sequenceNumber)) {
4095 T(YAFFS_TRACE_ALWAYS,
4097 ("yaffs: Allocation block %d was not highest sequence id:"
4098 " block seq = %d, dev seq = %d"
4099 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4103 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4104 } else if (tags.chunkId > 0) {
4105 /* chunkId > 0 so it is a data chunk... */
4106 unsigned int endpos;
4108 yaffs_SetChunkBit(dev, blk, c);
4111 in = yaffs_FindOrCreateObjectByNumber(dev,
4114 YAFFS_OBJECT_TYPE_FILE);
4115 /* PutChunkIntoFile checks for a clash (two data chunks with
4116 * the same chunkId).
4118 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4121 (tags.chunkId - 1) * dev->nBytesPerChunk +
4123 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4124 && in->variant.fileVariant.scannedFileSize <
4126 in->variant.fileVariant.
4127 scannedFileSize = endpos;
4128 if (!dev->useHeaderFileSize) {
4129 in->variant.fileVariant.
4131 in->variant.fileVariant.
4136 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4138 /* chunkId == 0, so it is an ObjectHeader.
4139 * Thus, we read in the object header and make the object
4141 yaffs_SetChunkBit(dev, blk, c);
4144 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4148 oh = (yaffs_ObjectHeader *) chunkData;
4150 in = yaffs_FindObjectByNumber(dev,
4152 if (in && in->variantType != oh->type) {
4153 /* This should not happen, but somehow
4154 * Wev'e ended up with an objectId that has been reused but not yet
4155 * deleted, and worse still it has changed type. Delete the old object.
4158 yaffs_DestroyObject(in);
4163 in = yaffs_FindOrCreateObjectByNumber(dev,
4168 if (oh->shadowsObject > 0) {
4169 yaffs_HandleShadowedObject(dev,
4176 /* We have already filled this one. We have a duplicate and need to resolve it. */
4178 unsigned existingSerial = in->serial;
4179 unsigned newSerial = tags.serialNumber;
4181 if (dev->isYaffs2 ||
4182 ((existingSerial + 1) & 3) ==
4184 /* Use new one - destroy the exisiting one */
4185 yaffs_DeleteChunk(dev,
4190 /* Use existing - destroy this one. */
4191 yaffs_DeleteChunk(dev, chunk, 1,
4197 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4198 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4199 /* We only load some info, don't fiddle with directory structure */
4201 in->variantType = oh->type;
4203 in->yst_mode = oh->yst_mode;
4204 #ifdef CONFIG_YAFFS_WINCE
4205 in->win_atime[0] = oh->win_atime[0];
4206 in->win_ctime[0] = oh->win_ctime[0];
4207 in->win_mtime[0] = oh->win_mtime[0];
4208 in->win_atime[1] = oh->win_atime[1];
4209 in->win_ctime[1] = oh->win_ctime[1];
4210 in->win_mtime[1] = oh->win_mtime[1];
4212 in->yst_uid = oh->yst_uid;
4213 in->yst_gid = oh->yst_gid;
4214 in->yst_atime = oh->yst_atime;
4215 in->yst_mtime = oh->yst_mtime;
4216 in->yst_ctime = oh->yst_ctime;
4217 in->yst_rdev = oh->yst_rdev;
4219 in->chunkId = chunk;
4221 } else if (!in->valid) {
4222 /* we need to load this info */
4225 in->variantType = oh->type;
4227 in->yst_mode = oh->yst_mode;
4228 #ifdef CONFIG_YAFFS_WINCE
4229 in->win_atime[0] = oh->win_atime[0];
4230 in->win_ctime[0] = oh->win_ctime[0];
4231 in->win_mtime[0] = oh->win_mtime[0];
4232 in->win_atime[1] = oh->win_atime[1];
4233 in->win_ctime[1] = oh->win_ctime[1];
4234 in->win_mtime[1] = oh->win_mtime[1];
4236 in->yst_uid = oh->yst_uid;
4237 in->yst_gid = oh->yst_gid;
4238 in->yst_atime = oh->yst_atime;
4239 in->yst_mtime = oh->yst_mtime;
4240 in->yst_ctime = oh->yst_ctime;
4241 in->yst_rdev = oh->yst_rdev;
4243 in->chunkId = chunk;
4245 yaffs_SetObjectName(in, oh->name);
4248 /* directory stuff...
4253 yaffs_FindOrCreateObjectByNumber
4254 (dev, oh->parentObjectId,
4255 YAFFS_OBJECT_TYPE_DIRECTORY);
4256 if (parent->variantType ==
4257 YAFFS_OBJECT_TYPE_UNKNOWN) {
4258 /* Set up as a directory */
4259 parent->variantType =
4260 YAFFS_OBJECT_TYPE_DIRECTORY;
4261 INIT_LIST_HEAD(&parent->variant.
4264 } else if (parent->variantType !=
4265 YAFFS_OBJECT_TYPE_DIRECTORY)
4267 /* Hoosterman, another problem....
4268 * We're trying to use a non-directory as a directory
4271 T(YAFFS_TRACE_ERROR,
4273 ("yaffs tragedy: attempting to use non-directory as"
4274 " a directory in scan. Put in lost+found."
4276 parent = dev->lostNFoundDir;
4279 yaffs_AddObjectToDirectory(parent, in);
4281 if (0 && (parent == dev->deletedDir ||
4282 parent == dev->unlinkedDir)) {
4283 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
4284 dev->nDeletedFiles++;
4286 /* Note re hardlinks.
4287 * Since we might scan a hardlink before its equivalent object is scanned
4288 * we put them all in a list.
4289 * After scanning is complete, we should have all the objects, so we run through this
4290 * list and fix up all the chains.
4293 switch (in->variantType) {
4294 case YAFFS_OBJECT_TYPE_UNKNOWN:
4295 /* Todo got a problem */
4297 case YAFFS_OBJECT_TYPE_FILE:
4300 /* Prune back the shrunken chunks */
4301 yaffs_PruneResizedChunks
4303 /* Mark the block as having a shrinkHeader */
4304 bi->hasShrinkHeader = 1;
4307 if (dev->useHeaderFileSize)
4309 in->variant.fileVariant.
4314 case YAFFS_OBJECT_TYPE_HARDLINK:
4315 in->variant.hardLinkVariant.
4316 equivalentObjectId =
4317 oh->equivalentObjectId;
4318 in->hardLinks.next =
4319 (struct list_head *)
4323 case YAFFS_OBJECT_TYPE_DIRECTORY:
4326 case YAFFS_OBJECT_TYPE_SPECIAL:
4329 case YAFFS_OBJECT_TYPE_SYMLINK:
4330 in->variant.symLinkVariant.
4332 yaffs_CloneString(oh->alias);
4336 if (parent == dev->deletedDir) {
4337 yaffs_DestroyObject(in);
4338 bi->hasShrinkHeader = 1;
4344 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4345 /* If we got this far while scanning, then the block is fully allocated.*/
4346 state = YAFFS_BLOCK_STATE_FULL;
4349 bi->blockState = state;
4351 /* Now let's see if it was dirty */
4352 if (bi->pagesInUse == 0 &&
4353 !bi->hasShrinkHeader &&
4354 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4355 yaffs_BlockBecameDirty(dev, blk);
4364 /* Ok, we've done all the scanning.
4365 * Fix up the hard link chains.
4366 * We should now have scanned all the objects, now it's time to add these
4371 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4373 in = yaffs_FindObjectByNumber(dev,
4374 hl->variant.hardLinkVariant.
4375 equivalentObjectId);
4378 /* Add the hardlink pointers */
4379 hl->variant.hardLinkVariant.equivalentObject = in;
4380 list_add(&hl->hardLinks, &in->hardLinks);
4382 /* Todo Need to report/handle this better.
4383 * Got a problem... hardlink to a non-existant object
4385 hl->variant.hardLinkVariant.equivalentObject = NULL;
4386 INIT_LIST_HEAD(&hl->hardLinks);
4392 /* Handle the unlinked files. Since they were left in an unlinked state we should
4396 struct list_head *i;
4397 struct list_head *n;
4400 /* Soft delete all the unlinked files */
4401 list_for_each_safe(i, n,
4402 &dev->unlinkedDir->variant.directoryVariant.
4405 l = list_entry(i, yaffs_Object, siblings);
4406 yaffs_DestroyObject(l);
4411 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4413 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4418 static int yaffs_ScanBackwards(yaffs_Device * dev)
4420 yaffs_ExtendedTags tags;
4425 int nBlocksToScan = 0;
4430 yaffs_BlockState state;
4431 yaffs_Object *hardList = NULL;
4433 yaffs_BlockInfo *bi;
4435 yaffs_ObjectHeader *oh;
4437 yaffs_Object *parent;
4438 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4442 yaffs_BlockIndex *blockIndex = NULL;
4444 if (!dev->isYaffs2) {
4446 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
4452 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
4453 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
4455 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4457 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4459 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4461 /* Scan all the blocks to determine their state */
4462 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4463 bi = yaffs_GetBlockInfo(dev, blk);
4464 yaffs_ClearChunkBits(dev, blk);
4466 bi->softDeletions = 0;
4468 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4470 bi->blockState = state;
4471 bi->sequenceNumber = sequenceNumber;
4473 T(YAFFS_TRACE_SCAN_DEBUG,
4474 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4475 state, sequenceNumber));
4477 if (state == YAFFS_BLOCK_STATE_DEAD) {
4478 T(YAFFS_TRACE_BAD_BLOCKS,
4479 (TSTR("block %d is bad" TENDSTR), blk));
4480 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4481 T(YAFFS_TRACE_SCAN_DEBUG,
4482 (TSTR("Block empty " TENDSTR)));
4483 dev->nErasedBlocks++;
4484 dev->nFreeChunks += dev->nChunksPerBlock;
4485 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4487 /* Determine the highest sequence number */
4488 if (dev->isYaffs2 &&
4489 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4490 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4492 blockIndex[nBlocksToScan].seq = sequenceNumber;
4493 blockIndex[nBlocksToScan].block = blk;
4497 if (sequenceNumber >= dev->sequenceNumber) {
4498 dev->sequenceNumber = sequenceNumber;
4500 } else if (dev->isYaffs2) {
4501 /* TODO: Nasty sequence number! */
4504 ("Block scanning block %d has bad sequence number %d"
4505 TENDSTR), blk, sequenceNumber));
4513 * Dungy old bubble sort for now...
4516 yaffs_BlockIndex temp;
4520 for (i = 0; i < nBlocksToScan; i++)
4521 for (j = i + 1; j < nBlocksToScan; j++)
4522 if (blockIndex[i].seq > blockIndex[j].seq) {
4523 temp = blockIndex[j];
4524 blockIndex[j] = blockIndex[i];
4525 blockIndex[i] = temp;
4529 /* Now scan the blocks looking at the data. */
4531 endIterator = nBlocksToScan - 1;
4532 T(YAFFS_TRACE_SCAN_DEBUG,
4533 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4535 /* For each block.... backwards */
4536 for (blockIterator = endIterator; blockIterator >= startIterator;
4539 /* get the block to scan in the correct order */
4540 blk = blockIndex[blockIterator].block;
4542 bi = yaffs_GetBlockInfo(dev, blk);
4543 state = bi->blockState;
4547 /* For each chunk in each block that needs scanning.... */
4548 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
4549 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
4550 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
4551 /* Scan backwards...
4552 * Read the tags and decide what to do
4554 chunk = blk * dev->nChunksPerBlock + c;
4556 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4559 /* Let's have a good look at this chunk... */
4561 if (!tags.chunkUsed) {
4562 // An unassigned chunk in the block
4563 // This means that either the block is empty or
4564 // this is the one being allocated from
4567 /* We're looking at the first chunk in the block so the block is unused */
4568 state = YAFFS_BLOCK_STATE_EMPTY;
4569 dev->nErasedBlocks++;
4571 /* this is the block being allocated from */
4573 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4576 (" Allocating from %d %d"
4579 state = YAFFS_BLOCK_STATE_ALLOCATING;
4580 dev->allocationBlock = blk;
4581 dev->allocationPage = c;
4582 dev->allocationBlockFinder = blk;
4583 /* Set it to here to encourage the allocator to
4584 * go forth from here.
4587 /* Yaffs2 sanity check:
4588 * This should be the one with the highest sequence number
4591 && (dev->sequenceNumber !=
4592 bi->sequenceNumber)) {
4593 T(YAFFS_TRACE_ALWAYS,
4595 ("yaffs: Allocation block %d was not highest sequence "
4596 "id: block seq = %d, dev seq = %d"
4599 dev->sequenceNumber));
4604 } else if (tags.chunkId > 0) {
4605 /* chunkId > 0 so it is a data chunk... */
4606 unsigned int endpos;
4609 (tags.chunkId - 1) * dev->nBytesPerChunk;
4611 yaffs_SetChunkBit(dev, blk, c);
4614 in = yaffs_FindOrCreateObjectByNumber(dev,
4617 YAFFS_OBJECT_TYPE_FILE);
4618 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4620 in->variant.fileVariant.shrinkSize) {
4621 /* This has not been invalidated by a resize */
4622 yaffs_PutChunkIntoFile(in, tags.chunkId,
4625 /* File size is calculated by looking at the data chunks if we have not
4626 * seen an object header yet. Stop this practice once we find an object header.
4630 1) * dev->nBytesPerChunk +
4633 if (!in->valid && /* have not got an object header yet */
4634 in->variant.fileVariant.
4635 scannedFileSize < endpos) {
4636 in->variant.fileVariant.
4637 scannedFileSize = endpos;
4638 in->variant.fileVariant.
4640 in->variant.fileVariant.
4645 /* This chunk has been invalidated by a resize, so delete */
4646 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4650 /* chunkId == 0, so it is an ObjectHeader.
4651 * Thus, we read in the object header and make the object
4653 yaffs_SetChunkBit(dev, blk, c);
4659 if (tags.extraHeaderInfoAvailable) {
4660 in = yaffs_FindOrCreateObjectByNumber
4661 (dev, tags.objectId,
4662 tags.extraObjectType);
4665 if (!in || !in->valid) {
4667 /* If we don't have valid info then we need to read the chunk
4668 * TODO In future we can probably defer reading the chunk and
4669 * living with invalid data until needed.
4672 yaffs_ReadChunkWithTagsFromNAND(dev,
4677 oh = (yaffs_ObjectHeader *) chunkData;
4680 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
4685 /* TODO Hoosterman we have a problem! */
4686 T(YAFFS_TRACE_ERROR,
4688 ("yaffs tragedy: Could not make object for object %d "
4689 "at chunk %d during scan"
4690 TENDSTR), tags.objectId, chunk));
4695 /* We have already filled this one.
4696 * We have a duplicate that will be discarded, but
4697 * we first have to suck out resize info if it is a file.
4700 if ((in->variantType ==
4701 YAFFS_OBJECT_TYPE_FILE) && ((oh
4706 YAFFS_OBJECT_TYPE_FILE)
4709 extraHeaderInfoAvailable
4714 YAFFS_OBJECT_TYPE_FILE))
4717 (oh) ? oh->fileSize : tags.
4719 __u32 parentObjectId =
4721 parentObjectId : tags.
4722 extraParentObjectId;
4724 (oh) ? oh->isShrink : tags.
4725 extraIsShrinkHeader;
4727 /* If it is deleted (unlinked at start also means deleted)
4728 * we treat the file size as being zeroed at this point.
4730 if (parentObjectId ==
4731 YAFFS_OBJECTID_DELETED
4732 || parentObjectId ==
4733 YAFFS_OBJECTID_UNLINKED) {
4739 in->variant.fileVariant.
4740 shrinkSize > thisSize) {
4741 in->variant.fileVariant.
4747 bi->hasShrinkHeader = 1;
4751 /* Use existing - destroy this one. */
4752 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4757 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4759 YAFFS_OBJECTID_LOSTNFOUND)) {
4760 /* We only load some info, don't fiddle with directory structure */
4762 in->variantType = oh->type;
4764 in->yst_mode = oh->yst_mode;
4765 #ifdef CONFIG_YAFFS_WINCE
4766 in->win_atime[0] = oh->win_atime[0];
4767 in->win_ctime[0] = oh->win_ctime[0];
4768 in->win_mtime[0] = oh->win_mtime[0];
4769 in->win_atime[1] = oh->win_atime[1];
4770 in->win_ctime[1] = oh->win_ctime[1];
4771 in->win_mtime[1] = oh->win_mtime[1];
4773 in->yst_uid = oh->yst_uid;
4774 in->yst_gid = oh->yst_gid;
4775 in->yst_atime = oh->yst_atime;
4776 in->yst_mtime = oh->yst_mtime;
4777 in->yst_ctime = oh->yst_ctime;
4778 in->yst_rdev = oh->yst_rdev;
4780 in->chunkId = chunk;
4782 } else if (!in->valid) {
4783 /* we need to load this info */
4786 in->variantType = oh->type;
4788 in->yst_mode = oh->yst_mode;
4789 #ifdef CONFIG_YAFFS_WINCE
4790 in->win_atime[0] = oh->win_atime[0];
4791 in->win_ctime[0] = oh->win_ctime[0];
4792 in->win_mtime[0] = oh->win_mtime[0];
4793 in->win_atime[1] = oh->win_atime[1];
4794 in->win_ctime[1] = oh->win_ctime[1];
4795 in->win_mtime[1] = oh->win_mtime[1];
4797 in->yst_uid = oh->yst_uid;
4798 in->yst_gid = oh->yst_gid;
4799 in->yst_atime = oh->yst_atime;
4800 in->yst_mtime = oh->yst_mtime;
4801 in->yst_ctime = oh->yst_ctime;
4802 in->yst_rdev = oh->yst_rdev;
4804 in->chunkId = chunk;
4806 if (oh->shadowsObject > 0) {
4807 yaffs_HandleShadowedObject(dev,
4813 yaffs_SetObjectName(in, oh->name);
4816 /* directory stuff...
4821 yaffs_FindOrCreateObjectByNumber
4822 (dev, oh->parentObjectId,
4823 YAFFS_OBJECT_TYPE_DIRECTORY);
4824 if (parent->variantType ==
4825 YAFFS_OBJECT_TYPE_UNKNOWN) {
4826 /* Set up as a directory */
4827 parent->variantType =
4828 YAFFS_OBJECT_TYPE_DIRECTORY;
4829 INIT_LIST_HEAD(&parent->variant.
4832 } else if (parent->variantType !=
4833 YAFFS_OBJECT_TYPE_DIRECTORY)
4835 /* Hoosterman, another problem....
4836 * We're trying to use a non-directory as a directory
4839 T(YAFFS_TRACE_ERROR,
4841 ("yaffs tragedy: attempting to use non-directory as"
4842 " a directory in scan. Put in lost+found."
4844 parent = dev->lostNFoundDir;
4847 yaffs_AddObjectToDirectory(parent, in);
4849 if ((parent == dev->deletedDir ||
4850 parent == dev->unlinkedDir)) {
4851 /* If it is unlinked at start up then it wants deleting */
4856 /* Mark the block as having a shrinkHeader */
4857 bi->hasShrinkHeader = 1;
4860 /* Note re hardlinks.
4861 * Since we might scan a hardlink before its equivalent object is scanned
4862 * we put them all in a list.
4863 * After scanning is complete, we should have all the objects, so we run
4864 * through this list and fix up all the chains.
4867 switch (in->variantType) {
4868 case YAFFS_OBJECT_TYPE_UNKNOWN:
4869 /* Todo got a problem */
4871 case YAFFS_OBJECT_TYPE_FILE:
4873 if (in->variant.fileVariant.
4876 /* This covers the case where the file size is greater
4877 * than where the data is
4878 * This will happen if the file is resized to be larger
4879 * than its current data extents.
4881 in->variant.fileVariant.fileSize =
4883 in->variant.fileVariant.scannedFileSize =
4884 in->variant.fileVariant.fileSize;
4888 in->variant.fileVariant.shrinkSize >
4890 in->variant.fileVariant.shrinkSize =
4895 case YAFFS_OBJECT_TYPE_HARDLINK:
4896 in->variant.hardLinkVariant.equivalentObjectId =
4897 oh->equivalentObjectId;
4898 in->hardLinks.next =
4899 (struct list_head *) hardList;
4902 case YAFFS_OBJECT_TYPE_DIRECTORY:
4905 case YAFFS_OBJECT_TYPE_SPECIAL:
4908 case YAFFS_OBJECT_TYPE_SYMLINK:
4909 in->variant.symLinkVariant.
4911 yaffs_CloneString(oh->
4920 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4921 /* If we got this far while scanning, then the block is fully allocated. */
4922 state = YAFFS_BLOCK_STATE_FULL;
4925 bi->blockState = state;
4927 /* Now let's see if it was dirty */
4928 if (bi->pagesInUse == 0 &&
4929 !bi->hasShrinkHeader &&
4930 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4931 yaffs_BlockBecameDirty(dev, blk);
4939 /* Ok, we've done all the scanning.
4940 * Fix up the hard link chains.
4941 * We should now have scanned all the objects, now it's time to add these
4946 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4948 in = yaffs_FindObjectByNumber(dev,
4949 hl->variant.hardLinkVariant.
4950 equivalentObjectId);
4953 /* Add the hardlink pointers */
4954 hl->variant.hardLinkVariant.equivalentObject = in;
4955 list_add(&hl->hardLinks, &in->hardLinks);
4957 /* Todo Need to report/handle this better.
4958 * Got a problem... hardlink to a non-existant object
4960 hl->variant.hardLinkVariant.equivalentObject = NULL;
4961 INIT_LIST_HEAD(&hl->hardLinks);
4968 struct list_head *i;
4969 struct list_head *n;
4973 /* Soft delete all the unlinked files */
4974 list_for_each_safe(i, n,
4975 &dev->unlinkedDir->variant.directoryVariant.
4978 l = list_entry(i, yaffs_Object, siblings);
4979 yaffs_DestroyObject(l);
4983 /* Soft delete all the deletedDir files */
4984 list_for_each_safe(i, n,
4985 &dev->deletedDir->variant.directoryVariant.
4988 l = list_entry(i, yaffs_Object, siblings);
4989 yaffs_DestroyObject(l);
4995 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4997 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5002 /*------------------------------ Directory Functions ----------------------------- */
5004 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5006 yaffs_Device *dev = obj->myDev;
5008 if(dev && dev->removeObjectCallback)
5009 dev->removeObjectCallback(obj);
5011 list_del_init(&obj->siblings);
5016 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5021 T(YAFFS_TRACE_ALWAYS,
5023 ("tragedy: Trying to add an object to a null pointer directory"
5027 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5028 T(YAFFS_TRACE_ALWAYS,
5030 ("tragedy: Trying to add an object to a non-directory"
5035 if (obj->siblings.prev == NULL) {
5036 /* Not initialised */
5037 INIT_LIST_HEAD(&obj->siblings);
5039 } else if (!list_empty(&obj->siblings)) {
5040 /* If it is holed up somewhere else, un hook it */
5041 yaffs_RemoveObjectFromDirectory(obj);
5044 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5045 obj->parent = directory;
5047 if (directory == obj->myDev->unlinkedDir
5048 || directory == obj->myDev->deletedDir) {
5050 obj->myDev->nUnlinkedFiles++;
5051 obj->renameAllowed = 0;
5055 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5060 struct list_head *i;
5061 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5070 T(YAFFS_TRACE_ALWAYS,
5072 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5076 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5077 T(YAFFS_TRACE_ALWAYS,
5079 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5083 sum = yaffs_CalcNameSum(name);
5085 list_for_each(i, &directory->variant.directoryVariant.children) {
5087 l = list_entry(i, yaffs_Object, siblings);
5089 /* Special case for lost-n-found */
5090 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5091 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5094 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5096 /* LostnFound cunk called Objxxx
5099 yaffs_GetObjectName(l, buffer,
5100 YAFFS_MAX_NAME_LENGTH);
5101 if (yaffs_strcmp(name, buffer) == 0) {
5114 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5115 int (*fn) (yaffs_Object *))
5117 struct list_head *i;
5121 T(YAFFS_TRACE_ALWAYS,
5123 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5127 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5128 T(YAFFS_TRACE_ALWAYS,
5130 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5134 list_for_each(i, &theDir->variant.directoryVariant.children) {
5136 l = list_entry(i, yaffs_Object, siblings);
5148 /* GetEquivalentObject dereferences any hard links to get to the
5152 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5154 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5155 /* We want the object id of the equivalent object, not this one */
5156 obj = obj->variant.hardLinkVariant.equivalentObject;
5162 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5164 memset(name, 0, buffSize * sizeof(YCHAR));
5166 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5167 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5168 } else if (obj->chunkId <= 0) {
5170 /* make up a name */
5171 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5173 yaffs_strncpy(name, locName, buffSize - 1);
5176 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5177 else if (obj->shortName[0]) {
5178 yaffs_strcpy(name, obj->shortName);
5182 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5184 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5186 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5188 if (obj->chunkId >= 0) {
5189 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5190 obj->chunkId, buffer,
5193 yaffs_strncpy(name, oh->name, buffSize - 1);
5195 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5198 return yaffs_strlen(name);
5201 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5204 /* Dereference any hard linking */
5205 obj = yaffs_GetEquivalentObject(obj);
5207 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5208 return obj->variant.fileVariant.fileSize;
5210 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5211 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5213 /* Only a directory should drop through to here */
5214 return obj->myDev->nBytesPerChunk;
5218 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5221 struct list_head *i;
5223 if (!obj->unlinked) {
5224 count++; /* the object itself */
5226 list_for_each(i, &obj->hardLinks) {
5227 count++; /* add the hard links; */
5233 int yaffs_GetObjectInode(yaffs_Object * obj)
5235 obj = yaffs_GetEquivalentObject(obj);
5237 return obj->objectId;
5240 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5242 obj = yaffs_GetEquivalentObject(obj);
5244 switch (obj->variantType) {
5245 case YAFFS_OBJECT_TYPE_FILE:
5248 case YAFFS_OBJECT_TYPE_DIRECTORY:
5251 case YAFFS_OBJECT_TYPE_SYMLINK:
5254 case YAFFS_OBJECT_TYPE_HARDLINK:
5257 case YAFFS_OBJECT_TYPE_SPECIAL:
5258 if (S_ISFIFO(obj->yst_mode))
5260 if (S_ISCHR(obj->yst_mode))
5262 if (S_ISBLK(obj->yst_mode))
5264 if (S_ISSOCK(obj->yst_mode))
5272 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5274 obj = yaffs_GetEquivalentObject(obj);
5275 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5276 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5278 return yaffs_CloneString(_Y(""));
5282 #ifndef CONFIG_YAFFS_WINCE
5284 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5286 unsigned int valid = attr->ia_valid;
5288 if (valid & ATTR_MODE)
5289 obj->yst_mode = attr->ia_mode;
5290 if (valid & ATTR_UID)
5291 obj->yst_uid = attr->ia_uid;
5292 if (valid & ATTR_GID)
5293 obj->yst_gid = attr->ia_gid;
5295 if (valid & ATTR_ATIME)
5296 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5297 if (valid & ATTR_CTIME)
5298 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5299 if (valid & ATTR_MTIME)
5300 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5302 if (valid & ATTR_SIZE)
5303 yaffs_ResizeFile(obj, attr->ia_size);
5305 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5310 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5312 unsigned int valid = 0;
5314 attr->ia_mode = obj->yst_mode;
5316 attr->ia_uid = obj->yst_uid;
5318 attr->ia_gid = obj->yst_gid;
5321 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5322 valid |= ATTR_ATIME;
5323 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5324 valid |= ATTR_CTIME;
5325 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5326 valid |= ATTR_MTIME;
5328 attr->ia_size = yaffs_GetFileSize(obj);
5331 attr->ia_valid = valid;
5340 int yaffs_DumpObject(yaffs_Object * obj)
5344 yaffs_GetObjectName(obj, name, 256);
5346 T(YAFFS_TRACE_ALWAYS,
5348 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5349 " chunk %d type %d size %d\n"
5350 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5351 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5352 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5358 /*---------------------------- Initialisation code -------------------------------------- */
5360 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5363 /* Common functions, gotta have */
5364 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5367 #ifdef CONFIG_YAFFS_YAFFS2
5369 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5370 if (dev->writeChunkWithTagsToNAND &&
5371 dev->readChunkWithTagsFromNAND &&
5372 !dev->writeChunkToNAND &&
5373 !dev->readChunkFromNAND &&
5374 dev->markNANDBlockBad && dev->queryNANDBlock)
5378 /* Can use the "spare" style interface for yaffs1 */
5379 if (!dev->isYaffs2 &&
5380 !dev->writeChunkWithTagsToNAND &&
5381 !dev->readChunkWithTagsFromNAND &&
5382 dev->writeChunkToNAND &&
5383 dev->readChunkFromNAND &&
5384 !dev->markNANDBlockBad && !dev->queryNANDBlock)
5390 int yaffs_GutsInitialise(yaffs_Device * dev)
5397 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5399 /* Check stuff that must be set */
5402 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5406 dev->internalStartBlock = dev->startBlock;
5407 dev->internalEndBlock = dev->endBlock;
5408 dev->blockOffset = 0;
5409 dev->chunkOffset = 0;
5410 dev->nFreeChunks = 0;
5412 if (dev->startBlock == 0) {
5413 dev->internalStartBlock = dev->startBlock + 1;
5414 dev->internalEndBlock = dev->endBlock + 1;
5415 dev->blockOffset = 1;
5416 dev->chunkOffset = dev->nChunksPerBlock;
5419 /* Check geometry parameters. */
5421 if ((dev->isYaffs2 && dev->nBytesPerChunk < 1024) || (!dev->isYaffs2 && dev->nBytesPerChunk != 512) || dev->nChunksPerBlock < 2 || dev->nReservedBlocks < 2 || dev->internalStartBlock <= 0 || dev->internalEndBlock <= 0 || dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
5423 T(YAFFS_TRACE_ALWAYS,
5425 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
5426 TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
5430 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5431 T(YAFFS_TRACE_ALWAYS,
5432 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5436 /* Got the right mix of functions? */
5437 if (!yaffs_CheckDevFunctions(dev)) {
5438 /* Function missing */
5439 T(YAFFS_TRACE_ALWAYS,
5441 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5446 /* This is really a compilation check. */
5447 if (!yaffs_CheckStructures()) {
5448 T(YAFFS_TRACE_ALWAYS,
5449 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5453 if (dev->isMounted) {
5454 T(YAFFS_TRACE_ALWAYS,
5455 (TSTR("yaffs: device already mounted\n" TENDSTR)));
5459 /* Finished with most checks. One or two more checks happen later on too. */
5463 nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5465 /* OK now calculate a few things for the device
5466 * Calculate chunkGroupBits.
5467 * We need to find the next power of 2 > than internalEndBlock
5470 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
5472 for (bits = extraBits = 0; x > 1; bits++) {
5481 /* Set up tnode width if wide tnodes are enabled. */
5482 if(!dev->wideTnodesDisabled){
5483 /* bits must be even so that we end up with 32-bit words */
5487 dev->tnodeWidth = 16;
5489 dev->tnodeWidth = bits;
5492 dev->tnodeWidth = 16;
5494 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5496 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5497 * so if the bitwidth of the
5498 * chunk range we're using is greater than 16 we need
5499 * to figure out chunk shift and chunkGroupSize
5502 if (bits <= dev->tnodeWidth)
5503 dev->chunkGroupBits = 0;
5505 dev->chunkGroupBits = bits - dev->tnodeWidth;
5508 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5510 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
5511 /* We have a problem because the soft delete won't work if
5512 * the chunk group size > chunks per block.
5513 * This can be remedied by using larger "virtual blocks".
5515 T(YAFFS_TRACE_ALWAYS,
5516 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5521 /* OK, we've finished verifying the device, lets continue with initialisation */
5523 /* More device initialisation */
5524 dev->garbageCollections = 0;
5525 dev->passiveGarbageCollections = 0;
5526 dev->currentDirtyChecker = 0;
5527 dev->bufferedBlock = -1;
5528 dev->doingBufferedBlockRewrite = 0;
5529 dev->nDeletedFiles = 0;
5530 dev->nBackgroundDeletions = 0;
5531 dev->nUnlinkedFiles = 0;
5533 dev->eccUnfixed = 0;
5534 dev->tagsEccFixed = 0;
5535 dev->tagsEccUnfixed = 0;
5536 dev->nErasureFailures = 0;
5537 dev->nErasedBlocks = 0;
5540 /* Initialise temporary buffers */
5543 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5544 dev->tempBuffer[i].line = 0; /* not in use */
5545 dev->tempBuffer[i].buffer =
5546 YMALLOC(dev->nBytesPerChunk);
5550 yaffs_InitialiseBlocks(dev, nBlocks);
5552 yaffs_InitialiseTnodes(dev);
5554 yaffs_InitialiseObjects(dev);
5556 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
5558 if (dev->nShortOpCaches > 0) {
5561 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
5562 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5566 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
5568 for (i = 0; i < dev->nShortOpCaches; i++) {
5569 dev->srCache[i].object = NULL;
5570 dev->srCache[i].lastUse = 0;
5571 dev->srCache[i].dirty = 0;
5572 dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
5579 /* Initialise the unlinked, root and lost and found directories */
5580 dev->lostNFoundDir = dev->rootDir = NULL;
5581 dev->unlinkedDir = dev->deletedDir = NULL;
5584 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5586 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5589 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5590 YAFFS_ROOT_MODE | S_IFDIR);
5591 dev->lostNFoundDir =
5592 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5593 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5594 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5596 if (dev->isYaffs2) {
5597 dev->useHeaderFileSize = 1;
5600 /* Now scan the flash. */
5602 yaffs_ScanBackwards(dev);
5606 /* Zero out stats */
5607 dev->nPageReads = 0;
5608 dev->nPageWrites = 0;
5609 dev->nBlockErasures = 0;
5611 dev->nRetriedWrites = 0;
5613 dev->nRetiredBlocks = 0;
5615 yaffs_VerifyFreeChunks(dev);
5617 T(YAFFS_TRACE_TRACING,
5618 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5623 void yaffs_Deinitialise(yaffs_Device * dev)
5625 if (dev->isMounted) {
5628 yaffs_DeinitialiseBlocks(dev);
5629 yaffs_DeinitialiseTnodes(dev);
5630 yaffs_DeinitialiseObjects(dev);
5631 if (dev->nShortOpCaches > 0) {
5633 for (i = 0; i < dev->nShortOpCaches; i++) {
5634 YFREE(dev->srCache[i].data);
5637 YFREE(dev->srCache);
5640 YFREE(dev->gcCleanupList);
5642 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5643 YFREE(dev->tempBuffer[i].buffer);
5651 static int yaffs_CountFreeChunks(yaffs_Device * dev)
5656 yaffs_BlockInfo *blk;
5658 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
5660 blk = yaffs_GetBlockInfo(dev, b);
5662 switch (blk->blockState) {
5663 case YAFFS_BLOCK_STATE_EMPTY:
5664 case YAFFS_BLOCK_STATE_ALLOCATING:
5665 case YAFFS_BLOCK_STATE_COLLECTING:
5666 case YAFFS_BLOCK_STATE_FULL:
5668 (dev->nChunksPerBlock - blk->pagesInUse +
5669 blk->softDeletions);
5680 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
5682 /* This is what we report to the outside world */
5685 int nDirtyCacheChunks;
5688 nFree = dev->nFreeChunks;
5690 nFree = yaffs_CountFreeChunks(dev);
5693 /* Now count the number of dirty chunks in the cache and subtract those */
5697 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
5698 if (dev->srCache[i].dirty)
5699 nDirtyCacheChunks++;
5703 nFree -= nDirtyCacheChunks;
5705 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
5714 static int yaffs_freeVerificationFailures;
5716 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
5718 int counted = yaffs_CountFreeChunks(dev);
5720 int difference = dev->nFreeChunks - counted;
5723 T(YAFFS_TRACE_ALWAYS,
5724 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
5725 dev->nFreeChunks, counted, difference));
5726 yaffs_freeVerificationFailures++;
5730 /*---------------------------------------- YAFFS test code ----------------------*/
5732 #define yaffs_CheckStruct(structure,syze, name) \
5733 if(sizeof(structure) != syze) \
5735 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
5736 name,syze,sizeof(structure))); \
5737 return YAFFS_FAIL; \
5740 static int yaffs_CheckStructures(void)
5742 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
5743 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
5744 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
5745 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5746 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
5748 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")