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;