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.18 2005-08-16 02:28:04 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_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62 yaffs_ExtendedTags * tags,
64 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
65 int chunkInNAND, int inScan);
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
68 yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
72 int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
76 int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
82 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
85 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
88 static int yaffs_UnlinkWorker(yaffs_Object * obj);
89 static void yaffs_DestroyObject(yaffs_Object * obj);
91 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
94 loff_t yaffs_GetFileSize(yaffs_Object * obj);
96 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
98 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
100 #ifdef YAFFS_PARANOID
101 static int yaffs_CheckFileSanity(yaffs_Object * in);
103 #define yaffs_CheckFileSanity(in)
106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
107 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
111 * Start of real code.
120 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
122 yaffs_ExtendedTags * tags)
124 chunkInNAND -= dev->chunkOffset;
126 if (dev->readChunkWithTagsFromNAND)
127 return dev->readChunkWithTagsFromNAND(dev, chunkInNAND, buffer,
130 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,
136 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
139 yaffs_ExtendedTags * tags)
141 chunkInNAND -= dev->chunkOffset;
144 tags->sequenceNumber = dev->sequenceNumber;
146 if (!yaffs_ValidateTags(tags)) {
148 (TSTR("Writing uninitialised tags" TENDSTR)));
152 (TSTR("Writing chunk %d tags %d %d" TENDSTR), chunkInNAND,
153 tags->objectId, tags->chunkId));
155 T(YAFFS_TRACE_ERROR, (TSTR("Writing with no tags" TENDSTR)));
159 if (dev->writeChunkWithTagsToNAND)
160 return dev->writeChunkWithTagsToNAND(dev, chunkInNAND, buffer,
163 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,
169 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo)
171 blockNo -= dev->blockOffset;
173 if (dev->markNANDBlockBad)
174 return dev->markNANDBlockBad(dev, blockNo);
176 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev, blockNo);
178 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
180 yaffs_BlockState * state,
181 unsigned *sequenceNumber)
183 blockNo -= dev->blockOffset;
185 if (dev->queryNANDBlock)
186 return dev->queryNANDBlock(dev, blockNo, state, sequenceNumber);
188 return yaffs_TagsCompatabilityQueryNANDBlock(dev, blockNo,
193 static int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,
198 blockInNAND -= dev->blockOffset;
200 dev->nBlockErasures++;
201 result = dev->eraseBlockInNAND(dev, blockInNAND);
203 /* If at first we don't succeed, try again *once*.*/
205 result = dev->eraseBlockInNAND(dev, blockInNAND);
209 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
211 return dev->initialiseNAND(dev);
215 * Temporary buffer manipulations.
218 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
221 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
222 if (dev->tempBuffer[i].line == 0) {
223 dev->tempBuffer[i].line = lineNo;
224 if ((i + 1) > dev->maxTemp) {
225 dev->maxTemp = i + 1;
226 for (j = 0; j <= i; j++)
227 dev->tempBuffer[j].maxLine =
228 dev->tempBuffer[j].line;
231 return dev->tempBuffer[i].buffer;
235 T(YAFFS_TRACE_BUFFERS,
236 (TSTR("Out of temp buffers at line %d, other held by lines:"),
238 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
239 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
244 * If we got here then we have to allocate an unmanaged one
248 dev->unmanagedTempAllocations++;
249 return YMALLOC(dev->nBytesPerChunk);
253 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
257 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
258 if (dev->tempBuffer[i].buffer == buffer) {
259 dev->tempBuffer[i].line = 0;
265 /* assume it is an unmanaged one. */
266 T(YAFFS_TRACE_BUFFERS,
267 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
270 dev->unmanagedTempDeallocations++;
276 * Chunk bitmap manipulations
279 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
281 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
283 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
287 return dev->chunkBits +
288 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
291 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
293 __u8 *blkBits = yaffs_BlockBits(dev, blk);
295 memset(blkBits, 0, dev->chunkBitmapStride);
298 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
300 __u8 *blkBits = yaffs_BlockBits(dev, blk);
302 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
305 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
307 __u8 *blkBits = yaffs_BlockBits(dev, blk);
309 blkBits[chunk / 8] |= (1 << (chunk & 7));
312 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
314 __u8 *blkBits = yaffs_BlockBits(dev, blk);
315 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
318 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
320 __u8 *blkBits = yaffs_BlockBits(dev, blk);
322 for (i = 0; i < dev->chunkBitmapStride; i++) {
331 * Simple hash function. Needs to have a reasonable spread
334 static Y_INLINE int yaffs_HashFunction(int n)
336 return (n % YAFFS_NOBJECT_BUCKETS);
340 * Access functions to useful fake objects
343 yaffs_Object *yaffs_Root(yaffs_Device * dev)
348 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
350 return dev->lostNFoundDir;
355 * Erased NAND checking functions
358 int yaffs_CheckFF(__u8 * buffer, int nBytes)
360 /* Horrible, slow implementation */
369 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
373 int retval = YAFFS_OK;
374 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
375 yaffs_ExtendedTags tags;
377 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
379 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
380 T(YAFFS_TRACE_NANDACCESS,
381 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
385 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
391 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
393 yaffs_ExtendedTags * tags,
402 chunk = yaffs_AllocateChunk(dev, useReserve);
406 /* First check this chunk is erased... */
407 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
408 writeOk = yaffs_CheckChunkErased(dev, chunk);
413 ("**>> yaffs chunk %d was not erased"
417 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
424 * Copy the data into the robustification buffer.
425 * NB We do this at the end to prevent duplicates in the case of a write error.
428 yaffs_HandleWriteChunkOk(dev, chunk, data,
431 yaffs_HandleWriteChunkError(dev, chunk);
435 } while (chunk >= 0 && !writeOk);
439 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
441 dev->nRetriedWrites += (attempts - 1);
448 * Block retiring for handling a broken block.
451 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
454 yaffs_MarkBlockBad(dev, blockInNAND);
456 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
457 YAFFS_BLOCK_STATE_DEAD;
459 dev->nRetiredBlocks++;
463 * Functions for robustisizing TODO
467 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
469 const yaffs_ExtendedTags * tags)
473 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
474 const yaffs_ExtendedTags * tags)
478 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
480 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
482 /* Mark the block for retirement */
483 yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
484 /* Delete the chunk */
485 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
489 /*---------------- Name handling functions ------------*/
491 static __u16 yaffs_CalcNameSum(const YCHAR * name)
496 YUCHAR *bname = (YUCHAR *) name;
498 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
500 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
501 sum += yaffs_toupper(*bname) * i;
512 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
514 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
515 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
516 yaffs_strcpy(obj->shortName, name);
518 obj->shortName[0] = _Y('\0');
521 obj->sum = yaffs_CalcNameSum(name);
524 /*-------------------- TNODES -------------------
526 * List of spare tnodes
527 * The list is hooked together using the first pointer
531 /* yaffs_CreateTnodes creates a bunch more tnodes and
532 * adds them to the tnode free list.
533 * Don't use this function directly
536 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
539 yaffs_Tnode *newTnodes;
540 yaffs_TnodeList *tnl;
545 /* make these things */
547 newTnodes = YMALLOC(nTnodes * sizeof(yaffs_Tnode));
551 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
555 /* Hook them into the free list */
556 for (i = 0; i < nTnodes - 1; i++) {
557 newTnodes[i].internal[0] = &newTnodes[i + 1];
558 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
559 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
563 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
564 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
565 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
567 dev->freeTnodes = newTnodes;
568 dev->nFreeTnodes += nTnodes;
569 dev->nTnodesCreated += nTnodes;
571 /* Now add this bunch of tnodes to a list for freeing up.
572 * NB If we can't add this to the management list it isn't fatal
573 * but it just means we can't free this bunch of tnodes later.
576 tnl = YMALLOC(sizeof(yaffs_TnodeList));
580 ("yaffs: Could not add tnodes to management list" TENDSTR)));
583 tnl->tnodes = newTnodes;
584 tnl->next = dev->allocatedTnodeList;
585 dev->allocatedTnodeList = tnl;
588 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
593 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
595 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
597 yaffs_Tnode *tn = NULL;
599 /* If there are none left make more */
600 if (!dev->freeTnodes) {
601 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
604 if (dev->freeTnodes) {
605 tn = dev->freeTnodes;
606 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
607 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
608 /* Hoosterman, this thing looks like it isn't in the list */
609 T(YAFFS_TRACE_ALWAYS,
610 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
613 dev->freeTnodes = dev->freeTnodes->internal[0];
616 memset(tn, 0, sizeof(yaffs_Tnode));
622 /* FreeTnode frees up a tnode and puts it back on the free list */
623 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
626 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
627 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
628 /* Hoosterman, this thing looks like it is already in the list */
629 T(YAFFS_TRACE_ALWAYS,
630 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
632 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
634 tn->internal[0] = dev->freeTnodes;
635 dev->freeTnodes = tn;
640 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
642 /* Free the list of allocated tnodes */
643 yaffs_TnodeList *tmp;
645 while (dev->allocatedTnodeList) {
646 tmp = dev->allocatedTnodeList->next;
648 YFREE(dev->allocatedTnodeList->tnodes);
649 YFREE(dev->allocatedTnodeList);
650 dev->allocatedTnodeList = tmp;
654 dev->freeTnodes = NULL;
655 dev->nFreeTnodes = 0;
658 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
660 dev->allocatedTnodeList = NULL;
661 dev->freeTnodes = NULL;
662 dev->nFreeTnodes = 0;
663 dev->nTnodesCreated = 0;
667 /* ------------------- End of individual tnode manipulation -----------------*/
669 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
670 * The look up tree is represented by the top tnode and the number of topLevel
671 * in the tree. 0 means only the level 0 tnode is in the tree.
674 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
675 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
676 yaffs_FileStructure * fStruct,
680 yaffs_Tnode *tn = fStruct->top;
682 int requiredTallness;
683 int level = fStruct->topLevel;
685 /* Check sane level and chunk Id */
686 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
690 if (chunkId > YAFFS_MAX_CHUNK_ID) {
694 /* First check we're tall enough (ie enough topLevel) */
696 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
697 requiredTallness = 0;
699 i >>= YAFFS_TNODES_INTERNAL_BITS;
703 if (requiredTallness > fStruct->topLevel) {
704 /* Not tall enough, so we can't find it, return NULL. */
708 /* Traverse down to level 0 */
709 while (level > 0 && tn) {
712 ( YAFFS_TNODES_LEVEL0_BITS +
714 YAFFS_TNODES_INTERNAL_BITS)
716 YAFFS_TNODES_INTERNAL_MASK];
724 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
725 * This happens in two steps:
726 * 1. If the tree isn't tall enough, then make it taller.
727 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
729 * Used when modifying the tree.
732 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
733 yaffs_FileStructure * fStruct,
739 int requiredTallness;
746 /* Check sane level and page Id */
747 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
751 if (chunkId > YAFFS_MAX_CHUNK_ID) {
755 /* First check we're tall enough (ie enough topLevel) */
757 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
758 requiredTallness = 0;
760 x >>= YAFFS_TNODES_INTERNAL_BITS;
765 if (requiredTallness > fStruct->topLevel) {
766 /* Not tall enough,gotta make the tree taller */
767 for (i = fStruct->topLevel; i < requiredTallness; i++) {
769 tn = yaffs_GetTnode(dev);
772 tn->internal[0] = fStruct->top;
776 (TSTR("yaffs: no more tnodes" TENDSTR)));
780 fStruct->topLevel = requiredTallness;
783 /* Traverse down to level 0, adding anything we need */
785 l = fStruct->topLevel;
787 while (l > 0 && tn) {
789 ( YAFFS_TNODES_LEVEL0_BITS +
790 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
791 YAFFS_TNODES_INTERNAL_MASK;
794 if (!tn->internal[x])
795 tn->internal[x] = yaffs_GetTnode(dev);
797 tn = tn->internal[x];
805 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
806 yaffs_ExtendedTags * tags, int objectId,
811 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
812 if (yaffs_CheckChunkBit
813 (dev, theChunk / dev->nChunksPerBlock,
814 theChunk % dev->nChunksPerBlock)) {
815 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
817 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
829 /* DeleteWorker scans backwards through the tnode tree and deletes all the
830 * chunks and tnodes in the file
831 * Returns 1 if the tree was deleted.
832 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
835 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
836 int chunkOffset, int *limit)
841 yaffs_ExtendedTags tags;
843 yaffs_Device *dev = in->myDev;
850 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
852 if (tn->internal[i]) {
853 if (limit && (*limit) < 0) {
857 yaffs_DeleteWorker(in,
865 YAFFS_TNODES_INTERNAL_BITS)
873 tn->internal[i] = NULL;
878 return (allDone) ? 1 : 0;
879 } else if (level == 0) {
882 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
888 YAFFS_TNODES_LEVEL0_BITS) + i;
891 tn->level0[i] << dev->
895 yaffs_FindChunkInGroup(dev,
901 if (foundChunk > 0) {
902 yaffs_DeleteChunk(dev,
919 return (i < 0) ? 1 : 0;
929 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
932 yaffs_BlockInfo *theBlock;
934 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
936 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
938 theBlock->softDeletions++;
943 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
944 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
946 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
949 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
950 __u32 level, int chunkOffset)
955 yaffs_Device *dev = in->myDev;
960 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
962 if (tn->internal[i]) {
964 yaffs_SoftDeleteWorker(in,
970 YAFFS_TNODES_INTERNAL_BITS)
976 tn->internal[i] = NULL;
978 /* Hoosterman... how could this happen? */
982 return (allDone) ? 1 : 0;
983 } else if (level == 0) {
985 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
987 /* Note this does not find the real chunk, only the chunk group.
988 * We make an assumption that a chunk group is not larger than
992 (tn->level0[i] << dev->
995 yaffs_SoftDeleteChunk(dev, theChunk);
1010 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1013 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1014 if (obj->nDataChunks <= 0) {
1015 /* Empty file with no duplicate object headers, just delete it immediately */
1016 yaffs_FreeTnode(obj->myDev,
1017 obj->variant.fileVariant.top);
1018 obj->variant.fileVariant.top = NULL;
1019 T(YAFFS_TRACE_TRACING,
1020 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1022 yaffs_DoGenericObjectDeletion(obj);
1024 yaffs_SoftDeleteWorker(obj,
1025 obj->variant.fileVariant.top,
1026 obj->variant.fileVariant.
1028 obj->softDeleted = 1;
1033 /* Pruning removes any part of the file structure tree that is beyond the
1034 * bounds of the file (ie that does not point to chunks).
1036 * A file should only get pruned when its size is reduced.
1038 * Before pruning, the chunks must be pulled from the tree and the
1039 * level 0 tnode entries must be zeroed out.
1040 * Could also use this for file deletion, but that's probably better handled
1041 * by a special case.
1044 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1045 __u32 level, int del0)
1053 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1054 if (tn->internal[i] && level > 0) {
1056 yaffs_PruneWorker(dev, tn->internal[i],
1058 (i == 0) ? del0 : 1);
1061 if (tn->internal[i]) {
1066 if (hasData == 0 && del0) {
1067 /* Free and return NULL */
1069 yaffs_FreeTnode(dev, tn);
1079 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1080 yaffs_FileStructure * fStruct)
1087 if (fStruct->topLevel > 0) {
1089 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1091 /* Now we have a tree with all the non-zero branches NULL but the height
1092 * is the same as it was.
1093 * Let's see if we can trim internal tnodes to shorten the tree.
1094 * We can do this if only the 0th element in the tnode is in use
1095 * (ie all the non-zero are NULL)
1098 while (fStruct->topLevel && !done) {
1102 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1103 if (tn->internal[i]) {
1109 fStruct->top = tn->internal[0];
1110 fStruct->topLevel--;
1111 yaffs_FreeTnode(dev, tn);
1121 /*-------------------- End of File Structure functions.-------------------*/
1123 /* yaffs_CreateFreeObjects creates a bunch more objects and
1124 * adds them to the object free list.
1126 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1129 yaffs_Object *newObjects;
1130 yaffs_ObjectList *list;
1135 /* make these things */
1136 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1139 T(YAFFS_TRACE_ALLOCATE,
1140 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1144 /* Hook them into the free list */
1145 for (i = 0; i < nObjects - 1; i++) {
1146 newObjects[i].siblings.next =
1147 (struct list_head *)(&newObjects[i + 1]);
1150 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1151 dev->freeObjects = newObjects;
1152 dev->nFreeObjects += nObjects;
1153 dev->nObjectsCreated += nObjects;
1155 /* Now add this bunch of Objects to a list for freeing up. */
1157 list = YMALLOC(sizeof(yaffs_ObjectList));
1159 T(YAFFS_TRACE_ALLOCATE,
1160 (TSTR("Could not add objects to management list" TENDSTR)));
1162 list->objects = newObjects;
1163 list->next = dev->allocatedObjectList;
1164 dev->allocatedObjectList = list;
1171 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1172 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1174 yaffs_Object *tn = NULL;
1176 /* If there are none left make more */
1177 if (!dev->freeObjects) {
1178 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1181 if (dev->freeObjects) {
1182 tn = dev->freeObjects;
1184 (yaffs_Object *) (dev->freeObjects->siblings.next);
1185 dev->nFreeObjects--;
1187 /* Now sweeten it up... */
1189 memset(tn, 0, sizeof(yaffs_Object));
1192 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1193 INIT_LIST_HEAD(&(tn->hardLinks));
1194 INIT_LIST_HEAD(&(tn->hashLink));
1195 INIT_LIST_HEAD(&tn->siblings);
1197 /* Add it to the lost and found directory.
1198 * NB Can't put root or lostNFound in lostNFound so
1199 * check if lostNFound exists first
1201 if (dev->lostNFoundDir) {
1202 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1209 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1214 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1216 obj->fake = 1; /* it is fake so it has no NAND presence... */
1217 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1218 obj->unlinkAllowed = 0; /* ... or unlink it */
1221 obj->yst_mode = mode;
1223 obj->chunkId = 0; /* Not a valid chunk. */
1230 static void yaffs_UnhashObject(yaffs_Object * tn)
1233 yaffs_Device *dev = tn->myDev;
1235 /* If it is still linked into the bucket list, free from the list */
1236 if (!list_empty(&tn->hashLink)) {
1237 list_del_init(&tn->hashLink);
1238 bucket = yaffs_HashFunction(tn->objectId);
1239 dev->objectBucket[bucket].count--;
1244 /* FreeObject frees up a Object and puts it back on the free list */
1245 static void yaffs_FreeObject(yaffs_Object * tn)
1248 yaffs_Device *dev = tn->myDev;
1252 /* We're still hooked up to a cached inode.
1253 * Don't delete now, but mark for later deletion
1255 tn->deferedFree = 1;
1260 yaffs_UnhashObject(tn);
1262 /* Link into the free list. */
1263 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1264 dev->freeObjects = tn;
1265 dev->nFreeObjects++;
1270 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1272 if (obj->deferedFree) {
1273 yaffs_FreeObject(obj);
1279 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1281 /* Free the list of allocated Objects */
1283 yaffs_ObjectList *tmp;
1285 while (dev->allocatedObjectList) {
1286 tmp = dev->allocatedObjectList->next;
1287 YFREE(dev->allocatedObjectList->objects);
1288 YFREE(dev->allocatedObjectList);
1290 dev->allocatedObjectList = tmp;
1293 dev->freeObjects = NULL;
1294 dev->nFreeObjects = 0;
1297 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1301 dev->allocatedObjectList = NULL;
1302 dev->freeObjects = NULL;
1303 dev->nFreeObjects = 0;
1305 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1306 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1307 dev->objectBucket[i].count = 0;
1312 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1317 int lowest = 999999;
1319 /* First let's see if we can find one that's empty. */
1321 for (i = 0; i < 10 && lowest > 0; i++) {
1323 x %= YAFFS_NOBJECT_BUCKETS;
1324 if (dev->objectBucket[x].count < lowest) {
1325 lowest = dev->objectBucket[x].count;
1331 /* If we didn't find an empty list, then try
1332 * looking a bit further for a short one
1335 for (i = 0; i < 10 && lowest > 3; i++) {
1337 x %= YAFFS_NOBJECT_BUCKETS;
1338 if (dev->objectBucket[x].count < lowest) {
1339 lowest = dev->objectBucket[x].count;
1348 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1350 int bucket = yaffs_FindNiceObjectBucket(dev);
1352 /* Now find an object value that has not already been taken
1353 * by scanning the list.
1357 struct list_head *i;
1359 __u32 n = (__u32) bucket;
1361 /* yaffs_CheckObjectHashSanity(); */
1365 n += YAFFS_NOBJECT_BUCKETS;
1366 if (1 || dev->objectBucket[bucket].count > 0) {
1367 list_for_each(i, &dev->objectBucket[bucket].list) {
1368 /* If there is already one in the list */
1370 && list_entry(i, yaffs_Object,
1371 hashLink)->objectId == n) {
1382 static void yaffs_HashObject(yaffs_Object * in)
1384 int bucket = yaffs_HashFunction(in->objectId);
1385 yaffs_Device *dev = in->myDev;
1387 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1388 dev->objectBucket[bucket].count++;
1392 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1394 int bucket = yaffs_HashFunction(number);
1395 struct list_head *i;
1398 list_for_each(i, &dev->objectBucket[bucket].list) {
1399 /* Look if it is in the list */
1401 in = list_entry(i, yaffs_Object, hashLink);
1402 if (in->objectId == number) {
1404 /* Don't tell the VFS about this one if it is defered free */
1405 if (in->deferedFree)
1417 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1418 yaffs_ObjectType type)
1421 yaffs_Object *theObject;
1424 number = yaffs_CreateNewObjectNumber(dev);
1427 theObject = yaffs_AllocateEmptyObject(dev);
1430 theObject->fake = 0;
1431 theObject->renameAllowed = 1;
1432 theObject->unlinkAllowed = 1;
1433 theObject->objectId = number;
1434 yaffs_HashObject(theObject);
1435 theObject->variantType = type;
1436 #ifdef CONFIG_YAFFS_WINCE
1437 yfsd_WinFileTimeNow(theObject->win_atime);
1438 theObject->win_ctime[0] = theObject->win_mtime[0] =
1439 theObject->win_atime[0];
1440 theObject->win_ctime[1] = theObject->win_mtime[1] =
1441 theObject->win_atime[1];
1445 theObject->yst_atime = theObject->yst_mtime =
1446 theObject->yst_ctime = Y_CURRENT_TIME;
1449 case YAFFS_OBJECT_TYPE_FILE:
1450 theObject->variant.fileVariant.fileSize = 0;
1451 theObject->variant.fileVariant.scannedFileSize = 0;
1452 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1453 theObject->variant.fileVariant.topLevel = 0;
1454 theObject->variant.fileVariant.top =
1455 yaffs_GetTnode(dev);
1457 case YAFFS_OBJECT_TYPE_DIRECTORY:
1458 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1461 case YAFFS_OBJECT_TYPE_SYMLINK:
1462 case YAFFS_OBJECT_TYPE_HARDLINK:
1463 case YAFFS_OBJECT_TYPE_SPECIAL:
1464 /* No action required */
1466 case YAFFS_OBJECT_TYPE_UNKNOWN:
1467 /* todo this should not happen */
1475 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1477 yaffs_ObjectType type)
1479 yaffs_Object *theObject = NULL;
1482 theObject = yaffs_FindObjectByNumber(dev, number);
1486 theObject = yaffs_CreateNewObject(dev, number, type);
1493 static YCHAR *yaffs_CloneString(const YCHAR * str)
1495 YCHAR *newStr = NULL;
1498 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1499 yaffs_strcpy(newStr, str);
1507 * Mknod (create) a new object.
1508 * equivalentObject only has meaning for a hard link;
1509 * aliasString only has meaning for a sumlink.
1510 * rdev only has meaning for devices (a subset of special objects)
1513 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1514 yaffs_Object * parent,
1519 yaffs_Object * equivalentObject,
1520 const YCHAR * aliasString, __u32 rdev)
1524 yaffs_Device *dev = parent->myDev;
1526 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1527 if (yaffs_FindObjectByName(parent, name)) {
1531 in = yaffs_CreateNewObject(dev, -1, type);
1536 in->variantType = type;
1538 in->yst_mode = mode;
1540 #ifdef CONFIG_YAFFS_WINCE
1541 yfsd_WinFileTimeNow(in->win_atime);
1542 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1543 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1546 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1548 in->yst_rdev = rdev;
1552 in->nDataChunks = 0;
1554 yaffs_SetObjectName(in, name);
1557 yaffs_AddObjectToDirectory(parent, in);
1559 in->myDev = parent->myDev;
1562 case YAFFS_OBJECT_TYPE_SYMLINK:
1563 in->variant.symLinkVariant.alias =
1564 yaffs_CloneString(aliasString);
1566 case YAFFS_OBJECT_TYPE_HARDLINK:
1567 in->variant.hardLinkVariant.equivalentObject =
1569 in->variant.hardLinkVariant.equivalentObjectId =
1570 equivalentObject->objectId;
1571 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1573 case YAFFS_OBJECT_TYPE_FILE:
1574 case YAFFS_OBJECT_TYPE_DIRECTORY:
1575 case YAFFS_OBJECT_TYPE_SPECIAL:
1576 case YAFFS_OBJECT_TYPE_UNKNOWN:
1581 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1582 /* Could not create the object header, fail the creation */
1583 yaffs_DestroyObject(in);
1592 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1593 __u32 mode, __u32 uid, __u32 gid)
1595 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1596 uid, gid, NULL, NULL, 0);
1599 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1600 __u32 mode, __u32 uid, __u32 gid)
1602 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1603 mode, uid, gid, NULL, NULL, 0);
1606 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1607 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1609 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1610 uid, gid, NULL, NULL, rdev);
1613 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1614 __u32 mode, __u32 uid, __u32 gid,
1615 const YCHAR * alias)
1617 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1618 uid, gid, NULL, alias, 0);
1621 /* yaffs_Link returns the object id of the equivalent object.*/
1622 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1623 yaffs_Object * equivalentObject)
1625 /* Get the real object in case we were fed a hard link as an equivalent object */
1626 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1628 if (yaffs_MknodObject
1629 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1630 equivalentObject, NULL, 0)) {
1631 return equivalentObject;
1638 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1639 const YCHAR * newName, int force, int shadows)
1644 yaffs_Object *existingTarget;
1646 if (newDir == NULL) {
1647 newDir = obj->parent; /* use the old directory */
1650 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1651 T(YAFFS_TRACE_ALWAYS,
1653 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1658 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1659 if (obj->myDev->isYaffs2) {
1660 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1662 unlinkOp = (newDir == obj->myDev->unlinkedDir
1663 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1666 deleteOp = (newDir == obj->myDev->deletedDir);
1668 existingTarget = yaffs_FindObjectByName(newDir, newName);
1670 /* If the object is a file going into the unlinked directory,
1671 * then it is OK to just stuff it in since duplicate names are allowed.
1672 * else only proceed if the new name does not exist and if we're putting
1673 * it into a directory.
1680 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1681 yaffs_SetObjectName(obj, newName);
1684 yaffs_AddObjectToDirectory(newDir, obj);
1689 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1690 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1697 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1698 yaffs_Object * newDir, const YCHAR * newName)
1701 yaffs_Object *existingTarget;
1704 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1705 /* Special case for case insemsitive systems (eg. WinCE).
1706 * While look-up is case insensitive, the name isn't.
1707 * Therefore we might want to change x.txt to X.txt
1709 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1714 obj = yaffs_FindObjectByName(oldDir, oldName);
1716 if (obj && obj->renameAllowed) {
1718 /* Now do the handling for an existing target, if there is one */
1720 existingTarget = yaffs_FindObjectByName(newDir, newName);
1721 if (existingTarget &&
1722 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1723 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1724 /* There is a target that is a non-empty directory, so we fail */
1725 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1726 } else if (existingTarget && existingTarget != obj) {
1727 /* Nuke the target first, using shadowing,
1728 * but only if it isn't the same object
1730 yaffs_ChangeObjectName(obj, newDir, newName, force,
1731 existingTarget->objectId);
1732 yaffs_Unlink(newDir, newName);
1735 return yaffs_ChangeObjectName(obj, newDir, newName, force, 0);
1740 /*------------------------- Block Management and Page Allocation ----------------*/
1742 static int yaffs_InitialiseBlocks(yaffs_Device * dev, int nBlocks)
1744 dev->allocationBlock = -1; /* force it to get a new one */
1746 /* Todo we're assuming the malloc will pass. */
1747 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1749 /* Set up dynamic blockinfo stuff. */
1750 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8;
1751 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1752 if (dev->blockInfo && dev->chunkBits) {
1753 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1754 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1762 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1764 YFREE(dev->blockInfo);
1765 dev->blockInfo = NULL;
1766 YFREE(dev->chunkBits);
1767 dev->chunkBits = NULL;
1770 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1771 yaffs_BlockInfo * bi)
1778 return 1; /* disqualification only applies to yaffs2. */
1780 if (!bi->hasShrinkHeader)
1781 return 1; /* can gc */
1783 /* Find the oldest dirty sequence number if we don't know it and save it
1784 * so we don't have to keep recomputing it.
1786 if (!dev->oldestDirtySequence) {
1787 seq = dev->sequenceNumber;
1789 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1791 b = yaffs_GetBlockInfo(dev, i);
1792 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1793 (b->pagesInUse - b->softDeletions) <
1794 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1795 seq = b->sequenceNumber;
1798 dev->oldestDirtySequence = seq;
1801 /* Can't do gc of this block if there are any blocks older than this one that have
1804 return (bi->sequenceNumber <= dev->oldestDirtySequence);
1810 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1811 * for garbage collection.
1814 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1818 int b = dev->currentDirtyChecker;
1824 yaffs_BlockInfo *bi;
1825 static int nonAggressiveSkip = 0;
1827 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1829 * else (we're doing a leasurely gc), then we only bother to do this if the
1830 * block has only a few pages in use.
1833 nonAggressiveSkip--;
1835 if (!aggressive && (nonAggressiveSkip > 0)) {
1840 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1844 dev->internalEndBlock - dev->internalStartBlock + 1;
1847 dev->internalEndBlock - dev->internalStartBlock + 1;
1848 iterations = iterations / 16;
1849 if (iterations > 200) {
1854 for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1856 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1857 b = dev->internalStartBlock;
1860 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1861 T(YAFFS_TRACE_ERROR,
1862 (TSTR("**>> Block %d is not valid" TENDSTR), b));
1866 bi = yaffs_GetBlockInfo(dev, b);
1868 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1869 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1870 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1872 pagesInUse = (bi->pagesInUse - bi->softDeletions);
1876 dev->currentDirtyChecker = b;
1880 (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1881 dev->nChunksPerBlock - pagesInUse));
1884 dev->oldestDirtySequence = 0;
1887 nonAggressiveSkip = 4;
1893 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1895 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1899 /* If the block is still healthy erase it and mark as clean.
1900 * If the block has had a data failure, then retire it.
1902 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1904 if (!bi->needsRetiring) {
1905 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1907 dev->nErasureFailures++;
1908 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1909 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1913 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
1915 for (i = 0; i < dev->nChunksPerBlock; i++) {
1916 if (!yaffs_CheckChunkErased
1917 (dev, blockNo * dev->nChunksPerBlock + i)) {
1918 T(YAFFS_TRACE_ERROR,
1920 (">>Block %d erasure supposedly OK, but chunk %d not erased"
1921 TENDSTR), blockNo, i));
1927 /* Clean it up... */
1928 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1929 dev->nErasedBlocks++;
1931 bi->softDeletions = 0;
1932 bi->hasShrinkHeader = 0;
1933 yaffs_ClearChunkBits(dev, blockNo);
1935 T(YAFFS_TRACE_ERASE,
1936 (TSTR("Erased block %d" TENDSTR), blockNo));
1938 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
1940 yaffs_RetireBlock(dev, blockNo);
1941 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1942 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
1946 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
1950 yaffs_BlockInfo *bi;
1952 if (dev->nErasedBlocks < 1) {
1953 /* Hoosterman we've got a problem.
1954 * Can't get space to gc
1956 T(YAFFS_TRACE_ERROR,
1957 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
1962 /* Find an empty block. */
1964 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1965 dev->allocationBlockFinder++;
1966 if (dev->allocationBlockFinder < dev->internalStartBlock
1967 || dev->allocationBlockFinder > dev->internalEndBlock) {
1968 dev->allocationBlockFinder = dev->internalStartBlock;
1971 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
1973 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
1974 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1975 dev->sequenceNumber++;
1976 bi->sequenceNumber = dev->sequenceNumber;
1977 dev->nErasedBlocks--;
1978 T(YAFFS_TRACE_ALLOCATE,
1979 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
1980 dev->allocationBlockFinder, dev->sequenceNumber,
1981 dev->nErasedBlocks));
1982 return dev->allocationBlockFinder;
1986 T(YAFFS_TRACE_ALWAYS,
1988 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
1989 TENDSTR), dev->nErasedBlocks));
1996 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
1998 int reservedChunks = (dev->nReservedBlocks * dev->nChunksPerBlock);
1999 return (dev->nFreeChunks > reservedChunks);
2002 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2005 yaffs_BlockInfo *bi;
2007 if (dev->allocationBlock < 0) {
2008 /* Get next block to allocate off */
2009 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2010 dev->allocationPage = 0;
2013 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2014 /* Not enough space to allocate unless we're allowed to use the reserve. */
2018 if (dev->nErasedBlocks < dev->nReservedBlocks
2019 && dev->allocationPage == 0) {
2020 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2023 /* Next page please.... */
2024 if (dev->allocationBlock >= 0) {
2025 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2027 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2028 dev->allocationPage;
2030 yaffs_SetChunkBit(dev, dev->allocationBlock,
2031 dev->allocationPage);
2033 dev->allocationPage++;
2037 /* If the block is full set the state to full */
2038 if (dev->allocationPage >= dev->nChunksPerBlock) {
2039 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2040 dev->allocationBlock = -1;
2046 T(YAFFS_TRACE_ERROR,
2047 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2052 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2056 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2058 if (dev->allocationBlock > 0) {
2059 n += (dev->nChunksPerBlock - dev->allocationPage);
2066 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2072 int retVal = YAFFS_OK;
2076 int chunksBefore = yaffs_GetErasedChunks(dev);
2079 yaffs_ExtendedTags tags;
2081 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2083 yaffs_Object *object;
2085 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2087 T(YAFFS_TRACE_TRACING,
2088 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2089 bi->pagesInUse, bi->hasShrinkHeader));
2091 /*yaffs_VerifyFreeChunks(dev); */
2093 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2095 /* Take off the number of soft deleted entries because
2096 * they're going to get really deleted during GC.
2098 dev->nFreeChunks -= bi->softDeletions;
2102 if (!yaffs_StillSomeChunkBits(dev, block)) {
2103 T(YAFFS_TRACE_TRACING,
2105 ("Collecting block %d that has no chunks in use" TENDSTR),
2107 yaffs_BlockBecameDirty(dev, block);
2110 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2112 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2113 chunkInBlock < dev->nChunksPerBlock
2114 && yaffs_StillSomeChunkBits(dev, block);
2115 chunkInBlock++, oldChunk++) {
2116 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2118 /* This page is in use and might need to be copied off */
2122 yaffs_InitialiseTags(&tags);
2124 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2128 yaffs_FindObjectByNumber(dev,
2131 T(YAFFS_TRACE_GC_DETAIL,
2133 ("Collecting page %d, %d %d %d " TENDSTR),
2134 chunkInBlock, tags.objectId, tags.chunkId,
2138 T(YAFFS_TRACE_ERROR,
2140 ("page %d in gc has no object "
2141 TENDSTR), oldChunk));
2144 if (object && object->deleted
2145 && tags.chunkId != 0) {
2146 /* Data chunk in a deleted file, throw it away
2147 * It's a soft deleted data chunk,
2148 * No need to copy this, just forget about it and
2149 * fix up the object.
2152 object->nDataChunks--;
2154 if (object->nDataChunks <= 0) {
2155 /* remeber to clean up the object */
2156 dev->gcCleanupList[cleanups] =
2162 /* Todo object && object->deleted && object->nDataChunks == 0 */
2164 /* Deleted object header with no data chunks.
2165 * Can be discarded and the file deleted.
2167 object->chunkId = 0;
2168 yaffs_FreeTnode(object->myDev,
2171 object->variant.fileVariant.top = NULL;
2172 yaffs_DoGenericObjectDeletion(object);
2174 } else if (object) {
2175 /* It's either a data chunk in a live file or
2176 * an ObjectHeader, so we're interested in it.
2177 * NB Need to keep the ObjectHeaders of deleted files
2178 * until the whole file has been deleted off
2180 tags.serialNumber++;
2184 if (tags.chunkId == 0) {
2185 /* It is an object Id,
2186 * We need to nuke the shrinkheader flags first
2187 * We no longer want the shrinkHeader flag since its work is done
2188 * and if it is left in place it will mess up scanning.
2189 * Also, clear out any shadowing stuff
2192 yaffs_ObjectHeader *oh;
2193 oh = (yaffs_ObjectHeader *)buffer;
2195 oh->shadowsObject = -1;
2196 tags.extraShadows = 0;
2197 tags.extraIsShrinkHeader = 0;
2201 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2204 retVal = YAFFS_FAIL;
2207 /* Ok, now fix up the Tnodes etc. */
2209 if (tags.chunkId == 0) {
2211 object->chunkId = newChunk;
2212 object->serial = tags.serialNumber;
2214 /* It's a data chunk */
2215 yaffs_PutChunkIntoFile
2223 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2228 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2231 /* Do any required cleanups */
2232 for (i = 0; i < cleanups; i++) {
2233 /* Time to delete the file too */
2235 yaffs_FindObjectByNumber(dev,
2236 dev->gcCleanupList[i]);
2238 yaffs_FreeTnode(dev,
2239 object->variant.fileVariant.
2241 object->variant.fileVariant.top = NULL;
2244 ("yaffs: About to finally delete object %d"
2245 TENDSTR), object->objectId));
2246 yaffs_DoGenericObjectDeletion(object);
2253 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2256 ("gc did not increase free chunks before %d after %d"
2257 TENDSTR), chunksBefore, chunksAfter));
2265 /* New garbage collector
2266 * If we're very low on erased blocks then we do aggressive garbage collection
2267 * otherwise we do "leasurely" garbage collection.
2268 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2269 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2271 * The idea is to help clear out space in a more spread-out manner.
2272 * Dunno if it really does anything useful.
2274 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2278 int gcOk = YAFFS_OK;
2281 if (dev->isDoingGC) {
2282 /* Bail out so we don't get recursive gc */
2286 /* This loop should pass the first time.
2287 * We'll only see looping here if the erase of the collected block fails.
2292 if (dev->nErasedBlocks < dev->nReservedBlocks) {
2293 /* We need a block soon...*/
2296 /* We're in no hurry */
2300 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2303 dev->garbageCollections++;
2305 dev->passiveGarbageCollections++;
2310 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2311 dev->nErasedBlocks, aggressive));
2313 gcOk = yaffs_GarbageCollectBlock(dev, block);
2316 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2319 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2320 TENDSTR), dev->nErasedBlocks, maxTries, block));
2322 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2325 return aggressive ? gcOk : YAFFS_OK;
2328 /*------------------------- TAGS --------------------------------*/
2330 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2333 return (tags->chunkId == chunkInObject &&
2334 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2339 /*-------------------- Data file manipulation -----------------*/
2341 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2342 yaffs_ExtendedTags * tags)
2344 /*Get the Tnode, then get the level 0 offset chunk offset */
2347 yaffs_ExtendedTags localTags;
2350 yaffs_Device *dev = in->myDev;
2353 /* Passed a NULL, so use our own tags space */
2357 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2361 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] <<
2362 dev->chunkGroupBits;
2365 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2371 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2372 yaffs_ExtendedTags * tags)
2374 /* Get the Tnode, then get the level 0 offset chunk offset */
2377 yaffs_ExtendedTags localTags;
2379 yaffs_Device *dev = in->myDev;
2383 /* Passed a NULL, so use our own tags space */
2387 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2392 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->
2396 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2399 /* Delete the entry in the filestructure (if found) */
2401 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2404 /*T(("No level 0 found for %d\n", chunkInInode)); */
2408 /* T(("Could not find %d to delete\n",chunkInInode)); */
2413 #ifdef YAFFS_PARANOID
2415 static int yaffs_CheckFileSanity(yaffs_Object * in)
2423 yaffs_Tags localTags;
2424 yaffs_Tags *tags = &localTags;
2428 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2429 /* T(("Object not a file\n")); */
2433 objId = in->objectId;
2434 fSize = in->variant.fileVariant.fileSize;
2436 (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2438 for (chunk = 1; chunk <= nChunks; chunk++) {
2439 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2445 tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->
2446 myDev->chunkGroupBits;
2448 if (yaffs_CheckChunkBits
2449 (dev, theChunk / dev->nChunksPerBlock,
2450 theChunk % dev->nChunksPerBlock)) {
2452 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2456 (tags, in->objectId, chunk, chunkDeleted)) {
2466 /* T(("No level 0 found for %d\n", chunk)); */
2470 return failed ? YAFFS_FAIL : YAFFS_OK;
2475 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2476 int chunkInNAND, int inScan)
2478 /* NB inScan is zero unless scanning.
2479 * For forward scanning, inScan is > 0;
2480 * for backward scanning inScan is < 0
2484 yaffs_Device *dev = in->myDev;
2486 yaffs_ExtendedTags existingTags;
2487 yaffs_ExtendedTags newTags;
2488 unsigned existingSerial, newSerial;
2490 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2491 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2492 * If it is not during Scanning then something went wrong!
2495 T(YAFFS_TRACE_ERROR,
2497 ("yaffs tragedy:attempt to put data chunk into a non-file"
2502 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2506 tn = yaffs_AddOrFindLevel0Tnode(dev, &in->variant.fileVariant,
2512 existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2515 /* If we're scanning then we need to test for duplicates
2516 * NB This does not need to be efficient since it should only ever
2517 * happen when the power fails during a write, then only one
2518 * chunk should ever be affected.
2520 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2521 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2524 if (existingChunk != 0) {
2525 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2526 * thus we have to do a FindChunkInFile to get the real chunk id.
2528 * We have a duplicate now we need to decide which one to use:
2530 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2531 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2532 * YAFFS1: Get both sets of tags and compare serial numbers.
2536 /* Only do this for forward scanning */
2537 yaffs_ReadChunkWithTagsFromNAND(dev,
2541 /* Do a proper find */
2543 yaffs_FindChunkInFile(in, chunkInInode,
2547 if (existingChunk <= 0) {
2548 /*Hoosterman - how did this happen? */
2550 T(YAFFS_TRACE_ERROR,
2552 ("yaffs tragedy: existing chunk < 0 in scan"
2557 /* NB The deleted flags should be false, otherwise the chunks will
2558 * not be loaded during a scan
2561 newSerial = newTags.serialNumber;
2562 existingSerial = existingTags.serialNumber;
2565 (in->myDev->isYaffs2 ||
2566 existingChunk <= 0 ||
2567 ((existingSerial + 1) & 3) == newSerial)) {
2568 /* Forward scanning.
2570 * Delete the old one and drop through to update the tnode
2572 yaffs_DeleteChunk(dev, existingChunk, 1,
2575 /* Backward scanning or we want to use the existing one
2577 * Delete the new one and return early so that the tnode isn't changed
2579 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2587 if (existingChunk == 0) {
2591 tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] =
2592 (chunkInNAND >> dev->chunkGroupBits);
2597 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2600 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2602 if (chunkInNAND >= 0) {
2603 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2606 T(YAFFS_TRACE_NANDACCESS,
2607 (TSTR("Chunk %d not found zero instead" TENDSTR),
2609 /* get sane (zero) data if you read a hole */
2610 memset(buffer, 0, in->myDev->nBytesPerChunk);
2616 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2620 yaffs_ExtendedTags tags;
2621 yaffs_BlockInfo *bi;
2627 block = chunkId / dev->nChunksPerBlock;
2628 page = chunkId % dev->nChunksPerBlock;
2630 bi = yaffs_GetBlockInfo(dev, block);
2632 T(YAFFS_TRACE_DELETION,
2633 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2636 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2638 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
2640 /* Read data before write, to ensure correct ecc
2641 * if we're using MTD verification under Linux
2643 yaffs_ReadChunkFromNAND(dev, chunkId, NULL, &spare, 0);
2646 yaffs_InitialiseTags(&tags);
2648 tags.chunkDeleted = 1;
2650 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2651 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2653 dev->nUnmarkedDeletions++;
2656 /* Pull out of the management area.
2657 * If the whole block became dirty, this will kick off an erasure.
2659 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2660 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2661 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2662 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2665 yaffs_ClearChunkBit(dev, block, page);
2669 if (bi->pagesInUse == 0 &&
2670 !bi->hasShrinkHeader &&
2671 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2672 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2673 yaffs_BlockBecameDirty(dev, block);
2677 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2682 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2683 const __u8 * buffer, int nBytes,
2686 /* Find old chunk Need to do this to get serial number
2687 * Write new one and patch into tree.
2688 * Invalidate old tags.
2692 yaffs_ExtendedTags prevTags;
2695 yaffs_ExtendedTags newTags;
2697 yaffs_Device *dev = in->myDev;
2699 yaffs_CheckGarbageCollection(dev);
2701 /* Get the previous chunk at this location in the file if it exists */
2702 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2704 /* Set up new tags */
2705 yaffs_InitialiseTags(&newTags);
2707 newTags.chunkId = chunkInInode;
2708 newTags.objectId = in->objectId;
2709 newTags.serialNumber =
2710 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2711 newTags.byteCount = nBytes;
2714 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2717 if (newChunkId >= 0) {
2718 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2720 if (prevChunkId >= 0) {
2721 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2725 yaffs_CheckFileSanity(in);
2731 /* UpdateObjectHeader updates the header on NAND for an object.
2732 * If name is not NULL, then that new name is used.
2734 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2735 int isShrink, int shadows)
2738 yaffs_BlockInfo *bi;
2740 yaffs_Device *dev = in->myDev;
2746 yaffs_ExtendedTags newTags;
2748 __u8 *buffer = NULL;
2749 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2751 yaffs_ObjectHeader *oh = NULL;
2753 if (!in->fake || force) {
2755 yaffs_CheckGarbageCollection(dev);
2757 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2758 oh = (yaffs_ObjectHeader *) buffer;
2760 prevChunkId = in->chunkId;
2762 if (prevChunkId >= 0) {
2763 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2765 memcpy(oldName, oh->name, sizeof(oh->name));
2768 memset(buffer, 0xFF, dev->nBytesPerChunk);
2770 oh->type = in->variantType;
2771 oh->yst_mode = in->yst_mode;
2772 oh->shadowsObject = shadows;
2774 #ifdef CONFIG_YAFFS_WINCE
2775 oh->win_atime[0] = in->win_atime[0];
2776 oh->win_ctime[0] = in->win_ctime[0];
2777 oh->win_mtime[0] = in->win_mtime[0];
2778 oh->win_atime[1] = in->win_atime[1];
2779 oh->win_ctime[1] = in->win_ctime[1];
2780 oh->win_mtime[1] = in->win_mtime[1];
2782 oh->yst_uid = in->yst_uid;
2783 oh->yst_gid = in->yst_gid;
2784 oh->yst_atime = in->yst_atime;
2785 oh->yst_mtime = in->yst_mtime;
2786 oh->yst_ctime = in->yst_ctime;
2787 oh->yst_rdev = in->yst_rdev;
2790 oh->parentObjectId = in->parent->objectId;
2792 oh->parentObjectId = 0;
2795 if (name && *name) {
2796 memset(oh->name, 0, sizeof(oh->name));
2797 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2798 } else if (prevChunkId) {
2799 memcpy(oh->name, oldName, sizeof(oh->name));
2801 memset(oh->name, 0, sizeof(oh->name));
2804 oh->isShrink = isShrink;
2806 switch (in->variantType) {
2807 case YAFFS_OBJECT_TYPE_UNKNOWN:
2808 /* Should not happen */
2810 case YAFFS_OBJECT_TYPE_FILE:
2812 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2813 || oh->parentObjectId ==
2814 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2815 fileVariant.fileSize;
2817 case YAFFS_OBJECT_TYPE_HARDLINK:
2818 oh->equivalentObjectId =
2819 in->variant.hardLinkVariant.equivalentObjectId;
2821 case YAFFS_OBJECT_TYPE_SPECIAL:
2824 case YAFFS_OBJECT_TYPE_DIRECTORY:
2827 case YAFFS_OBJECT_TYPE_SYMLINK:
2828 yaffs_strncpy(oh->alias,
2829 in->variant.symLinkVariant.alias,
2830 YAFFS_MAX_ALIAS_LENGTH);
2831 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2836 yaffs_InitialiseTags(&newTags);
2838 newTags.chunkId = 0;
2839 newTags.objectId = in->objectId;
2840 newTags.serialNumber = in->serial;
2842 /* Add extra info for file header */
2844 newTags.extraHeaderInfoAvailable = 1;
2845 newTags.extraParentObjectId = oh->parentObjectId;
2846 newTags.extraFileLength = oh->fileSize;
2847 newTags.extraIsShrinkHeader = oh->isShrink;
2848 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2849 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2850 newTags.extraObjectType = in->variantType;
2852 /* Create new chunk in NAND */
2854 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2855 (prevChunkId >= 0) ? 1 : 0);
2857 if (newChunkId >= 0) {
2859 in->chunkId = newChunkId;
2861 if (prevChunkId >= 0) {
2862 yaffs_DeleteChunk(dev, prevChunkId, 1,
2868 /* If this was a shrink, then mark the block that the chunk lives on */
2870 bi = yaffs_GetBlockInfo(in->myDev,
2871 newChunkId /in->myDev-> nChunksPerBlock);
2872 bi->hasShrinkHeader = 1;
2877 retVal = newChunkId;
2882 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2887 /*------------------------ Short Operations Cache ----------------------------------------
2888 * In many situations where there is no high level buffering (eg WinCE) a lot of
2889 * reads might be short sequential reads, and a lot of writes may be short
2890 * sequential writes. eg. scanning/writing a jpeg file.
2891 * In these cases, a short read/write cache can provide a huge perfomance benefit
2892 * with dumb-as-a-rock code.
2893 * In Linux, the page cache provides read buffering aand the short op cache provides write
2896 * There are a limited number (~10) of cache chunks per device so that we don't
2897 * need a very intelligent search.
2900 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2902 yaffs_Device *dev = obj->myDev;
2903 int lowest = -99; /* Stop compiler whining. */
2905 yaffs_ChunkCache *cache;
2906 int chunkWritten = 0;
2907 int nCaches = obj->myDev->nShortOpCaches;
2913 /* Find the dirty cache for this object with the lowest chunk id. */
2914 for (i = 0; i < nCaches; i++) {
2915 if (dev->srCache[i].object == obj &&
2916 dev->srCache[i].dirty) {
2918 || dev->srCache[i].chunkId <
2920 cache = &dev->srCache[i];
2921 lowest = cache->chunkId;
2926 if (cache && !cache->locked) {
2927 /* Write it out and free it up */
2930 yaffs_WriteChunkDataToObject(cache->object,
2936 cache->object = NULL;
2939 } while (cache && chunkWritten > 0);
2942 /* Hoosterman, disk full while writing cache out. */
2943 T(YAFFS_TRACE_ERROR,
2944 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
2951 /* Grab us a cache chunk for use.
2952 * First look for an empty one.
2953 * Then look for the least recently used non-dirty one.
2954 * Then look for the least recently used dirty one...., flush and look again.
2956 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
2962 if (dev->nShortOpCaches > 0) {
2963 for (i = 0; i < dev->nShortOpCaches; i++) {
2964 if (!dev->srCache[i].object)
2965 return &dev->srCache[i];
2971 usage = 0; /* just to stop the compiler grizzling */
2973 for (i = 0; i < dev->nShortOpCaches; i++) {
2974 if (!dev->srCache[i].dirty &&
2975 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
2977 usage = dev->srCache[i].lastUse;
2983 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
2990 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
2992 yaffs_ChunkCache *cache;
2993 yaffs_Object *theObj;
2998 if (dev->nShortOpCaches > 0) {
2999 /* Try find a non-dirty one... */
3001 cache = yaffs_GrabChunkCacheWorker(dev);
3004 /* They were all dirty, find the last recently used object and flush
3005 * its cache, then find again.
3006 * NB what's here is not very accurate, we actually flush the object
3007 * the last recently used page.
3010 /* With locking we can't assume we can use entry zero */
3017 for (i = 0; i < dev->nShortOpCaches; i++) {
3018 if (dev->srCache[i].object &&
3019 !dev->srCache[i].locked &&
3020 (dev->srCache[i].lastUse < usage || !cache))
3022 usage = dev->srCache[i].lastUse;
3023 theObj = dev->srCache[i].object;
3024 cache = &dev->srCache[i];
3029 if (!cache || cache->dirty) {
3030 /* Flush and try again */
3031 yaffs_FlushFilesChunkCache(theObj);
3032 cache = yaffs_GrabChunkCacheWorker(dev);
3042 /* Find a cached chunk */
3043 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3046 yaffs_Device *dev = obj->myDev;
3048 if (dev->nShortOpCaches > 0) {
3049 for (i = 0; i < dev->nShortOpCaches; i++) {
3050 if (dev->srCache[i].object == obj &&
3051 dev->srCache[i].chunkId == chunkId) {
3054 return &dev->srCache[i];
3061 /* Mark the chunk for the least recently used algorithym */
3062 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3066 if (dev->nShortOpCaches > 0) {
3067 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3068 /* Reset the cache usages */
3070 for (i = 1; i < dev->nShortOpCaches; i++) {
3071 dev->srCache[i].lastUse = 0;
3078 cache->lastUse = dev->srLastUse;
3086 /* Invalidate a single cache page.
3087 * Do this when a whole page gets written,
3088 * ie the short cache for this page is no longer valid.
3090 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3092 if (object->myDev->nShortOpCaches > 0) {
3093 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3096 cache->object = NULL;
3101 /* Invalidate all the cache pages associated with this object
3102 * Do this whenever ther file is deleted or resized.
3104 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3107 yaffs_Device *dev = in->myDev;
3109 if (dev->nShortOpCaches > 0) {
3110 /* Invalidate it. */
3111 for (i = 0; i < dev->nShortOpCaches; i++) {
3112 if (dev->srCache[i].object == in) {
3113 dev->srCache[i].object = NULL;
3119 /*--------------------- File read/write ------------------------
3120 * Read and write have very similar structures.
3121 * In general the read/write has three parts to it
3122 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3123 * Some complete chunks
3124 * An incomplete chunk to end off with
3126 * Curve-balls: the first chunk might also be the last chunk.
3129 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3138 yaffs_ChunkCache *cache;
3145 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3146 start = offset % dev->nBytesPerChunk;
3148 /* OK now check for the curveball where the start and end are in
3151 if ((start + n) < dev->nBytesPerChunk) {
3154 nToCopy = dev->nBytesPerChunk - start;
3157 cache = yaffs_FindChunkCache(in, chunk);
3159 /* If the chunk is already in the cache or it is less than a whole chunk
3160 * then use the cache (if there is caching)
3161 * else bypass the cache.
3163 if (cache || nToCopy != dev->nBytesPerChunk) {
3164 if (dev->nShortOpCaches > 0) {
3166 /* If we can't find the data in the cache, then load it up. */
3169 cache = yaffs_GrabChunkCache(in->myDev);
3171 cache->chunkId = chunk;
3174 yaffs_ReadChunkDataFromObject(in, chunk,
3180 yaffs_UseChunkCache(dev, cache, 0);
3184 #ifdef CONFIG_YAFFS_WINCE
3185 yfsd_UnlockYAFFS(TRUE);
3187 memcpy(buffer, &cache->data[start], nToCopy);
3189 #ifdef CONFIG_YAFFS_WINCE
3190 yfsd_LockYAFFS(TRUE);
3194 /* Read into the local buffer then copy..*/
3197 yaffs_GetTempBuffer(dev, __LINE__);
3198 yaffs_ReadChunkDataFromObject(in, chunk,
3200 #ifdef CONFIG_YAFFS_WINCE
3201 yfsd_UnlockYAFFS(TRUE);
3203 memcpy(buffer, &localBuffer[start], nToCopy);
3205 #ifdef CONFIG_YAFFS_WINCE
3206 yfsd_LockYAFFS(TRUE);
3208 yaffs_ReleaseTempBuffer(dev, localBuffer,
3213 #ifdef CONFIG_YAFFS_WINCE
3214 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3216 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3217 * This is because we otherwise screw up WinCE's memory mapper
3219 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3221 #ifdef CONFIG_YAFFS_WINCE
3222 yfsd_UnlockYAFFS(TRUE);
3224 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3226 #ifdef CONFIG_YAFFS_WINCE
3227 yfsd_LockYAFFS(TRUE);
3228 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3232 /* A full chunk. Read directly into the supplied buffer. */
3233 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3247 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3248 int nBytes, int writeThrough)
3257 int startOfWrite = offset;
3258 int chunkWritten = 0;
3265 while (n > 0 && chunkWritten >= 0) {
3266 chunk = offset / dev->nBytesPerChunk + 1;
3267 start = offset % dev->nBytesPerChunk;
3269 /* OK now check for the curveball where the start and end are in
3273 if ((start + n) < dev->nBytesPerChunk) {
3276 /* Now folks, to calculate how many bytes to write back....
3277 * If we're overwriting and not writing to then end of file then
3278 * we need to write back as much as was there before.
3282 in->variant.fileVariant.fileSize -
3283 ((chunk - 1) * dev->nBytesPerChunk);
3285 if (nBytesRead > dev->nBytesPerChunk) {
3286 nBytesRead = dev->nBytesPerChunk;
3291 (start + n)) ? nBytesRead : (start + n);
3294 nToCopy = dev->nBytesPerChunk - start;
3295 nToWriteBack = dev->nBytesPerChunk;
3298 if (nToCopy != dev->nBytesPerChunk) {
3299 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3300 if (dev->nShortOpCaches > 0) {
3301 yaffs_ChunkCache *cache;
3302 /* If we can't find the data in the cache, then load the cache */
3303 cache = yaffs_FindChunkCache(in, chunk);
3305 && yaffs_CheckSpaceForAllocation(in->
3307 cache = yaffs_GrabChunkCache(in->myDev);
3309 cache->chunkId = chunk;
3312 yaffs_ReadChunkDataFromObject(in, chunk,
3318 yaffs_UseChunkCache(dev, cache, 1);
3320 #ifdef CONFIG_YAFFS_WINCE
3321 yfsd_UnlockYAFFS(TRUE);
3324 memcpy(&cache->data[start], buffer,
3327 #ifdef CONFIG_YAFFS_WINCE
3328 yfsd_LockYAFFS(TRUE);
3331 cache->nBytes = nToWriteBack;
3335 yaffs_WriteChunkDataToObject
3338 cache->data, cache->nBytes,
3344 chunkWritten = -1; /* fail the write */
3347 /* An incomplete start or end chunk (or maybe both start and end chunk)
3348 * Read into the local buffer then copy, then copy over and write back.
3352 yaffs_GetTempBuffer(dev, __LINE__);
3354 yaffs_ReadChunkDataFromObject(in, chunk,
3357 #ifdef CONFIG_YAFFS_WINCE
3358 yfsd_UnlockYAFFS(TRUE);
3361 memcpy(&localBuffer[start], buffer, nToCopy);
3363 #ifdef CONFIG_YAFFS_WINCE
3364 yfsd_LockYAFFS(TRUE);
3367 yaffs_WriteChunkDataToObject(in, chunk,
3372 yaffs_ReleaseTempBuffer(dev, localBuffer,
3379 #ifdef CONFIG_YAFFS_WINCE
3380 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3381 * This is because we otherwise screw up WinCE's memory mapper
3383 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3384 #ifdef CONFIG_YAFFS_WINCE
3385 yfsd_UnlockYAFFS(TRUE);
3387 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3388 #ifdef CONFIG_YAFFS_WINCE
3389 yfsd_LockYAFFS(TRUE);
3392 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3393 dev->nBytesPerChunk,
3395 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3397 /* A full chunk. Write directly from the supplied buffer. */
3399 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3400 dev->nBytesPerChunk,
3403 /* Since we've overwritten the cached data, we better invalidate it. */
3404 yaffs_InvalidateChunkCache(in, chunk);
3407 if (chunkWritten >= 0) {
3416 /* Update file object */
3418 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3419 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3428 /* ---------------------- File resizing stuff ------------------ */
3430 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
3433 yaffs_Device *dev = in->myDev;
3434 int oldFileSize = in->variant.fileVariant.fileSize;
3436 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
3438 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
3439 dev->nBytesPerChunk;
3443 /* Delete backwards so that we don't end up with holes if
3444 * power is lost part-way through the operation.
3446 for (i = lastDel; i >= startDel; i--) {
3447 /* NB this could be optimised somewhat,
3448 * eg. could retrieve the tags and write them without
3449 * using yaffs_DeleteChunk
3452 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3455 (dev->internalStartBlock * dev->nChunksPerBlock)
3457 ((dev->internalEndBlock +
3458 1) * dev->nChunksPerBlock)) {
3459 T(YAFFS_TRACE_ALWAYS,
3460 (TSTR("Found daft chunkId %d for %d" TENDSTR),
3464 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3471 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
3474 int oldFileSize = in->variant.fileVariant.fileSize;
3475 int sizeOfPartialChunk;
3476 yaffs_Device *dev = in->myDev;
3478 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
3480 yaffs_FlushFilesChunkCache(in);
3481 yaffs_InvalidateWholeChunkCache(in);
3483 yaffs_CheckGarbageCollection(dev);
3485 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3486 return yaffs_GetFileSize(in);
3489 if (newSize == oldFileSize) {
3493 if (newSize < oldFileSize) {
3495 yaffs_PruneResizedChunks(in, newSize);
3497 if (sizeOfPartialChunk != 0) {
3498 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
3499 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3501 /* Got to read and rewrite the last chunk with its new size and zero pad */
3502 yaffs_ReadChunkDataFromObject(in, lastChunk,
3505 memset(localBuffer + sizeOfPartialChunk, 0,
3506 dev->nBytesPerChunk - sizeOfPartialChunk);
3508 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
3509 sizeOfPartialChunk, 1);
3511 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3514 in->variant.fileVariant.fileSize = newSize;
3516 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
3518 /* Write a new object header.
3519 * show we've shrunk the file, if need be
3520 * Do this only if the file is not in the deleted directories.
3522 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3523 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
3524 yaffs_UpdateObjectHeader(in, NULL, 0,
3525 (newSize < oldFileSize) ? 1 : 0, 0);
3531 loff_t yaffs_GetFileSize(yaffs_Object * obj)
3533 obj = yaffs_GetEquivalentObject(obj);
3535 switch (obj->variantType) {
3536 case YAFFS_OBJECT_TYPE_FILE:
3537 return obj->variant.fileVariant.fileSize;
3538 case YAFFS_OBJECT_TYPE_SYMLINK:
3539 return yaffs_strlen(obj->variant.symLinkVariant.alias);
3547 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
3551 yaffs_FlushFilesChunkCache(in);
3553 #ifdef CONFIG_YAFFS_WINCE
3554 yfsd_WinFileTimeNow(in->win_mtime);
3557 in->yst_mtime = Y_CURRENT_TIME;
3563 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
3564 0) ? YAFFS_OK : YAFFS_FAIL;
3573 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
3576 /* First off, invalidate the file's data in the cache, without flushing. */
3577 yaffs_InvalidateWholeChunkCache(in);
3579 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3580 /* Move to the unlinked directory so we have a record that it was deleted. */
3581 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
3585 yaffs_RemoveObjectFromDirectory(in);
3586 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
3589 yaffs_FreeObject(in);
3594 /* yaffs_DeleteFile deletes the whole file data
3595 * and the inode associated with the file.
3596 * It does not delete the links associated with the file.
3598 static int yaffs_UnlinkFile(yaffs_Object * in)
3602 int immediateDeletion = 0;
3607 immediateDeletion = 1;
3611 if (in->inUse <= 0) {
3612 immediateDeletion = 1;
3616 if (immediateDeletion) {
3618 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3620 T(YAFFS_TRACE_TRACING,
3621 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3624 in->myDev->nDeletedFiles++;
3625 if (0 && in->myDev->isYaffs2) {
3626 yaffs_ResizeFile(in, 0);
3628 yaffs_SoftDeleteFile(in);
3631 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3639 int yaffs_DeleteFile(yaffs_Object * in)
3641 int retVal = YAFFS_OK;
3643 if (in->nDataChunks > 0) {
3644 /* Use soft deletion if there is data in the file */
3645 if (!in->unlinked) {
3646 retVal = yaffs_UnlinkFile(in);
3648 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3650 in->myDev->nDeletedFiles++;
3651 yaffs_SoftDeleteFile(in);
3653 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3655 /* The file has no data chunks so we toss it immediately */
3656 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3657 in->variant.fileVariant.top = NULL;
3658 yaffs_DoGenericObjectDeletion(in);
3664 static int yaffs_DeleteDirectory(yaffs_Object * in)
3666 /* First check that the directory is empty. */
3667 if (list_empty(&in->variant.directoryVariant.children)) {
3668 return yaffs_DoGenericObjectDeletion(in);
3675 static int yaffs_DeleteSymLink(yaffs_Object * in)
3677 YFREE(in->variant.symLinkVariant.alias);
3679 return yaffs_DoGenericObjectDeletion(in);
3682 static int yaffs_DeleteHardLink(yaffs_Object * in)
3684 /* remove this hardlink from the list assocaited with the equivalent
3687 list_del(&in->hardLinks);
3688 return yaffs_DoGenericObjectDeletion(in);
3691 static void yaffs_DestroyObject(yaffs_Object * obj)
3693 switch (obj->variantType) {
3694 case YAFFS_OBJECT_TYPE_FILE:
3695 yaffs_DeleteFile(obj);
3697 case YAFFS_OBJECT_TYPE_DIRECTORY:
3698 yaffs_DeleteDirectory(obj);
3700 case YAFFS_OBJECT_TYPE_SYMLINK:
3701 yaffs_DeleteSymLink(obj);
3703 case YAFFS_OBJECT_TYPE_HARDLINK:
3704 yaffs_DeleteHardLink(obj);
3706 case YAFFS_OBJECT_TYPE_SPECIAL:
3707 yaffs_DoGenericObjectDeletion(obj);
3709 case YAFFS_OBJECT_TYPE_UNKNOWN:
3710 break; /* should not happen. */
3714 static int yaffs_UnlinkWorker(yaffs_Object * obj)
3717 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3718 return yaffs_DeleteHardLink(obj);
3719 } else if (!list_empty(&obj->hardLinks)) {
3720 /* Curve ball: We're unlinking an object that has a hardlink.
3722 * This problem arises because we are not strictly following
3723 * The Linux link/inode model.
3725 * We can't really delete the object.
3726 * Instead, we do the following:
3727 * - Select a hardlink.
3728 * - Unhook it from the hard links
3729 * - Unhook it from its parent directory (so that the rename can work)
3730 * - Rename the object to the hardlink's name.
3731 * - Delete the hardlink
3736 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3738 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
3740 list_del_init(&hl->hardLinks);
3741 list_del_init(&hl->siblings);
3743 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3745 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
3747 if (retVal == YAFFS_OK) {
3748 retVal = yaffs_DoGenericObjectDeletion(hl);
3753 switch (obj->variantType) {
3754 case YAFFS_OBJECT_TYPE_FILE:
3755 return yaffs_UnlinkFile(obj);
3757 case YAFFS_OBJECT_TYPE_DIRECTORY:
3758 return yaffs_DeleteDirectory(obj);
3760 case YAFFS_OBJECT_TYPE_SYMLINK:
3761 return yaffs_DeleteSymLink(obj);
3763 case YAFFS_OBJECT_TYPE_SPECIAL:
3764 return yaffs_DoGenericObjectDeletion(obj);
3766 case YAFFS_OBJECT_TYPE_HARDLINK:
3767 case YAFFS_OBJECT_TYPE_UNKNOWN:
3774 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
3778 obj = yaffs_FindObjectByName(dir, name);
3780 if (obj && obj->unlinkAllowed) {
3781 return yaffs_UnlinkWorker(obj);
3788 /*----------------------- Initialisation Scanning ---------------------- */
3790 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
3791 int backwardScanning)
3795 if (!backwardScanning) {
3796 /* Handle YAFFS1 forward scanning case
3797 * For YAFFS1 we always do the deletion
3801 /* Handle YAFFS2 case (backward scanning)
3802 * If the shadowed object exists then ignore.
3804 if (yaffs_FindObjectByNumber(dev, objId)) {
3809 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
3810 * We put it in unlinked dir to be cleaned up after the scanning
3813 yaffs_FindOrCreateObjectByNumber(dev, objId,
3814 YAFFS_OBJECT_TYPE_FILE);
3815 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
3816 obj->variant.fileVariant.shrinkSize = 0;
3817 obj->valid = 1; /* So that we don't read any other info for this file */
3826 static int yaffs_Scan(yaffs_Device * dev)
3828 yaffs_ExtendedTags tags;
3833 int nBlocksToScan = 0;
3838 yaffs_BlockState state;
3839 yaffs_Object *hardList = NULL;
3841 yaffs_BlockInfo *bi;
3843 yaffs_ObjectHeader *oh;
3845 yaffs_Object *parent;
3846 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3850 yaffs_BlockIndex *blockIndex = NULL;
3853 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
3854 dev->internalStartBlock, dev->internalEndBlock));
3856 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
3858 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
3860 if (dev->isYaffs2) {
3861 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
3864 /* Scan all the blocks to determine their state */
3865 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
3866 bi = yaffs_GetBlockInfo(dev, blk);
3867 yaffs_ClearChunkBits(dev, blk);
3869 bi->softDeletions = 0;
3871 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
3873 bi->blockState = state;
3874 bi->sequenceNumber = sequenceNumber;
3876 T(YAFFS_TRACE_SCAN_DEBUG,
3877 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
3878 state, sequenceNumber));
3880 if (state == YAFFS_BLOCK_STATE_DEAD) {
3881 T(YAFFS_TRACE_BAD_BLOCKS,
3882 (TSTR("block %d is bad" TENDSTR), blk));
3883 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
3884 T(YAFFS_TRACE_SCAN_DEBUG,
3885 (TSTR("Block empty " TENDSTR)));
3886 dev->nErasedBlocks++;
3887 dev->nFreeChunks += dev->nChunksPerBlock;
3888 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3890 /* Determine the highest sequence number */
3891 if (dev->isYaffs2 &&
3892 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
3893 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
3895 blockIndex[nBlocksToScan].seq = sequenceNumber;
3896 blockIndex[nBlocksToScan].block = blk;
3900 if (sequenceNumber >= dev->sequenceNumber) {
3901 dev->sequenceNumber = sequenceNumber;
3903 } else if (dev->isYaffs2) {
3904 /* TODO: Nasty sequence number! */
3907 ("Block scanning block %d has bad sequence number %d"
3908 TENDSTR), blk, sequenceNumber));
3915 * Dungy old bubble sort for now...
3917 if (dev->isYaffs2) {
3918 yaffs_BlockIndex temp;
3922 for (i = 0; i < nBlocksToScan; i++)
3923 for (j = i + 1; j < nBlocksToScan; j++)
3924 if (blockIndex[i].seq > blockIndex[j].seq) {
3925 temp = blockIndex[j];
3926 blockIndex[j] = blockIndex[i];
3927 blockIndex[i] = temp;
3931 /* Now scan the blocks looking at the data. */
3932 if (dev->isYaffs2) {
3934 endIterator = nBlocksToScan - 1;
3935 T(YAFFS_TRACE_SCAN_DEBUG,
3936 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
3938 startIterator = dev->internalStartBlock;
3939 endIterator = dev->internalEndBlock;
3942 /* For each block.... */
3943 for (blockIterator = startIterator; blockIterator <= endIterator;
3946 if (dev->isYaffs2) {
3947 /* get the block to scan in the correct order */
3948 blk = blockIndex[blockIterator].block;
3950 blk = blockIterator;
3953 bi = yaffs_GetBlockInfo(dev, blk);
3954 state = bi->blockState;
3958 /* For each chunk in each block that needs scanning....*/
3959 for (c = 0; c < dev->nChunksPerBlock &&
3960 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
3961 /* Read the tags and decide what to do */
3962 chunk = blk * dev->nChunksPerBlock + c;
3964 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
3967 /* Let's have a good look at this chunk... */
3969 if (!dev->isYaffs2 && tags.chunkDeleted) {
3975 /*T((" %d %d deleted\n",blk,c)); */
3976 } else if (!tags.chunkUsed) {
3977 /* An unassigned chunk in the block
3978 * This means that either the block is empty or
3979 * this is the one being allocated from
3983 /* We're looking at the first chunk in the block so the block is unused */
3984 state = YAFFS_BLOCK_STATE_EMPTY;
3985 dev->nErasedBlocks++;
3987 /* this is the block being allocated from */
3990 (" Allocating from %d %d" TENDSTR),
3992 state = YAFFS_BLOCK_STATE_ALLOCATING;
3993 dev->allocationBlock = blk;
3994 dev->allocationPage = c;
3995 dev->allocationBlockFinder = blk;
3996 /* Set it to here to encourage the allocator to go forth from here. */
3998 /* Yaffs2 sanity check:
3999 * This should be the one with the highest sequence number
4002 && (dev->sequenceNumber !=
4003 bi->sequenceNumber)) {
4004 T(YAFFS_TRACE_ALWAYS,
4006 ("yaffs: Allocation block %d was not highest sequence id:"
4007 " block seq = %d, dev seq = %d"
4008 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4012 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4013 } else if (tags.chunkId > 0) {
4014 /* chunkId > 0 so it is a data chunk... */
4015 unsigned int endpos;
4017 yaffs_SetChunkBit(dev, blk, c);
4020 in = yaffs_FindOrCreateObjectByNumber(dev,
4023 YAFFS_OBJECT_TYPE_FILE);
4024 /* PutChunkIntoFile checks for a clash (two data chunks with
4025 * the same chunkId).
4027 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4030 (tags.chunkId - 1) * dev->nBytesPerChunk +
4032 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4033 && in->variant.fileVariant.scannedFileSize <
4035 in->variant.fileVariant.
4036 scannedFileSize = endpos;
4037 if (!dev->useHeaderFileSize) {
4038 in->variant.fileVariant.
4040 in->variant.fileVariant.
4045 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4047 /* chunkId == 0, so it is an ObjectHeader.
4048 * Thus, we read in the object header and make the object
4050 yaffs_SetChunkBit(dev, blk, c);
4053 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4057 oh = (yaffs_ObjectHeader *) chunkData;
4059 in = yaffs_FindObjectByNumber(dev,
4061 if (in && in->variantType != oh->type) {
4062 /* This should not happen, but somehow
4063 * Wev'e ended up with an objectId that has been reused but not yet
4064 * deleted, and worse still it has changed type. Delete the old object.
4067 yaffs_DestroyObject(in);
4072 in = yaffs_FindOrCreateObjectByNumber(dev,
4077 if (oh->shadowsObject > 0) {
4078 yaffs_HandleShadowedObject(dev,
4085 /* We have already filled this one. We have a duplicate and need to resolve it. */
4087 unsigned existingSerial = in->serial;
4088 unsigned newSerial = tags.serialNumber;
4090 if (dev->isYaffs2 ||
4091 ((existingSerial + 1) & 3) ==
4093 /* Use new one - destroy the exisiting one */
4094 yaffs_DeleteChunk(dev,
4099 /* Use existing - destroy this one. */
4100 yaffs_DeleteChunk(dev, chunk, 1,
4106 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4107 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4108 /* We only load some info, don't fiddle with directory structure */
4110 in->variantType = oh->type;
4112 in->yst_mode = oh->yst_mode;
4113 #ifdef CONFIG_YAFFS_WINCE
4114 in->win_atime[0] = oh->win_atime[0];
4115 in->win_ctime[0] = oh->win_ctime[0];
4116 in->win_mtime[0] = oh->win_mtime[0];
4117 in->win_atime[1] = oh->win_atime[1];
4118 in->win_ctime[1] = oh->win_ctime[1];
4119 in->win_mtime[1] = oh->win_mtime[1];
4121 in->yst_uid = oh->yst_uid;
4122 in->yst_gid = oh->yst_gid;
4123 in->yst_atime = oh->yst_atime;
4124 in->yst_mtime = oh->yst_mtime;
4125 in->yst_ctime = oh->yst_ctime;
4126 in->yst_rdev = oh->yst_rdev;
4128 in->chunkId = chunk;
4130 } else if (!in->valid) {
4131 /* we need to load this info */
4134 in->variantType = oh->type;
4136 in->yst_mode = oh->yst_mode;
4137 #ifdef CONFIG_YAFFS_WINCE
4138 in->win_atime[0] = oh->win_atime[0];
4139 in->win_ctime[0] = oh->win_ctime[0];
4140 in->win_mtime[0] = oh->win_mtime[0];
4141 in->win_atime[1] = oh->win_atime[1];
4142 in->win_ctime[1] = oh->win_ctime[1];
4143 in->win_mtime[1] = oh->win_mtime[1];
4145 in->yst_uid = oh->yst_uid;
4146 in->yst_gid = oh->yst_gid;
4147 in->yst_atime = oh->yst_atime;
4148 in->yst_mtime = oh->yst_mtime;
4149 in->yst_ctime = oh->yst_ctime;
4150 in->yst_rdev = oh->yst_rdev;
4152 in->chunkId = chunk;
4154 yaffs_SetObjectName(in, oh->name);
4157 /* directory stuff...
4162 yaffs_FindOrCreateObjectByNumber
4163 (dev, oh->parentObjectId,
4164 YAFFS_OBJECT_TYPE_DIRECTORY);
4165 if (parent->variantType ==
4166 YAFFS_OBJECT_TYPE_UNKNOWN) {
4167 /* Set up as a directory */
4168 parent->variantType =
4169 YAFFS_OBJECT_TYPE_DIRECTORY;
4170 INIT_LIST_HEAD(&parent->variant.
4173 } else if (parent->variantType !=
4174 YAFFS_OBJECT_TYPE_DIRECTORY)
4176 /* Hoosterman, another problem....
4177 * We're trying to use a non-directory as a directory
4180 T(YAFFS_TRACE_ERROR,
4182 ("yaffs tragedy: attempting to use non-directory as"
4183 " a directory in scan. Put in lost+found."
4185 parent = dev->lostNFoundDir;
4188 yaffs_AddObjectToDirectory(parent, in);
4190 if (0 && (parent == dev->deletedDir ||
4191 parent == dev->unlinkedDir)) {
4192 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
4193 dev->nDeletedFiles++;
4195 /* Note re hardlinks.
4196 * Since we might scan a hardlink before its equivalent object is scanned
4197 * we put them all in a list.
4198 * After scanning is complete, we should have all the objects, so we run through this
4199 * list and fix up all the chains.
4202 switch (in->variantType) {
4203 case YAFFS_OBJECT_TYPE_UNKNOWN:
4204 /* Todo got a problem */
4206 case YAFFS_OBJECT_TYPE_FILE:
4209 /* Prune back the shrunken chunks */
4210 yaffs_PruneResizedChunks
4212 /* Mark the block as having a shrinkHeader */
4213 bi->hasShrinkHeader = 1;
4216 if (dev->useHeaderFileSize)
4218 in->variant.fileVariant.
4223 case YAFFS_OBJECT_TYPE_HARDLINK:
4224 in->variant.hardLinkVariant.
4225 equivalentObjectId =
4226 oh->equivalentObjectId;
4227 in->hardLinks.next =
4228 (struct list_head *)
4232 case YAFFS_OBJECT_TYPE_DIRECTORY:
4235 case YAFFS_OBJECT_TYPE_SPECIAL:
4238 case YAFFS_OBJECT_TYPE_SYMLINK:
4239 in->variant.symLinkVariant.
4241 yaffs_CloneString(oh->alias);
4245 if (parent == dev->deletedDir) {
4246 yaffs_DestroyObject(in);
4247 bi->hasShrinkHeader = 1;
4253 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4254 /* If we got this far while scanning, then the block is fully allocated.*/
4255 state = YAFFS_BLOCK_STATE_FULL;
4258 bi->blockState = state;
4260 /* Now let's see if it was dirty */
4261 if (bi->pagesInUse == 0 &&
4262 !bi->hasShrinkHeader &&
4263 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4264 yaffs_BlockBecameDirty(dev, blk);
4273 /* Ok, we've done all the scanning.
4274 * Fix up the hard link chains.
4275 * We should now have scanned all the objects, now it's time to add these
4280 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4282 in = yaffs_FindObjectByNumber(dev,
4283 hl->variant.hardLinkVariant.
4284 equivalentObjectId);
4287 /* Add the hardlink pointers */
4288 hl->variant.hardLinkVariant.equivalentObject = in;
4289 list_add(&hl->hardLinks, &in->hardLinks);
4291 /* Todo Need to report/handle this better.
4292 * Got a problem... hardlink to a non-existant object
4294 hl->variant.hardLinkVariant.equivalentObject = NULL;
4295 INIT_LIST_HEAD(&hl->hardLinks);
4301 /* Handle the unlinked files. Since they were left in an unlinked state we should
4305 struct list_head *i;
4306 struct list_head *n;
4309 /* Soft delete all the unlinked files */
4310 list_for_each_safe(i, n,
4311 &dev->unlinkedDir->variant.directoryVariant.
4314 l = list_entry(i, yaffs_Object, siblings);
4315 yaffs_DestroyObject(l);
4320 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4322 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4327 static int yaffs_ScanBackwards(yaffs_Device * dev)
4329 yaffs_ExtendedTags tags;
4334 int nBlocksToScan = 0;
4339 yaffs_BlockState state;
4340 yaffs_Object *hardList = NULL;
4342 yaffs_BlockInfo *bi;
4344 yaffs_ObjectHeader *oh;
4346 yaffs_Object *parent;
4347 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4351 yaffs_BlockIndex *blockIndex = NULL;
4353 if (!dev->isYaffs2) {
4355 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
4361 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
4362 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
4364 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4366 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4368 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4370 /* Scan all the blocks to determine their state */
4371 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4372 bi = yaffs_GetBlockInfo(dev, blk);
4373 yaffs_ClearChunkBits(dev, blk);
4375 bi->softDeletions = 0;
4377 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4379 bi->blockState = state;
4380 bi->sequenceNumber = sequenceNumber;
4382 T(YAFFS_TRACE_SCAN_DEBUG,
4383 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4384 state, sequenceNumber));
4386 if (state == YAFFS_BLOCK_STATE_DEAD) {
4387 T(YAFFS_TRACE_BAD_BLOCKS,
4388 (TSTR("block %d is bad" TENDSTR), blk));
4389 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4390 T(YAFFS_TRACE_SCAN_DEBUG,
4391 (TSTR("Block empty " TENDSTR)));
4392 dev->nErasedBlocks++;
4393 dev->nFreeChunks += dev->nChunksPerBlock;
4394 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4396 /* Determine the highest sequence number */
4397 if (dev->isYaffs2 &&
4398 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4399 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4401 blockIndex[nBlocksToScan].seq = sequenceNumber;
4402 blockIndex[nBlocksToScan].block = blk;
4406 if (sequenceNumber >= dev->sequenceNumber) {
4407 dev->sequenceNumber = sequenceNumber;
4409 } else if (dev->isYaffs2) {
4410 /* TODO: Nasty sequence number! */
4413 ("Block scanning block %d has bad sequence number %d"
4414 TENDSTR), blk, sequenceNumber));
4422 * Dungy old bubble sort for now...
4425 yaffs_BlockIndex temp;
4429 for (i = 0; i < nBlocksToScan; i++)
4430 for (j = i + 1; j < nBlocksToScan; j++)
4431 if (blockIndex[i].seq > blockIndex[j].seq) {
4432 temp = blockIndex[j];
4433 blockIndex[j] = blockIndex[i];
4434 blockIndex[i] = temp;
4438 /* Now scan the blocks looking at the data. */
4440 endIterator = nBlocksToScan - 1;
4441 T(YAFFS_TRACE_SCAN_DEBUG,
4442 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4444 /* For each block.... backwards */
4445 for (blockIterator = endIterator; blockIterator >= startIterator;
4448 /* get the block to scan in the correct order */
4449 blk = blockIndex[blockIterator].block;
4451 bi = yaffs_GetBlockInfo(dev, blk);
4452 state = bi->blockState;
4456 /* For each chunk in each block that needs scanning.... */
4457 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
4458 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
4459 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
4460 /* Scan backwards...
4461 * Read the tags and decide what to do
4463 chunk = blk * dev->nChunksPerBlock + c;
4465 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4468 /* Let's have a good look at this chunk... */
4470 if (!tags.chunkUsed) {
4471 // An unassigned chunk in the block
4472 // This means that either the block is empty or
4473 // this is the one being allocated from
4476 /* We're looking at the first chunk in the block so the block is unused */
4477 state = YAFFS_BLOCK_STATE_EMPTY;
4478 dev->nErasedBlocks++;
4480 /* this is the block being allocated from */
4482 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4485 (" Allocating from %d %d"
4488 state = YAFFS_BLOCK_STATE_ALLOCATING;
4489 dev->allocationBlock = blk;
4490 dev->allocationPage = c;
4491 dev->allocationBlockFinder = blk;
4492 /* Set it to here to encourage the allocator to
4493 * go forth from here.
4496 /* Yaffs2 sanity check:
4497 * This should be the one with the highest sequence number
4500 && (dev->sequenceNumber !=
4501 bi->sequenceNumber)) {
4502 T(YAFFS_TRACE_ALWAYS,
4504 ("yaffs: Allocation block %d was not highest sequence "
4505 "id: block seq = %d, dev seq = %d"
4508 dev->sequenceNumber));
4513 } else if (tags.chunkId > 0) {
4514 /* chunkId > 0 so it is a data chunk... */
4515 unsigned int endpos;
4518 (tags.chunkId - 1) * dev->nBytesPerChunk;
4520 yaffs_SetChunkBit(dev, blk, c);
4523 in = yaffs_FindOrCreateObjectByNumber(dev,
4526 YAFFS_OBJECT_TYPE_FILE);
4527 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4529 in->variant.fileVariant.shrinkSize) {
4530 /* This has not been invalidated by a resize */
4531 yaffs_PutChunkIntoFile(in, tags.chunkId,
4534 /* File size is calculated by looking at the data chunks if we have not
4535 * seen an object header yet. Stop this practice once we find an object header.
4539 1) * dev->nBytesPerChunk +
4542 if (!in->valid && /* have not got an object header yet */
4543 in->variant.fileVariant.
4544 scannedFileSize < endpos) {
4545 in->variant.fileVariant.
4546 scannedFileSize = endpos;
4547 in->variant.fileVariant.
4549 in->variant.fileVariant.
4554 /* This chunk has been invalidated by a resize, so delete */
4555 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4559 /* chunkId == 0, so it is an ObjectHeader.
4560 * Thus, we read in the object header and make the object
4562 yaffs_SetChunkBit(dev, blk, c);
4568 if (tags.extraHeaderInfoAvailable) {
4569 in = yaffs_FindOrCreateObjectByNumber
4570 (dev, tags.objectId,
4571 tags.extraObjectType);
4574 if (!in || !in->valid) {
4576 /* If we don't have valid info then we need to read the chunk
4577 * TODO In future we can probably defer reading the chunk and
4578 * living with invalid data until needed.
4581 yaffs_ReadChunkWithTagsFromNAND(dev,
4586 oh = (yaffs_ObjectHeader *) chunkData;
4589 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
4594 /* TODO Hoosterman we have a problem! */
4595 T(YAFFS_TRACE_ERROR,
4597 ("yaffs tragedy: Could not make object for object %d "
4598 "at chunk %d during scan"
4599 TENDSTR), tags.objectId, chunk));
4604 /* We have already filled this one.
4605 * We have a duplicate that will be discarded, but
4606 * we first have to suck out resize info if it is a file.
4609 if ((in->variantType ==
4610 YAFFS_OBJECT_TYPE_FILE) && ((oh
4615 YAFFS_OBJECT_TYPE_FILE)
4618 extraHeaderInfoAvailable
4623 YAFFS_OBJECT_TYPE_FILE))
4626 (oh) ? oh->fileSize : tags.
4628 __u32 parentObjectId =
4630 parentObjectId : tags.
4631 extraParentObjectId;
4633 (oh) ? oh->isShrink : tags.
4634 extraIsShrinkHeader;
4636 /* If it is deleted (unlinked at start also means deleted)
4637 * we treat the file size as being zeroed at this point.
4639 if (parentObjectId ==
4640 YAFFS_OBJECTID_DELETED
4641 || parentObjectId ==
4642 YAFFS_OBJECTID_UNLINKED) {
4648 in->variant.fileVariant.
4649 shrinkSize > thisSize) {
4650 in->variant.fileVariant.
4656 bi->hasShrinkHeader = 1;
4660 /* Use existing - destroy this one. */
4661 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4666 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4668 YAFFS_OBJECTID_LOSTNFOUND)) {
4669 /* We only load some info, don't fiddle with directory structure */
4671 in->variantType = oh->type;
4673 in->yst_mode = oh->yst_mode;
4674 #ifdef CONFIG_YAFFS_WINCE
4675 in->win_atime[0] = oh->win_atime[0];
4676 in->win_ctime[0] = oh->win_ctime[0];
4677 in->win_mtime[0] = oh->win_mtime[0];
4678 in->win_atime[1] = oh->win_atime[1];
4679 in->win_ctime[1] = oh->win_ctime[1];
4680 in->win_mtime[1] = oh->win_mtime[1];
4682 in->yst_uid = oh->yst_uid;
4683 in->yst_gid = oh->yst_gid;
4684 in->yst_atime = oh->yst_atime;
4685 in->yst_mtime = oh->yst_mtime;
4686 in->yst_ctime = oh->yst_ctime;
4687 in->yst_rdev = oh->yst_rdev;
4689 in->chunkId = chunk;
4691 } else if (!in->valid) {
4692 /* we need to load this info */
4695 in->variantType = oh->type;
4697 in->yst_mode = oh->yst_mode;
4698 #ifdef CONFIG_YAFFS_WINCE
4699 in->win_atime[0] = oh->win_atime[0];
4700 in->win_ctime[0] = oh->win_ctime[0];
4701 in->win_mtime[0] = oh->win_mtime[0];
4702 in->win_atime[1] = oh->win_atime[1];
4703 in->win_ctime[1] = oh->win_ctime[1];
4704 in->win_mtime[1] = oh->win_mtime[1];
4706 in->yst_uid = oh->yst_uid;
4707 in->yst_gid = oh->yst_gid;
4708 in->yst_atime = oh->yst_atime;
4709 in->yst_mtime = oh->yst_mtime;
4710 in->yst_ctime = oh->yst_ctime;
4711 in->yst_rdev = oh->yst_rdev;
4713 in->chunkId = chunk;
4715 if (oh->shadowsObject > 0) {
4716 yaffs_HandleShadowedObject(dev,
4722 yaffs_SetObjectName(in, oh->name);
4725 /* directory stuff...
4730 yaffs_FindOrCreateObjectByNumber
4731 (dev, oh->parentObjectId,
4732 YAFFS_OBJECT_TYPE_DIRECTORY);
4733 if (parent->variantType ==
4734 YAFFS_OBJECT_TYPE_UNKNOWN) {
4735 /* Set up as a directory */
4736 parent->variantType =
4737 YAFFS_OBJECT_TYPE_DIRECTORY;
4738 INIT_LIST_HEAD(&parent->variant.
4741 } else if (parent->variantType !=
4742 YAFFS_OBJECT_TYPE_DIRECTORY)
4744 /* Hoosterman, another problem....
4745 * We're trying to use a non-directory as a directory
4748 T(YAFFS_TRACE_ERROR,
4750 ("yaffs tragedy: attempting to use non-directory as"
4751 " a directory in scan. Put in lost+found."
4753 parent = dev->lostNFoundDir;
4756 yaffs_AddObjectToDirectory(parent, in);
4758 if ((parent == dev->deletedDir ||
4759 parent == dev->unlinkedDir)) {
4760 /* If it is unlinked at start up then it wants deleting */
4765 /* Mark the block as having a shrinkHeader */
4766 bi->hasShrinkHeader = 1;
4769 /* Note re hardlinks.
4770 * Since we might scan a hardlink before its equivalent object is scanned
4771 * we put them all in a list.
4772 * After scanning is complete, we should have all the objects, so we run
4773 * through this list and fix up all the chains.
4776 switch (in->variantType) {
4777 case YAFFS_OBJECT_TYPE_UNKNOWN:
4778 /* Todo got a problem */
4780 case YAFFS_OBJECT_TYPE_FILE:
4782 if (in->variant.fileVariant.
4785 /* This covers the case where the file size is greater
4786 * than where the data is
4787 * This will happen if the file is resized to be larger
4788 * than its current data extents.
4790 in->variant.fileVariant.fileSize =
4792 in->variant.fileVariant.scannedFileSize =
4793 in->variant.fileVariant.fileSize;
4797 in->variant.fileVariant.shrinkSize >
4799 in->variant.fileVariant.shrinkSize =
4804 case YAFFS_OBJECT_TYPE_HARDLINK:
4805 in->variant.hardLinkVariant.equivalentObjectId =
4806 oh->equivalentObjectId;
4807 in->hardLinks.next =
4808 (struct list_head *) hardList;
4811 case YAFFS_OBJECT_TYPE_DIRECTORY:
4814 case YAFFS_OBJECT_TYPE_SPECIAL:
4817 case YAFFS_OBJECT_TYPE_SYMLINK:
4818 in->variant.symLinkVariant.
4820 yaffs_CloneString(oh->
4829 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4830 /* If we got this far while scanning, then the block is fully allocated. */
4831 state = YAFFS_BLOCK_STATE_FULL;
4834 bi->blockState = state;
4836 /* Now let's see if it was dirty */
4837 if (bi->pagesInUse == 0 &&
4838 !bi->hasShrinkHeader &&
4839 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4840 yaffs_BlockBecameDirty(dev, blk);
4848 /* Ok, we've done all the scanning.
4849 * Fix up the hard link chains.
4850 * We should now have scanned all the objects, now it's time to add these
4855 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4857 in = yaffs_FindObjectByNumber(dev,
4858 hl->variant.hardLinkVariant.
4859 equivalentObjectId);
4862 /* Add the hardlink pointers */
4863 hl->variant.hardLinkVariant.equivalentObject = in;
4864 list_add(&hl->hardLinks, &in->hardLinks);
4866 /* Todo Need to report/handle this better.
4867 * Got a problem... hardlink to a non-existant object
4869 hl->variant.hardLinkVariant.equivalentObject = NULL;
4870 INIT_LIST_HEAD(&hl->hardLinks);
4877 struct list_head *i;
4878 struct list_head *n;
4882 /* Soft delete all the unlinked files */
4883 list_for_each_safe(i, n,
4884 &dev->unlinkedDir->variant.directoryVariant.
4887 l = list_entry(i, yaffs_Object, siblings);
4888 yaffs_DestroyObject(l);
4892 /* Soft delete all the deletedDir files */
4893 list_for_each_safe(i, n,
4894 &dev->deletedDir->variant.directoryVariant.
4897 l = list_entry(i, yaffs_Object, siblings);
4898 yaffs_DestroyObject(l);
4904 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4906 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
4911 /*------------------------------ Directory Functions ----------------------------- */
4913 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
4918 T(YAFFS_TRACE_ALWAYS,
4920 ("tragedy: Trying to add an object to a null pointer directory"
4924 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4925 T(YAFFS_TRACE_ALWAYS,
4927 ("tragedy: Trying to add an object to a non-directory"
4932 if (obj->siblings.prev == NULL) {
4933 /* Not initialised */
4934 INIT_LIST_HEAD(&obj->siblings);
4936 } else if (!list_empty(&obj->siblings)) {
4937 /* If it is holed up somewhere else, un hook it */
4938 list_del_init(&obj->siblings);
4941 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
4942 obj->parent = directory;
4944 if (directory == obj->myDev->unlinkedDir
4945 || directory == obj->myDev->deletedDir) {
4947 obj->myDev->nUnlinkedFiles++;
4948 obj->renameAllowed = 0;
4952 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
4954 list_del_init(&obj->siblings);
4958 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
4963 struct list_head *i;
4964 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4973 T(YAFFS_TRACE_ALWAYS,
4975 ("tragedy: yaffs_FindObjectByName: null pointer directory"
4979 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4980 T(YAFFS_TRACE_ALWAYS,
4982 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4986 sum = yaffs_CalcNameSum(name);
4988 list_for_each(i, &directory->variant.directoryVariant.children) {
4990 l = list_entry(i, yaffs_Object, siblings);
4992 /* Special case for lost-n-found */
4993 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4994 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
4997 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
4999 /* LostnFound cunk called Objxxx
5002 yaffs_GetObjectName(l, buffer,
5003 YAFFS_MAX_NAME_LENGTH);
5004 if (yaffs_strcmp(name, buffer) == 0) {
5017 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5018 int (*fn) (yaffs_Object *))
5020 struct list_head *i;
5024 T(YAFFS_TRACE_ALWAYS,
5026 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5030 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5031 T(YAFFS_TRACE_ALWAYS,
5033 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5037 list_for_each(i, &theDir->variant.directoryVariant.children) {
5039 l = list_entry(i, yaffs_Object, siblings);
5051 /* GetEquivalentObject dereferences any hard links to get to the
5055 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5057 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5058 /* We want the object id of the equivalent object, not this one */
5059 obj = obj->variant.hardLinkVariant.equivalentObject;
5065 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5067 memset(name, 0, buffSize * sizeof(YCHAR));
5069 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5070 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5071 } else if (obj->chunkId <= 0) {
5073 /* make up a name */
5074 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5076 yaffs_strncpy(name, locName, buffSize - 1);
5079 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5080 else if (obj->shortName[0]) {
5081 yaffs_strcpy(name, obj->shortName);
5085 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5087 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5089 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5091 if (obj->chunkId >= 0) {
5092 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5093 obj->chunkId, buffer,
5096 yaffs_strncpy(name, oh->name, buffSize - 1);
5098 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5101 return yaffs_strlen(name);
5104 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5107 /* Dereference any hard linking */
5108 obj = yaffs_GetEquivalentObject(obj);
5110 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5111 return obj->variant.fileVariant.fileSize;
5113 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5114 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5116 /* Only a directory should drop through to here */
5117 return obj->myDev->nBytesPerChunk;
5121 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5124 struct list_head *i;
5126 if (!obj->unlinked) {
5127 count++; /* the object itself */
5129 list_for_each(i, &obj->hardLinks) {
5130 count++; /* add the hard links; */
5136 int yaffs_GetObjectInode(yaffs_Object * obj)
5138 obj = yaffs_GetEquivalentObject(obj);
5140 return obj->objectId;
5143 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5145 obj = yaffs_GetEquivalentObject(obj);
5147 switch (obj->variantType) {
5148 case YAFFS_OBJECT_TYPE_FILE:
5151 case YAFFS_OBJECT_TYPE_DIRECTORY:
5154 case YAFFS_OBJECT_TYPE_SYMLINK:
5157 case YAFFS_OBJECT_TYPE_HARDLINK:
5160 case YAFFS_OBJECT_TYPE_SPECIAL:
5161 if (S_ISFIFO(obj->yst_mode))
5163 if (S_ISCHR(obj->yst_mode))
5165 if (S_ISBLK(obj->yst_mode))
5167 if (S_ISSOCK(obj->yst_mode))
5175 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5177 obj = yaffs_GetEquivalentObject(obj);
5178 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5179 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5181 return yaffs_CloneString(_Y(""));
5185 #ifndef CONFIG_YAFFS_WINCE
5187 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5189 unsigned int valid = attr->ia_valid;
5191 if (valid & ATTR_MODE)
5192 obj->yst_mode = attr->ia_mode;
5193 if (valid & ATTR_UID)
5194 obj->yst_uid = attr->ia_uid;
5195 if (valid & ATTR_GID)
5196 obj->yst_gid = attr->ia_gid;
5198 if (valid & ATTR_ATIME)
5199 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5200 if (valid & ATTR_CTIME)
5201 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5202 if (valid & ATTR_MTIME)
5203 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5205 if (valid & ATTR_SIZE)
5206 yaffs_ResizeFile(obj, attr->ia_size);
5208 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5213 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5215 unsigned int valid = 0;
5217 attr->ia_mode = obj->yst_mode;
5219 attr->ia_uid = obj->yst_uid;
5221 attr->ia_gid = obj->yst_gid;
5224 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5225 valid |= ATTR_ATIME;
5226 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5227 valid |= ATTR_CTIME;
5228 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5229 valid |= ATTR_MTIME;
5231 attr->ia_size = yaffs_GetFileSize(obj);
5234 attr->ia_valid = valid;
5243 int yaffs_DumpObject(yaffs_Object * obj)
5247 yaffs_GetObjectName(obj, name, 256);
5249 T(YAFFS_TRACE_ALWAYS,
5251 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5252 " chunk %d type %d size %d\n"
5253 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5254 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5255 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5261 /*---------------------------- Initialisation code -------------------------------------- */
5263 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5266 /* Common functions, gotta have */
5267 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5270 #ifdef CONFIG_YAFFS_YAFFS2
5272 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5273 if (dev->writeChunkWithTagsToNAND &&
5274 dev->readChunkWithTagsFromNAND &&
5275 !dev->writeChunkToNAND &&
5276 !dev->readChunkFromNAND &&
5277 dev->markNANDBlockBad && dev->queryNANDBlock)
5281 /* Can use the "spare" style interface for yaffs1 */
5282 if (!dev->isYaffs2 &&
5283 !dev->writeChunkWithTagsToNAND &&
5284 !dev->readChunkWithTagsFromNAND &&
5285 dev->writeChunkToNAND &&
5286 dev->readChunkFromNAND &&
5287 !dev->markNANDBlockBad && !dev->queryNANDBlock)
5293 int yaffs_GutsInitialise(yaffs_Device * dev)
5300 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5302 /* Check stuff that must be set */
5305 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5309 dev->internalStartBlock = dev->startBlock;
5310 dev->internalEndBlock = dev->endBlock;
5311 dev->blockOffset = 0;
5312 dev->chunkOffset = 0;
5313 dev->nFreeChunks = 0;
5315 if (dev->startBlock == 0) {
5316 dev->internalStartBlock = dev->startBlock + 1;
5317 dev->internalEndBlock = dev->endBlock + 1;
5318 dev->blockOffset = 1;
5319 dev->chunkOffset = dev->nChunksPerBlock;
5322 /* Check geometry parameters. */
5324 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
5326 T(YAFFS_TRACE_ALWAYS,
5328 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
5329 TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
5333 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5334 T(YAFFS_TRACE_ALWAYS,
5335 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5339 /* Got the right mix of functions? */
5340 if (!yaffs_CheckDevFunctions(dev)) {
5341 /* Function missing */
5342 T(YAFFS_TRACE_ALWAYS,
5344 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5349 /* This is really a compilation check. */
5350 if (!yaffs_CheckStructures()) {
5351 T(YAFFS_TRACE_ALWAYS,
5352 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5356 if (dev->isMounted) {
5357 T(YAFFS_TRACE_ALWAYS,
5358 (TSTR("yaffs: device already mounted\n" TENDSTR)));
5362 /* Finished with most checks. One or two more checks happen later on too. */
5366 nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5368 /* OK now calculate a few things for the device
5369 * Calculate chunkGroupBits.
5370 * We need to find the next power of 2 > than internalEndBlock
5373 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
5375 for (bits = extraBits = 0; x > 1; bits++) {
5384 /* Level0 Tnodes are 16 bits, so if the bitwidth of the
5385 * chunk range we're using is greater than 16 we need
5386 * to figure out chunk shift and chunkGroupSize
5389 dev->chunkGroupBits = 0;
5391 dev->chunkGroupBits = bits - 16;
5394 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5396 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
5397 /* We have a problem because the soft delete won't work if
5398 * the chunk group size > chunks per block.
5399 * This can be remedied by using larger "virtual blocks".
5401 T(YAFFS_TRACE_ALWAYS,
5402 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5407 /* OK, we've finished verifying the device, lets continue with initialisation */
5409 /* More device initialisation */
5410 dev->garbageCollections = 0;
5411 dev->passiveGarbageCollections = 0;
5412 dev->currentDirtyChecker = 0;
5413 dev->bufferedBlock = -1;
5414 dev->doingBufferedBlockRewrite = 0;
5415 dev->nDeletedFiles = 0;
5416 dev->nBackgroundDeletions = 0;
5417 dev->nUnlinkedFiles = 0;
5419 dev->eccUnfixed = 0;
5420 dev->tagsEccFixed = 0;
5421 dev->tagsEccUnfixed = 0;
5422 dev->nErasureFailures = 0;
5423 dev->nErasedBlocks = 0;
5426 /* Initialise temporary buffers */
5429 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5430 dev->tempBuffer[i].line = 0; /* not in use */
5431 dev->tempBuffer[i].buffer =
5432 YMALLOC(dev->nBytesPerChunk);
5436 yaffs_InitialiseBlocks(dev, nBlocks);
5438 yaffs_InitialiseTnodes(dev);
5440 yaffs_InitialiseObjects(dev);
5442 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
5444 if (dev->nShortOpCaches > 0) {
5447 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
5448 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5452 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
5454 for (i = 0; i < dev->nShortOpCaches; i++) {
5455 dev->srCache[i].object = NULL;
5456 dev->srCache[i].lastUse = 0;
5457 dev->srCache[i].dirty = 0;
5458 dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
5465 /* Initialise the unlinked, root and lost and found directories */
5466 dev->lostNFoundDir = dev->rootDir = NULL;
5467 dev->unlinkedDir = dev->deletedDir = NULL;
5470 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5472 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5475 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5476 YAFFS_ROOT_MODE | S_IFDIR);
5477 dev->lostNFoundDir =
5478 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5479 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5480 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5482 if (dev->isYaffs2) {
5483 dev->useHeaderFileSize = 1;
5486 /* Now scan the flash. */
5488 yaffs_ScanBackwards(dev);
5492 /* Zero out stats */
5493 dev->nPageReads = 0;
5494 dev->nPageWrites = 0;
5495 dev->nBlockErasures = 0;
5497 dev->nRetriedWrites = 0;
5499 dev->nRetiredBlocks = 0;
5501 yaffs_VerifyFreeChunks(dev);
5503 T(YAFFS_TRACE_ALWAYS,
5504 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5509 void yaffs_Deinitialise(yaffs_Device * dev)
5511 if (dev->isMounted) {
5514 yaffs_DeinitialiseBlocks(dev);
5515 yaffs_DeinitialiseTnodes(dev);
5516 yaffs_DeinitialiseObjects(dev);
5517 if (dev->nShortOpCaches > 0) {
5519 for (i = 0; i < dev->nShortOpCaches; i++) {
5520 YFREE(dev->srCache[i].data);
5523 YFREE(dev->srCache);
5526 YFREE(dev->gcCleanupList);
5528 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5529 YFREE(dev->tempBuffer[i].buffer);
5537 static int yaffs_CountFreeChunks(yaffs_Device * dev)
5542 yaffs_BlockInfo *blk;
5544 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
5546 blk = yaffs_GetBlockInfo(dev, b);
5548 switch (blk->blockState) {
5549 case YAFFS_BLOCK_STATE_EMPTY:
5550 case YAFFS_BLOCK_STATE_ALLOCATING:
5551 case YAFFS_BLOCK_STATE_COLLECTING:
5552 case YAFFS_BLOCK_STATE_FULL:
5554 (dev->nChunksPerBlock - blk->pagesInUse +
5555 blk->softDeletions);
5566 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
5568 /* This is what we report to the outside world */
5571 int nDirtyCacheChunks;
5574 nFree = dev->nFreeChunks;
5576 nFree = yaffs_CountFreeChunks(dev);
5579 /* Now count the number of dirty chunks in the cache and subtract those */
5583 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
5584 if (dev->srCache[i].dirty)
5585 nDirtyCacheChunks++;
5589 nFree -= nDirtyCacheChunks;
5591 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
5600 static int yaffs_freeVerificationFailures;
5602 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
5604 int counted = yaffs_CountFreeChunks(dev);
5606 int difference = dev->nFreeChunks - counted;
5609 T(YAFFS_TRACE_ALWAYS,
5610 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
5611 dev->nFreeChunks, counted, difference));
5612 yaffs_freeVerificationFailures++;
5616 /*---------------------------------------- YAFFS test code ----------------------*/
5618 #define yaffs_CheckStruct(structure,syze, name) \
5619 if(sizeof(structure) != syze) \
5621 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
5622 name,syze,sizeof(structure))); \
5623 return YAFFS_FAIL; \
5626 static int yaffs_CheckStructures(void)
5628 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
5629 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
5630 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
5631 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5632 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
5634 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")