2 * YAFFS: Yet another FFS. A NAND-flash specific file system.
4 * Copyright (C) 2002 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
15 const char *yaffs_guts_c_version =
16 "$Id: yaffs_guts.c,v 1.24 2005-12-07 21:49:18 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
26 #ifdef CONFIG_YAFFS_WINCE
27 void yfsd_LockYAFFS(BOOL fsLockOnly);
28 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
31 #define YAFFS_PASSIVE_GC_CHUNKS 2
33 #include "yaffs_ecc.h"
37 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev,
40 yaffs_ExtendedTags * tags);
41 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
44 yaffs_ExtendedTags * tags);
45 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo);
46 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
48 yaffs_BlockState * state,
49 unsigned *sequenceNumber);
50 /* Robustification (if it ever comes about...) */
51 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
52 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND);
53 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
55 const yaffs_ExtendedTags * tags);
56 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
57 const yaffs_ExtendedTags * tags);
59 /* Other local prototypes */
60 static int yaffs_UnlinkObject( yaffs_Object *obj);
62 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
64 yaffs_ExtendedTags * tags,
66 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
67 int chunkInNAND, int inScan);
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
70 yaffs_ObjectType type);
71 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
73 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
74 int force, int isShrink, int shadows);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
78 int chunkOffset, int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
83 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
84 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
87 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
90 static int yaffs_UnlinkWorker(yaffs_Object * obj);
91 static void yaffs_DestroyObject(yaffs_Object * obj);
93 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
96 loff_t yaffs_GetFileSize(yaffs_Object * obj);
98 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
100 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
113 * Start of real code.
122 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
124 yaffs_ExtendedTags * tags)
126 chunkInNAND -= dev->chunkOffset;
128 if (dev->readChunkWithTagsFromNAND)
129 return dev->readChunkWithTagsFromNAND(dev, chunkInNAND, buffer,
132 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,
138 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
141 yaffs_ExtendedTags * tags)
143 chunkInNAND -= dev->chunkOffset;
146 tags->sequenceNumber = dev->sequenceNumber;
148 if (!yaffs_ValidateTags(tags)) {
150 (TSTR("Writing uninitialised tags" TENDSTR)));
154 (TSTR("Writing chunk %d tags %d %d" TENDSTR), chunkInNAND,
155 tags->objectId, tags->chunkId));
157 T(YAFFS_TRACE_ERROR, (TSTR("Writing with no tags" TENDSTR)));
161 if (dev->writeChunkWithTagsToNAND)
162 return dev->writeChunkWithTagsToNAND(dev, chunkInNAND, buffer,
165 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,
171 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo)
173 blockNo -= dev->blockOffset;
175 if (dev->markNANDBlockBad)
176 return dev->markNANDBlockBad(dev, blockNo);
178 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev, blockNo);
180 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
182 yaffs_BlockState * state,
183 unsigned *sequenceNumber)
185 blockNo -= dev->blockOffset;
187 if (dev->queryNANDBlock)
188 return dev->queryNANDBlock(dev, blockNo, state, sequenceNumber);
190 return yaffs_TagsCompatabilityQueryNANDBlock(dev, blockNo,
195 static int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,
200 blockInNAND -= dev->blockOffset;
202 dev->nBlockErasures++;
203 result = dev->eraseBlockInNAND(dev, blockInNAND);
205 /* If at first we don't succeed, try again *once*.*/
207 result = dev->eraseBlockInNAND(dev, blockInNAND);
211 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
213 return dev->initialiseNAND(dev);
217 * Temporary buffer manipulations.
220 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
223 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
224 if (dev->tempBuffer[i].line == 0) {
225 dev->tempBuffer[i].line = lineNo;
226 if ((i + 1) > dev->maxTemp) {
227 dev->maxTemp = i + 1;
228 for (j = 0; j <= i; j++)
229 dev->tempBuffer[j].maxLine =
230 dev->tempBuffer[j].line;
233 return dev->tempBuffer[i].buffer;
237 T(YAFFS_TRACE_BUFFERS,
238 (TSTR("Out of temp buffers at line %d, other held by lines:"),
240 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
243 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
246 * If we got here then we have to allocate an unmanaged one
250 dev->unmanagedTempAllocations++;
251 return YMALLOC(dev->nBytesPerChunk);
255 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
259 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
260 if (dev->tempBuffer[i].buffer == buffer) {
261 dev->tempBuffer[i].line = 0;
267 /* assume it is an unmanaged one. */
268 T(YAFFS_TRACE_BUFFERS,
269 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
272 dev->unmanagedTempDeallocations++;
278 * Chunk bitmap manipulations
281 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
283 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
285 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
289 return dev->chunkBits +
290 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
293 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
295 __u8 *blkBits = yaffs_BlockBits(dev, blk);
297 memset(blkBits, 0, dev->chunkBitmapStride);
300 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
302 __u8 *blkBits = yaffs_BlockBits(dev, blk);
304 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
307 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
309 __u8 *blkBits = yaffs_BlockBits(dev, blk);
311 blkBits[chunk / 8] |= (1 << (chunk & 7));
314 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
316 __u8 *blkBits = yaffs_BlockBits(dev, blk);
317 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
320 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
322 __u8 *blkBits = yaffs_BlockBits(dev, blk);
324 for (i = 0; i < dev->chunkBitmapStride; i++) {
333 * Simple hash function. Needs to have a reasonable spread
336 static Y_INLINE int yaffs_HashFunction(int n)
338 return (n % YAFFS_NOBJECT_BUCKETS);
342 * Access functions to useful fake objects
345 yaffs_Object *yaffs_Root(yaffs_Device * dev)
350 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
352 return dev->lostNFoundDir;
357 * Erased NAND checking functions
360 int yaffs_CheckFF(__u8 * buffer, int nBytes)
362 /* Horrible, slow implementation */
371 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
375 int retval = YAFFS_OK;
376 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
377 yaffs_ExtendedTags tags;
379 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
381 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
382 T(YAFFS_TRACE_NANDACCESS,
383 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
387 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
393 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
395 yaffs_ExtendedTags * tags,
404 chunk = yaffs_AllocateChunk(dev, useReserve);
408 /* First check this chunk is erased... */
409 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
410 writeOk = yaffs_CheckChunkErased(dev, chunk);
415 ("**>> yaffs chunk %d was not erased"
419 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
426 * Copy the data into the robustification buffer.
427 * NB We do this at the end to prevent duplicates in the case of a write error.
430 yaffs_HandleWriteChunkOk(dev, chunk, data,
433 yaffs_HandleWriteChunkError(dev, chunk);
437 } while (chunk >= 0 && !writeOk);
441 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
443 dev->nRetriedWrites += (attempts - 1);
450 * Block retiring for handling a broken block.
453 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
456 yaffs_MarkBlockBad(dev, blockInNAND);
458 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
459 YAFFS_BLOCK_STATE_DEAD;
461 dev->nRetiredBlocks++;
465 * Functions for robustisizing TODO
469 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
471 const yaffs_ExtendedTags * tags)
475 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
476 const yaffs_ExtendedTags * tags)
480 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
482 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
484 /* Mark the block for retirement */
485 yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
486 /* Delete the chunk */
487 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
491 /*---------------- Name handling functions ------------*/
493 static __u16 yaffs_CalcNameSum(const YCHAR * name)
498 YUCHAR *bname = (YUCHAR *) name;
500 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
502 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
503 sum += yaffs_toupper(*bname) * i;
514 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
516 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
517 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
518 yaffs_strcpy(obj->shortName, name);
520 obj->shortName[0] = _Y('\0');
523 obj->sum = yaffs_CalcNameSum(name);
526 /*-------------------- TNODES -------------------
528 * List of spare tnodes
529 * The list is hooked together using the first pointer
533 /* yaffs_CreateTnodes creates a bunch more tnodes and
534 * adds them to the tnode free list.
535 * Don't use this function directly
538 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
542 yaffs_Tnode *newTnodes;
544 yaffs_Tnode *current;
546 yaffs_TnodeList *tnl;
551 /* Calculate the tnode size in bytes for variable width tnode support.
552 * Must be a multiple of 32-bits */
553 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
555 /* make these things */
557 mem = newTnodes = YMALLOC(nTnodes * tnodeSize);
561 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
565 /* Hook them into the free list */
567 for (i = 0; i < nTnodes - 1; i++) {
568 newTnodes[i].internal[0] = &newTnodes[i + 1];
569 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
570 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
574 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
575 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
576 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
578 dev->freeTnodes = newTnodes;
580 /* New hookup for wide tnodes */
581 for(i = 0; i < nTnodes -1; i++) {
582 current = (yaffs_Tnode *) &mem[i * tnodeSize];
583 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
584 current->internal[0] = next;
587 current = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
588 current->internal[0] = dev->freeTnodes;
589 dev->freeTnodes = (yaffs_Tnode *)mem;
594 dev->nFreeTnodes += nTnodes;
595 dev->nTnodesCreated += nTnodes;
597 /* Now add this bunch of tnodes to a list for freeing up.
598 * NB If we can't add this to the management list it isn't fatal
599 * but it just means we can't free this bunch of tnodes later.
602 tnl = YMALLOC(sizeof(yaffs_TnodeList));
606 ("yaffs: Could not add tnodes to management list" TENDSTR)));
609 tnl->tnodes = newTnodes;
610 tnl->next = dev->allocatedTnodeList;
611 dev->allocatedTnodeList = tnl;
614 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
619 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
621 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
623 yaffs_Tnode *tn = NULL;
625 /* If there are none left make more */
626 if (!dev->freeTnodes) {
627 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
630 if (dev->freeTnodes) {
631 tn = dev->freeTnodes;
632 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
633 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
634 /* Hoosterman, this thing looks like it isn't in the list */
635 T(YAFFS_TRACE_ALWAYS,
636 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
639 dev->freeTnodes = dev->freeTnodes->internal[0];
642 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
648 /* FreeTnode frees up a tnode and puts it back on the free list */
649 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
652 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
653 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
654 /* Hoosterman, this thing looks like it is already in the list */
655 T(YAFFS_TRACE_ALWAYS,
656 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
658 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
660 tn->internal[0] = dev->freeTnodes;
661 dev->freeTnodes = tn;
666 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
668 /* Free the list of allocated tnodes */
669 yaffs_TnodeList *tmp;
671 while (dev->allocatedTnodeList) {
672 tmp = dev->allocatedTnodeList->next;
674 YFREE(dev->allocatedTnodeList->tnodes);
675 YFREE(dev->allocatedTnodeList);
676 dev->allocatedTnodeList = tmp;
680 dev->freeTnodes = NULL;
681 dev->nFreeTnodes = 0;
684 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
686 dev->allocatedTnodeList = NULL;
687 dev->freeTnodes = NULL;
688 dev->nFreeTnodes = 0;
689 dev->nTnodesCreated = 0;
694 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
696 __u32 *map = (__u32 *)tn;
702 pos &= YAFFS_TNODES_LEVEL0_MASK;
703 val >>= dev->chunkGroupBits;
705 bitInMap = pos * dev->tnodeWidth;
706 wordInMap = bitInMap /32;
707 bitInWord = bitInMap & (32 -1);
709 mask = dev->tnodeMask << bitInWord;
711 map[wordInMap] &= ~mask;
712 map[wordInMap] |= (mask & (val << bitInWord));
714 if(dev->tnodeWidth > (32-bitInWord)) {
715 bitInWord = (32 - bitInWord);
717 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
718 map[wordInMap] &= ~mask;
719 map[wordInMap] |= (mask & (val >> bitInWord));
723 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
725 __u32 *map = (__u32 *)tn;
731 pos &= YAFFS_TNODES_LEVEL0_MASK;
733 bitInMap = pos * dev->tnodeWidth;
734 wordInMap = bitInMap /32;
735 bitInWord = bitInMap & (32 -1);
737 val = map[wordInMap] >> bitInWord;
739 if(dev->tnodeWidth > (32-bitInWord)) {
740 bitInWord = (32 - bitInWord);
742 val |= (map[wordInMap] << bitInWord);
745 val &= dev->tnodeMask;
746 val <<= dev->chunkGroupBits;
751 /* ------------------- End of individual tnode manipulation -----------------*/
753 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
754 * The look up tree is represented by the top tnode and the number of topLevel
755 * in the tree. 0 means only the level 0 tnode is in the tree.
758 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
759 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
760 yaffs_FileStructure * fStruct,
764 yaffs_Tnode *tn = fStruct->top;
766 int requiredTallness;
767 int level = fStruct->topLevel;
769 /* Check sane level and chunk Id */
770 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
774 if (chunkId > YAFFS_MAX_CHUNK_ID) {
778 /* First check we're tall enough (ie enough topLevel) */
780 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
781 requiredTallness = 0;
783 i >>= YAFFS_TNODES_INTERNAL_BITS;
787 if (requiredTallness > fStruct->topLevel) {
788 /* Not tall enough, so we can't find it, return NULL. */
792 /* Traverse down to level 0 */
793 while (level > 0 && tn) {
796 ( YAFFS_TNODES_LEVEL0_BITS +
798 YAFFS_TNODES_INTERNAL_BITS)
800 YAFFS_TNODES_INTERNAL_MASK];
808 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
809 * This happens in two steps:
810 * 1. If the tree isn't tall enough, then make it taller.
811 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
813 * Used when modifying the tree.
816 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
817 yaffs_FileStructure * fStruct,
823 int requiredTallness;
830 /* Check sane level and page Id */
831 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
835 if (chunkId > YAFFS_MAX_CHUNK_ID) {
839 /* First check we're tall enough (ie enough topLevel) */
841 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
842 requiredTallness = 0;
844 x >>= YAFFS_TNODES_INTERNAL_BITS;
849 if (requiredTallness > fStruct->topLevel) {
850 /* Not tall enough,gotta make the tree taller */
851 for (i = fStruct->topLevel; i < requiredTallness; i++) {
853 tn = yaffs_GetTnode(dev);
856 tn->internal[0] = fStruct->top;
860 (TSTR("yaffs: no more tnodes" TENDSTR)));
864 fStruct->topLevel = requiredTallness;
867 /* Traverse down to level 0, adding anything we need */
869 l = fStruct->topLevel;
871 while (l > 0 && tn) {
873 ( YAFFS_TNODES_LEVEL0_BITS +
874 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
875 YAFFS_TNODES_INTERNAL_MASK;
878 if (!tn->internal[x])
879 tn->internal[x] = yaffs_GetTnode(dev);
881 tn = tn->internal[x];
889 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
890 yaffs_ExtendedTags * tags, int objectId,
895 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
896 if (yaffs_CheckChunkBit
897 (dev, theChunk / dev->nChunksPerBlock,
898 theChunk % dev->nChunksPerBlock)) {
899 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
901 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
913 /* DeleteWorker scans backwards through the tnode tree and deletes all the
914 * chunks and tnodes in the file
915 * Returns 1 if the tree was deleted.
916 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
919 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
920 int chunkOffset, int *limit)
925 yaffs_ExtendedTags tags;
927 yaffs_Device *dev = in->myDev;
934 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
936 if (tn->internal[i]) {
937 if (limit && (*limit) < 0) {
941 yaffs_DeleteWorker(in,
949 YAFFS_TNODES_INTERNAL_BITS)
957 tn->internal[i] = NULL;
962 return (allDone) ? 1 : 0;
963 } else if (level == 0) {
966 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
968 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
973 YAFFS_TNODES_LEVEL0_BITS) + i;
976 yaffs_FindChunkInGroup(dev,
982 if (foundChunk > 0) {
983 yaffs_DeleteChunk(dev,
996 yaffs_PutLevel0Tnode(dev,tn,i,0);
1000 return (i < 0) ? 1 : 0;
1010 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1013 yaffs_BlockInfo *theBlock;
1015 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1017 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1019 theBlock->softDeletions++;
1024 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1025 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1027 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1030 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1031 __u32 level, int chunkOffset)
1036 yaffs_Device *dev = in->myDev;
1041 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1043 if (tn->internal[i]) {
1045 yaffs_SoftDeleteWorker(in,
1051 YAFFS_TNODES_INTERNAL_BITS)
1054 yaffs_FreeTnode(dev,
1057 tn->internal[i] = NULL;
1059 /* Hoosterman... how could this happen? */
1063 return (allDone) ? 1 : 0;
1064 } else if (level == 0) {
1066 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1067 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1069 /* Note this does not find the real chunk, only the chunk group.
1070 * We make an assumption that a chunk group is not larger than
1073 yaffs_SoftDeleteChunk(dev, theChunk);
1074 yaffs_PutLevel0Tnode(dev,tn,i,0);
1088 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1091 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1092 if (obj->nDataChunks <= 0) {
1093 /* Empty file with no duplicate object headers, just delete it immediately */
1094 yaffs_FreeTnode(obj->myDev,
1095 obj->variant.fileVariant.top);
1096 obj->variant.fileVariant.top = NULL;
1097 T(YAFFS_TRACE_TRACING,
1098 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1100 yaffs_DoGenericObjectDeletion(obj);
1102 yaffs_SoftDeleteWorker(obj,
1103 obj->variant.fileVariant.top,
1104 obj->variant.fileVariant.
1106 obj->softDeleted = 1;
1111 /* Pruning removes any part of the file structure tree that is beyond the
1112 * bounds of the file (ie that does not point to chunks).
1114 * A file should only get pruned when its size is reduced.
1116 * Before pruning, the chunks must be pulled from the tree and the
1117 * level 0 tnode entries must be zeroed out.
1118 * Could also use this for file deletion, but that's probably better handled
1119 * by a special case.
1122 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1123 __u32 level, int del0)
1131 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1132 if (tn->internal[i] && level > 0) {
1134 yaffs_PruneWorker(dev, tn->internal[i],
1136 (i == 0) ? del0 : 1);
1139 if (tn->internal[i]) {
1144 if (hasData == 0 && del0) {
1145 /* Free and return NULL */
1147 yaffs_FreeTnode(dev, tn);
1157 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1158 yaffs_FileStructure * fStruct)
1165 if (fStruct->topLevel > 0) {
1167 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1169 /* Now we have a tree with all the non-zero branches NULL but the height
1170 * is the same as it was.
1171 * Let's see if we can trim internal tnodes to shorten the tree.
1172 * We can do this if only the 0th element in the tnode is in use
1173 * (ie all the non-zero are NULL)
1176 while (fStruct->topLevel && !done) {
1180 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1181 if (tn->internal[i]) {
1187 fStruct->top = tn->internal[0];
1188 fStruct->topLevel--;
1189 yaffs_FreeTnode(dev, tn);
1199 /*-------------------- End of File Structure functions.-------------------*/
1201 /* yaffs_CreateFreeObjects creates a bunch more objects and
1202 * adds them to the object free list.
1204 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1207 yaffs_Object *newObjects;
1208 yaffs_ObjectList *list;
1213 /* make these things */
1214 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1217 T(YAFFS_TRACE_ALLOCATE,
1218 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1222 /* Hook them into the free list */
1223 for (i = 0; i < nObjects - 1; i++) {
1224 newObjects[i].siblings.next =
1225 (struct list_head *)(&newObjects[i + 1]);
1228 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1229 dev->freeObjects = newObjects;
1230 dev->nFreeObjects += nObjects;
1231 dev->nObjectsCreated += nObjects;
1233 /* Now add this bunch of Objects to a list for freeing up. */
1235 list = YMALLOC(sizeof(yaffs_ObjectList));
1237 T(YAFFS_TRACE_ALLOCATE,
1238 (TSTR("Could not add objects to management list" TENDSTR)));
1240 list->objects = newObjects;
1241 list->next = dev->allocatedObjectList;
1242 dev->allocatedObjectList = list;
1249 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1250 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1252 yaffs_Object *tn = NULL;
1254 /* If there are none left make more */
1255 if (!dev->freeObjects) {
1256 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1259 if (dev->freeObjects) {
1260 tn = dev->freeObjects;
1262 (yaffs_Object *) (dev->freeObjects->siblings.next);
1263 dev->nFreeObjects--;
1265 /* Now sweeten it up... */
1267 memset(tn, 0, sizeof(yaffs_Object));
1270 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1271 INIT_LIST_HEAD(&(tn->hardLinks));
1272 INIT_LIST_HEAD(&(tn->hashLink));
1273 INIT_LIST_HEAD(&tn->siblings);
1275 /* Add it to the lost and found directory.
1276 * NB Can't put root or lostNFound in lostNFound so
1277 * check if lostNFound exists first
1279 if (dev->lostNFoundDir) {
1280 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1287 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1292 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1294 obj->fake = 1; /* it is fake so it has no NAND presence... */
1295 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1296 obj->unlinkAllowed = 0; /* ... or unlink it */
1299 obj->yst_mode = mode;
1301 obj->chunkId = 0; /* Not a valid chunk. */
1308 static void yaffs_UnhashObject(yaffs_Object * tn)
1311 yaffs_Device *dev = tn->myDev;
1313 /* If it is still linked into the bucket list, free from the list */
1314 if (!list_empty(&tn->hashLink)) {
1315 list_del_init(&tn->hashLink);
1316 bucket = yaffs_HashFunction(tn->objectId);
1317 dev->objectBucket[bucket].count--;
1322 /* FreeObject frees up a Object and puts it back on the free list */
1323 static void yaffs_FreeObject(yaffs_Object * tn)
1326 yaffs_Device *dev = tn->myDev;
1330 /* We're still hooked up to a cached inode.
1331 * Don't delete now, but mark for later deletion
1333 tn->deferedFree = 1;
1338 yaffs_UnhashObject(tn);
1340 /* Link into the free list. */
1341 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1342 dev->freeObjects = tn;
1343 dev->nFreeObjects++;
1348 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1350 if (obj->deferedFree) {
1351 yaffs_FreeObject(obj);
1357 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1359 /* Free the list of allocated Objects */
1361 yaffs_ObjectList *tmp;
1363 while (dev->allocatedObjectList) {
1364 tmp = dev->allocatedObjectList->next;
1365 YFREE(dev->allocatedObjectList->objects);
1366 YFREE(dev->allocatedObjectList);
1368 dev->allocatedObjectList = tmp;
1371 dev->freeObjects = NULL;
1372 dev->nFreeObjects = 0;
1375 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1379 dev->allocatedObjectList = NULL;
1380 dev->freeObjects = NULL;
1381 dev->nFreeObjects = 0;
1383 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1384 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1385 dev->objectBucket[i].count = 0;
1390 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1395 int lowest = 999999;
1397 /* First let's see if we can find one that's empty. */
1399 for (i = 0; i < 10 && lowest > 0; i++) {
1401 x %= YAFFS_NOBJECT_BUCKETS;
1402 if (dev->objectBucket[x].count < lowest) {
1403 lowest = dev->objectBucket[x].count;
1409 /* If we didn't find an empty list, then try
1410 * looking a bit further for a short one
1413 for (i = 0; i < 10 && lowest > 3; i++) {
1415 x %= YAFFS_NOBJECT_BUCKETS;
1416 if (dev->objectBucket[x].count < lowest) {
1417 lowest = dev->objectBucket[x].count;
1426 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1428 int bucket = yaffs_FindNiceObjectBucket(dev);
1430 /* Now find an object value that has not already been taken
1431 * by scanning the list.
1435 struct list_head *i;
1437 __u32 n = (__u32) bucket;
1439 /* yaffs_CheckObjectHashSanity(); */
1443 n += YAFFS_NOBJECT_BUCKETS;
1444 if (1 || dev->objectBucket[bucket].count > 0) {
1445 list_for_each(i, &dev->objectBucket[bucket].list) {
1446 /* If there is already one in the list */
1448 && list_entry(i, yaffs_Object,
1449 hashLink)->objectId == n) {
1460 static void yaffs_HashObject(yaffs_Object * in)
1462 int bucket = yaffs_HashFunction(in->objectId);
1463 yaffs_Device *dev = in->myDev;
1465 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1466 dev->objectBucket[bucket].count++;
1470 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1472 int bucket = yaffs_HashFunction(number);
1473 struct list_head *i;
1476 list_for_each(i, &dev->objectBucket[bucket].list) {
1477 /* Look if it is in the list */
1479 in = list_entry(i, yaffs_Object, hashLink);
1480 if (in->objectId == number) {
1482 /* Don't tell the VFS about this one if it is defered free */
1483 if (in->deferedFree)
1495 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1496 yaffs_ObjectType type)
1499 yaffs_Object *theObject;
1502 number = yaffs_CreateNewObjectNumber(dev);
1505 theObject = yaffs_AllocateEmptyObject(dev);
1508 theObject->fake = 0;
1509 theObject->renameAllowed = 1;
1510 theObject->unlinkAllowed = 1;
1511 theObject->objectId = number;
1512 yaffs_HashObject(theObject);
1513 theObject->variantType = type;
1514 #ifdef CONFIG_YAFFS_WINCE
1515 yfsd_WinFileTimeNow(theObject->win_atime);
1516 theObject->win_ctime[0] = theObject->win_mtime[0] =
1517 theObject->win_atime[0];
1518 theObject->win_ctime[1] = theObject->win_mtime[1] =
1519 theObject->win_atime[1];
1523 theObject->yst_atime = theObject->yst_mtime =
1524 theObject->yst_ctime = Y_CURRENT_TIME;
1527 case YAFFS_OBJECT_TYPE_FILE:
1528 theObject->variant.fileVariant.fileSize = 0;
1529 theObject->variant.fileVariant.scannedFileSize = 0;
1530 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1531 theObject->variant.fileVariant.topLevel = 0;
1532 theObject->variant.fileVariant.top =
1533 yaffs_GetTnode(dev);
1535 case YAFFS_OBJECT_TYPE_DIRECTORY:
1536 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1539 case YAFFS_OBJECT_TYPE_SYMLINK:
1540 case YAFFS_OBJECT_TYPE_HARDLINK:
1541 case YAFFS_OBJECT_TYPE_SPECIAL:
1542 /* No action required */
1544 case YAFFS_OBJECT_TYPE_UNKNOWN:
1545 /* todo this should not happen */
1553 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1555 yaffs_ObjectType type)
1557 yaffs_Object *theObject = NULL;
1560 theObject = yaffs_FindObjectByNumber(dev, number);
1564 theObject = yaffs_CreateNewObject(dev, number, type);
1571 static YCHAR *yaffs_CloneString(const YCHAR * str)
1573 YCHAR *newStr = NULL;
1576 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1577 yaffs_strcpy(newStr, str);
1585 * Mknod (create) a new object.
1586 * equivalentObject only has meaning for a hard link;
1587 * aliasString only has meaning for a sumlink.
1588 * rdev only has meaning for devices (a subset of special objects)
1591 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1592 yaffs_Object * parent,
1597 yaffs_Object * equivalentObject,
1598 const YCHAR * aliasString, __u32 rdev)
1602 yaffs_Device *dev = parent->myDev;
1604 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1605 if (yaffs_FindObjectByName(parent, name)) {
1609 in = yaffs_CreateNewObject(dev, -1, type);
1614 in->variantType = type;
1616 in->yst_mode = mode;
1618 #ifdef CONFIG_YAFFS_WINCE
1619 yfsd_WinFileTimeNow(in->win_atime);
1620 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1621 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1624 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1626 in->yst_rdev = rdev;
1630 in->nDataChunks = 0;
1632 yaffs_SetObjectName(in, name);
1635 yaffs_AddObjectToDirectory(parent, in);
1637 in->myDev = parent->myDev;
1640 case YAFFS_OBJECT_TYPE_SYMLINK:
1641 in->variant.symLinkVariant.alias =
1642 yaffs_CloneString(aliasString);
1644 case YAFFS_OBJECT_TYPE_HARDLINK:
1645 in->variant.hardLinkVariant.equivalentObject =
1647 in->variant.hardLinkVariant.equivalentObjectId =
1648 equivalentObject->objectId;
1649 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1651 case YAFFS_OBJECT_TYPE_FILE:
1652 case YAFFS_OBJECT_TYPE_DIRECTORY:
1653 case YAFFS_OBJECT_TYPE_SPECIAL:
1654 case YAFFS_OBJECT_TYPE_UNKNOWN:
1659 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1660 /* Could not create the object header, fail the creation */
1661 yaffs_DestroyObject(in);
1670 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1671 __u32 mode, __u32 uid, __u32 gid)
1673 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1674 uid, gid, NULL, NULL, 0);
1677 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1678 __u32 mode, __u32 uid, __u32 gid)
1680 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1681 mode, uid, gid, NULL, NULL, 0);
1684 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1685 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1687 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1688 uid, gid, NULL, NULL, rdev);
1691 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1692 __u32 mode, __u32 uid, __u32 gid,
1693 const YCHAR * alias)
1695 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1696 uid, gid, NULL, alias, 0);
1699 /* yaffs_Link returns the object id of the equivalent object.*/
1700 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1701 yaffs_Object * equivalentObject)
1703 /* Get the real object in case we were fed a hard link as an equivalent object */
1704 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1706 if (yaffs_MknodObject
1707 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1708 equivalentObject, NULL, 0)) {
1709 return equivalentObject;
1716 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1717 const YCHAR * newName, int force, int shadows)
1722 yaffs_Object *existingTarget;
1724 if (newDir == NULL) {
1725 newDir = obj->parent; /* use the old directory */
1728 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1729 T(YAFFS_TRACE_ALWAYS,
1731 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1736 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1737 if (obj->myDev->isYaffs2) {
1738 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1740 unlinkOp = (newDir == obj->myDev->unlinkedDir
1741 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1744 deleteOp = (newDir == obj->myDev->deletedDir);
1746 existingTarget = yaffs_FindObjectByName(newDir, newName);
1748 /* If the object is a file going into the unlinked directory,
1749 * then it is OK to just stuff it in since duplicate names are allowed.
1750 * else only proceed if the new name does not exist and if we're putting
1751 * it into a directory.
1758 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1759 yaffs_SetObjectName(obj, newName);
1762 yaffs_AddObjectToDirectory(newDir, obj);
1767 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1768 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1775 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1776 yaffs_Object * newDir, const YCHAR * newName)
1779 yaffs_Object *existingTarget;
1782 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1783 /* Special case for case insemsitive systems (eg. WinCE).
1784 * While look-up is case insensitive, the name isn't.
1785 * Therefore we might want to change x.txt to X.txt
1787 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1792 obj = yaffs_FindObjectByName(oldDir, oldName);
1794 if (obj && obj->renameAllowed) {
1796 /* Now do the handling for an existing target, if there is one */
1798 existingTarget = yaffs_FindObjectByName(newDir, newName);
1799 if (existingTarget &&
1800 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1801 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1802 /* There is a target that is a non-empty directory, so we fail */
1803 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1804 } else if (existingTarget && existingTarget != obj) {
1805 /* Nuke the target first, using shadowing,
1806 * but only if it isn't the same object
1808 yaffs_ChangeObjectName(obj, newDir, newName, force,
1809 existingTarget->objectId);
1810 yaffs_UnlinkObject(existingTarget);
1813 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1818 /*------------------------- Block Management and Page Allocation ----------------*/
1820 static int yaffs_InitialiseBlocks(yaffs_Device * dev, int nBlocks)
1822 dev->allocationBlock = -1; /* force it to get a new one */
1824 /* Todo we're assuming the malloc will pass. */
1825 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1826 if(!dev->blockInfo){
1827 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1828 dev->blockInfoAlt = 1;
1831 dev->blockInfoAlt = 0;
1833 /* Set up dynamic blockinfo stuff. */
1834 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8;
1835 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1836 if(!dev->chunkBits){
1837 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1838 dev->chunkBitsAlt = 1;
1841 dev->chunkBitsAlt = 0;
1843 if (dev->blockInfo && dev->chunkBits) {
1844 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1845 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1853 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1855 if(dev->blockInfoAlt)
1856 YFREE_ALT(dev->blockInfo);
1858 YFREE(dev->blockInfo);
1859 dev->blockInfoAlt = 0;
1861 dev->blockInfo = NULL;
1863 if(dev->chunkBitsAlt)
1864 YFREE_ALT(dev->chunkBits);
1866 YFREE(dev->chunkBits);
1867 dev->chunkBitsAlt = 0;
1868 dev->chunkBits = NULL;
1871 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1872 yaffs_BlockInfo * bi)
1879 return 1; /* disqualification only applies to yaffs2. */
1881 if (!bi->hasShrinkHeader)
1882 return 1; /* can gc */
1884 /* Find the oldest dirty sequence number if we don't know it and save it
1885 * so we don't have to keep recomputing it.
1887 if (!dev->oldestDirtySequence) {
1888 seq = dev->sequenceNumber;
1890 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1892 b = yaffs_GetBlockInfo(dev, i);
1893 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1894 (b->pagesInUse - b->softDeletions) <
1895 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1896 seq = b->sequenceNumber;
1899 dev->oldestDirtySequence = seq;
1902 /* Can't do gc of this block if there are any blocks older than this one that have
1905 return (bi->sequenceNumber <= dev->oldestDirtySequence);
1911 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1912 * for garbage collection.
1915 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1919 int b = dev->currentDirtyChecker;
1925 yaffs_BlockInfo *bi;
1926 static int nonAggressiveSkip = 0;
1928 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1930 * else (we're doing a leasurely gc), then we only bother to do this if the
1931 * block has only a few pages in use.
1934 nonAggressiveSkip--;
1936 if (!aggressive && (nonAggressiveSkip > 0)) {
1941 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1945 dev->internalEndBlock - dev->internalStartBlock + 1;
1948 dev->internalEndBlock - dev->internalStartBlock + 1;
1949 iterations = iterations / 16;
1950 if (iterations > 200) {
1955 for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1957 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1958 b = dev->internalStartBlock;
1961 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1962 T(YAFFS_TRACE_ERROR,
1963 (TSTR("**>> Block %d is not valid" TENDSTR), b));
1967 bi = yaffs_GetBlockInfo(dev, b);
1969 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1970 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1971 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1973 pagesInUse = (bi->pagesInUse - bi->softDeletions);
1977 dev->currentDirtyChecker = b;
1981 (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1982 dev->nChunksPerBlock - pagesInUse));
1985 dev->oldestDirtySequence = 0;
1988 nonAggressiveSkip = 4;
1994 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1996 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2000 /* If the block is still healthy erase it and mark as clean.
2001 * If the block has had a data failure, then retire it.
2003 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2005 if (!bi->needsRetiring) {
2006 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2008 dev->nErasureFailures++;
2009 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2010 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2014 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2016 for (i = 0; i < dev->nChunksPerBlock; i++) {
2017 if (!yaffs_CheckChunkErased
2018 (dev, blockNo * dev->nChunksPerBlock + i)) {
2019 T(YAFFS_TRACE_ERROR,
2021 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2022 TENDSTR), blockNo, i));
2028 /* Clean it up... */
2029 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2030 dev->nErasedBlocks++;
2032 bi->softDeletions = 0;
2033 bi->hasShrinkHeader = 0;
2034 yaffs_ClearChunkBits(dev, blockNo);
2036 T(YAFFS_TRACE_ERASE,
2037 (TSTR("Erased block %d" TENDSTR), blockNo));
2039 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2041 yaffs_RetireBlock(dev, blockNo);
2042 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2043 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2047 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2051 yaffs_BlockInfo *bi;
2053 if (dev->nErasedBlocks < 1) {
2054 /* Hoosterman we've got a problem.
2055 * Can't get space to gc
2057 T(YAFFS_TRACE_ERROR,
2058 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2063 /* Find an empty block. */
2065 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2066 dev->allocationBlockFinder++;
2067 if (dev->allocationBlockFinder < dev->internalStartBlock
2068 || dev->allocationBlockFinder > dev->internalEndBlock) {
2069 dev->allocationBlockFinder = dev->internalStartBlock;
2072 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2074 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2075 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2076 dev->sequenceNumber++;
2077 bi->sequenceNumber = dev->sequenceNumber;
2078 dev->nErasedBlocks--;
2079 T(YAFFS_TRACE_ALLOCATE,
2080 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2081 dev->allocationBlockFinder, dev->sequenceNumber,
2082 dev->nErasedBlocks));
2083 return dev->allocationBlockFinder;
2087 T(YAFFS_TRACE_ALWAYS,
2089 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2090 TENDSTR), dev->nErasedBlocks));
2097 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2099 int reservedChunks = (dev->nReservedBlocks * dev->nChunksPerBlock);
2100 return (dev->nFreeChunks > reservedChunks);
2103 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2106 yaffs_BlockInfo *bi;
2108 if (dev->allocationBlock < 0) {
2109 /* Get next block to allocate off */
2110 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2111 dev->allocationPage = 0;
2114 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2115 /* Not enough space to allocate unless we're allowed to use the reserve. */
2119 if (dev->nErasedBlocks < dev->nReservedBlocks
2120 && dev->allocationPage == 0) {
2121 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2124 /* Next page please.... */
2125 if (dev->allocationBlock >= 0) {
2126 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2128 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2129 dev->allocationPage;
2131 yaffs_SetChunkBit(dev, dev->allocationBlock,
2132 dev->allocationPage);
2134 dev->allocationPage++;
2138 /* If the block is full set the state to full */
2139 if (dev->allocationPage >= dev->nChunksPerBlock) {
2140 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2141 dev->allocationBlock = -1;
2147 T(YAFFS_TRACE_ERROR,
2148 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2153 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2157 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2159 if (dev->allocationBlock > 0) {
2160 n += (dev->nChunksPerBlock - dev->allocationPage);
2167 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2173 int retVal = YAFFS_OK;
2177 int chunksBefore = yaffs_GetErasedChunks(dev);
2180 yaffs_ExtendedTags tags;
2182 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2184 yaffs_Object *object;
2186 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2188 T(YAFFS_TRACE_TRACING,
2189 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2190 bi->pagesInUse, bi->hasShrinkHeader));
2192 /*yaffs_VerifyFreeChunks(dev); */
2194 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2196 /* Take off the number of soft deleted entries because
2197 * they're going to get really deleted during GC.
2199 dev->nFreeChunks -= bi->softDeletions;
2203 if (!yaffs_StillSomeChunkBits(dev, block)) {
2204 T(YAFFS_TRACE_TRACING,
2206 ("Collecting block %d that has no chunks in use" TENDSTR),
2208 yaffs_BlockBecameDirty(dev, block);
2211 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2213 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2214 chunkInBlock < dev->nChunksPerBlock
2215 && yaffs_StillSomeChunkBits(dev, block);
2216 chunkInBlock++, oldChunk++) {
2217 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2219 /* This page is in use and might need to be copied off */
2223 yaffs_InitialiseTags(&tags);
2225 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2229 yaffs_FindObjectByNumber(dev,
2232 T(YAFFS_TRACE_GC_DETAIL,
2234 ("Collecting page %d, %d %d %d " TENDSTR),
2235 chunkInBlock, tags.objectId, tags.chunkId,
2239 T(YAFFS_TRACE_ERROR,
2241 ("page %d in gc has no object "
2242 TENDSTR), oldChunk));
2245 if (object && object->deleted
2246 && tags.chunkId != 0) {
2247 /* Data chunk in a deleted file, throw it away
2248 * It's a soft deleted data chunk,
2249 * No need to copy this, just forget about it and
2250 * fix up the object.
2253 object->nDataChunks--;
2255 if (object->nDataChunks <= 0) {
2256 /* remeber to clean up the object */
2257 dev->gcCleanupList[cleanups] =
2263 /* Todo object && object->deleted && object->nDataChunks == 0 */
2265 /* Deleted object header with no data chunks.
2266 * Can be discarded and the file deleted.
2268 object->chunkId = 0;
2269 yaffs_FreeTnode(object->myDev,
2272 object->variant.fileVariant.top = NULL;
2273 yaffs_DoGenericObjectDeletion(object);
2275 } else if (object) {
2276 /* It's either a data chunk in a live file or
2277 * an ObjectHeader, so we're interested in it.
2278 * NB Need to keep the ObjectHeaders of deleted files
2279 * until the whole file has been deleted off
2281 tags.serialNumber++;
2285 if (tags.chunkId == 0) {
2286 /* It is an object Id,
2287 * We need to nuke the shrinkheader flags first
2288 * We no longer want the shrinkHeader flag since its work is done
2289 * and if it is left in place it will mess up scanning.
2290 * Also, clear out any shadowing stuff
2293 yaffs_ObjectHeader *oh;
2294 oh = (yaffs_ObjectHeader *)buffer;
2296 oh->shadowsObject = -1;
2297 tags.extraShadows = 0;
2298 tags.extraIsShrinkHeader = 0;
2302 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2305 retVal = YAFFS_FAIL;
2308 /* Ok, now fix up the Tnodes etc. */
2310 if (tags.chunkId == 0) {
2312 object->chunkId = newChunk;
2313 object->serial = tags.serialNumber;
2315 /* It's a data chunk */
2316 yaffs_PutChunkIntoFile
2324 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2329 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2332 /* Do any required cleanups */
2333 for (i = 0; i < cleanups; i++) {
2334 /* Time to delete the file too */
2336 yaffs_FindObjectByNumber(dev,
2337 dev->gcCleanupList[i]);
2339 yaffs_FreeTnode(dev,
2340 object->variant.fileVariant.
2342 object->variant.fileVariant.top = NULL;
2345 ("yaffs: About to finally delete object %d"
2346 TENDSTR), object->objectId));
2347 yaffs_DoGenericObjectDeletion(object);
2354 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2357 ("gc did not increase free chunks before %d after %d"
2358 TENDSTR), chunksBefore, chunksAfter));
2366 /* New garbage collector
2367 * If we're very low on erased blocks then we do aggressive garbage collection
2368 * otherwise we do "leasurely" garbage collection.
2369 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2370 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2372 * The idea is to help clear out space in a more spread-out manner.
2373 * Dunno if it really does anything useful.
2375 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2379 int gcOk = YAFFS_OK;
2382 if (dev->isDoingGC) {
2383 /* Bail out so we don't get recursive gc */
2387 /* This loop should pass the first time.
2388 * We'll only see looping here if the erase of the collected block fails.
2393 if (dev->nErasedBlocks < dev->nReservedBlocks) {
2394 /* We need a block soon...*/
2397 /* We're in no hurry */
2401 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2404 dev->garbageCollections++;
2406 dev->passiveGarbageCollections++;
2411 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2412 dev->nErasedBlocks, aggressive));
2414 gcOk = yaffs_GarbageCollectBlock(dev, block);
2417 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2420 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2421 TENDSTR), dev->nErasedBlocks, maxTries, block));
2423 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2426 return aggressive ? gcOk : YAFFS_OK;
2429 /*------------------------- TAGS --------------------------------*/
2431 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2434 return (tags->chunkId == chunkInObject &&
2435 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2440 /*-------------------- Data file manipulation -----------------*/
2442 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2443 yaffs_ExtendedTags * tags)
2445 /*Get the Tnode, then get the level 0 offset chunk offset */
2448 yaffs_ExtendedTags localTags;
2451 yaffs_Device *dev = in->myDev;
2454 /* Passed a NULL, so use our own tags space */
2458 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2461 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2464 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2470 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2471 yaffs_ExtendedTags * tags)
2473 /* Get the Tnode, then get the level 0 offset chunk offset */
2476 yaffs_ExtendedTags localTags;
2478 yaffs_Device *dev = in->myDev;
2482 /* Passed a NULL, so use our own tags space */
2486 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2490 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2493 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2496 /* Delete the entry in the filestructure (if found) */
2498 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2501 /*T(("No level 0 found for %d\n", chunkInInode)); */
2505 /* T(("Could not find %d to delete\n",chunkInInode)); */
2510 #ifdef YAFFS_PARANOID
2512 static int yaffs_CheckFileSanity(yaffs_Object * in)
2520 yaffs_Tags localTags;
2521 yaffs_Tags *tags = &localTags;
2525 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2526 /* T(("Object not a file\n")); */
2530 objId = in->objectId;
2531 fSize = in->variant.fileVariant.fileSize;
2533 (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2535 for (chunk = 1; chunk <= nChunks; chunk++) {
2536 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2541 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2543 if (yaffs_CheckChunkBits
2544 (dev, theChunk / dev->nChunksPerBlock,
2545 theChunk % dev->nChunksPerBlock)) {
2547 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2551 (tags, in->objectId, chunk, chunkDeleted)) {
2561 /* T(("No level 0 found for %d\n", chunk)); */
2565 return failed ? YAFFS_FAIL : YAFFS_OK;
2570 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2571 int chunkInNAND, int inScan)
2573 /* NB inScan is zero unless scanning.
2574 * For forward scanning, inScan is > 0;
2575 * for backward scanning inScan is < 0
2579 yaffs_Device *dev = in->myDev;
2581 yaffs_ExtendedTags existingTags;
2582 yaffs_ExtendedTags newTags;
2583 unsigned existingSerial, newSerial;
2585 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2586 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2587 * If it is not during Scanning then something went wrong!
2590 T(YAFFS_TRACE_ERROR,
2592 ("yaffs tragedy:attempt to put data chunk into a non-file"
2597 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2601 tn = yaffs_AddOrFindLevel0Tnode(dev, &in->variant.fileVariant,
2607 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2610 /* If we're scanning then we need to test for duplicates
2611 * NB This does not need to be efficient since it should only ever
2612 * happen when the power fails during a write, then only one
2613 * chunk should ever be affected.
2615 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2616 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2619 if (existingChunk != 0) {
2620 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2621 * thus we have to do a FindChunkInFile to get the real chunk id.
2623 * We have a duplicate now we need to decide which one to use:
2625 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2626 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2627 * YAFFS1: Get both sets of tags and compare serial numbers.
2631 /* Only do this for forward scanning */
2632 yaffs_ReadChunkWithTagsFromNAND(dev,
2636 /* Do a proper find */
2638 yaffs_FindChunkInFile(in, chunkInInode,
2642 if (existingChunk <= 0) {
2643 /*Hoosterman - how did this happen? */
2645 T(YAFFS_TRACE_ERROR,
2647 ("yaffs tragedy: existing chunk < 0 in scan"
2652 /* NB The deleted flags should be false, otherwise the chunks will
2653 * not be loaded during a scan
2656 newSerial = newTags.serialNumber;
2657 existingSerial = existingTags.serialNumber;
2660 (in->myDev->isYaffs2 ||
2661 existingChunk <= 0 ||
2662 ((existingSerial + 1) & 3) == newSerial)) {
2663 /* Forward scanning.
2665 * Delete the old one and drop through to update the tnode
2667 yaffs_DeleteChunk(dev, existingChunk, 1,
2670 /* Backward scanning or we want to use the existing one
2672 * Delete the new one and return early so that the tnode isn't changed
2674 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2682 if (existingChunk == 0) {
2686 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2691 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2694 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2696 if (chunkInNAND >= 0) {
2697 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2700 T(YAFFS_TRACE_NANDACCESS,
2701 (TSTR("Chunk %d not found zero instead" TENDSTR),
2703 /* get sane (zero) data if you read a hole */
2704 memset(buffer, 0, in->myDev->nBytesPerChunk);
2710 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2714 yaffs_ExtendedTags tags;
2715 yaffs_BlockInfo *bi;
2721 block = chunkId / dev->nChunksPerBlock;
2722 page = chunkId % dev->nChunksPerBlock;
2724 bi = yaffs_GetBlockInfo(dev, block);
2726 T(YAFFS_TRACE_DELETION,
2727 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2730 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2732 yaffs_InitialiseTags(&tags);
2734 tags.chunkDeleted = 1;
2736 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2737 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2739 dev->nUnmarkedDeletions++;
2742 /* Pull out of the management area.
2743 * If the whole block became dirty, this will kick off an erasure.
2745 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2746 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2747 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2748 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2751 yaffs_ClearChunkBit(dev, block, page);
2755 if (bi->pagesInUse == 0 &&
2756 !bi->hasShrinkHeader &&
2757 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2758 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2759 yaffs_BlockBecameDirty(dev, block);
2763 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2768 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2769 const __u8 * buffer, int nBytes,
2772 /* Find old chunk Need to do this to get serial number
2773 * Write new one and patch into tree.
2774 * Invalidate old tags.
2778 yaffs_ExtendedTags prevTags;
2781 yaffs_ExtendedTags newTags;
2783 yaffs_Device *dev = in->myDev;
2785 yaffs_CheckGarbageCollection(dev);
2787 /* Get the previous chunk at this location in the file if it exists */
2788 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2790 /* Set up new tags */
2791 yaffs_InitialiseTags(&newTags);
2793 newTags.chunkId = chunkInInode;
2794 newTags.objectId = in->objectId;
2795 newTags.serialNumber =
2796 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2797 newTags.byteCount = nBytes;
2800 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2803 if (newChunkId >= 0) {
2804 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2806 if (prevChunkId >= 0) {
2807 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2811 yaffs_CheckFileSanity(in);
2817 /* UpdateObjectHeader updates the header on NAND for an object.
2818 * If name is not NULL, then that new name is used.
2820 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2821 int isShrink, int shadows)
2824 yaffs_BlockInfo *bi;
2826 yaffs_Device *dev = in->myDev;
2832 yaffs_ExtendedTags newTags;
2834 __u8 *buffer = NULL;
2835 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2837 yaffs_ObjectHeader *oh = NULL;
2839 if (!in->fake || force) {
2841 yaffs_CheckGarbageCollection(dev);
2843 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2844 oh = (yaffs_ObjectHeader *) buffer;
2846 prevChunkId = in->chunkId;
2848 if (prevChunkId >= 0) {
2849 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2851 memcpy(oldName, oh->name, sizeof(oh->name));
2854 memset(buffer, 0xFF, dev->nBytesPerChunk);
2856 oh->type = in->variantType;
2857 oh->yst_mode = in->yst_mode;
2858 oh->shadowsObject = shadows;
2860 #ifdef CONFIG_YAFFS_WINCE
2861 oh->win_atime[0] = in->win_atime[0];
2862 oh->win_ctime[0] = in->win_ctime[0];
2863 oh->win_mtime[0] = in->win_mtime[0];
2864 oh->win_atime[1] = in->win_atime[1];
2865 oh->win_ctime[1] = in->win_ctime[1];
2866 oh->win_mtime[1] = in->win_mtime[1];
2868 oh->yst_uid = in->yst_uid;
2869 oh->yst_gid = in->yst_gid;
2870 oh->yst_atime = in->yst_atime;
2871 oh->yst_mtime = in->yst_mtime;
2872 oh->yst_ctime = in->yst_ctime;
2873 oh->yst_rdev = in->yst_rdev;
2876 oh->parentObjectId = in->parent->objectId;
2878 oh->parentObjectId = 0;
2881 if (name && *name) {
2882 memset(oh->name, 0, sizeof(oh->name));
2883 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2884 } else if (prevChunkId) {
2885 memcpy(oh->name, oldName, sizeof(oh->name));
2887 memset(oh->name, 0, sizeof(oh->name));
2890 oh->isShrink = isShrink;
2892 switch (in->variantType) {
2893 case YAFFS_OBJECT_TYPE_UNKNOWN:
2894 /* Should not happen */
2896 case YAFFS_OBJECT_TYPE_FILE:
2898 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2899 || oh->parentObjectId ==
2900 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2901 fileVariant.fileSize;
2903 case YAFFS_OBJECT_TYPE_HARDLINK:
2904 oh->equivalentObjectId =
2905 in->variant.hardLinkVariant.equivalentObjectId;
2907 case YAFFS_OBJECT_TYPE_SPECIAL:
2910 case YAFFS_OBJECT_TYPE_DIRECTORY:
2913 case YAFFS_OBJECT_TYPE_SYMLINK:
2914 yaffs_strncpy(oh->alias,
2915 in->variant.symLinkVariant.alias,
2916 YAFFS_MAX_ALIAS_LENGTH);
2917 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2922 yaffs_InitialiseTags(&newTags);
2924 newTags.chunkId = 0;
2925 newTags.objectId = in->objectId;
2926 newTags.serialNumber = in->serial;
2928 /* Add extra info for file header */
2930 newTags.extraHeaderInfoAvailable = 1;
2931 newTags.extraParentObjectId = oh->parentObjectId;
2932 newTags.extraFileLength = oh->fileSize;
2933 newTags.extraIsShrinkHeader = oh->isShrink;
2934 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2935 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2936 newTags.extraObjectType = in->variantType;
2938 /* Create new chunk in NAND */
2940 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2941 (prevChunkId >= 0) ? 1 : 0);
2943 if (newChunkId >= 0) {
2945 in->chunkId = newChunkId;
2947 if (prevChunkId >= 0) {
2948 yaffs_DeleteChunk(dev, prevChunkId, 1,
2954 /* If this was a shrink, then mark the block that the chunk lives on */
2956 bi = yaffs_GetBlockInfo(in->myDev,
2957 newChunkId /in->myDev-> nChunksPerBlock);
2958 bi->hasShrinkHeader = 1;
2963 retVal = newChunkId;
2968 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2973 /*------------------------ Short Operations Cache ----------------------------------------
2974 * In many situations where there is no high level buffering (eg WinCE) a lot of
2975 * reads might be short sequential reads, and a lot of writes may be short
2976 * sequential writes. eg. scanning/writing a jpeg file.
2977 * In these cases, a short read/write cache can provide a huge perfomance benefit
2978 * with dumb-as-a-rock code.
2979 * In Linux, the page cache provides read buffering aand the short op cache provides write
2982 * There are a limited number (~10) of cache chunks per device so that we don't
2983 * need a very intelligent search.
2986 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2988 yaffs_Device *dev = obj->myDev;
2989 int lowest = -99; /* Stop compiler whining. */
2991 yaffs_ChunkCache *cache;
2992 int chunkWritten = 0;
2993 int nCaches = obj->myDev->nShortOpCaches;
2999 /* Find the dirty cache for this object with the lowest chunk id. */
3000 for (i = 0; i < nCaches; i++) {
3001 if (dev->srCache[i].object == obj &&
3002 dev->srCache[i].dirty) {
3004 || dev->srCache[i].chunkId <
3006 cache = &dev->srCache[i];
3007 lowest = cache->chunkId;
3012 if (cache && !cache->locked) {
3013 /* Write it out and free it up */
3016 yaffs_WriteChunkDataToObject(cache->object,
3022 cache->object = NULL;
3025 } while (cache && chunkWritten > 0);
3028 /* Hoosterman, disk full while writing cache out. */
3029 T(YAFFS_TRACE_ERROR,
3030 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3037 /* Grab us a cache chunk for use.
3038 * First look for an empty one.
3039 * Then look for the least recently used non-dirty one.
3040 * Then look for the least recently used dirty one...., flush and look again.
3042 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3048 if (dev->nShortOpCaches > 0) {
3049 for (i = 0; i < dev->nShortOpCaches; i++) {
3050 if (!dev->srCache[i].object)
3051 return &dev->srCache[i];
3057 usage = 0; /* just to stop the compiler grizzling */
3059 for (i = 0; i < dev->nShortOpCaches; i++) {
3060 if (!dev->srCache[i].dirty &&
3061 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3063 usage = dev->srCache[i].lastUse;
3069 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3076 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3078 yaffs_ChunkCache *cache;
3079 yaffs_Object *theObj;
3084 if (dev->nShortOpCaches > 0) {
3085 /* Try find a non-dirty one... */
3087 cache = yaffs_GrabChunkCacheWorker(dev);
3090 /* They were all dirty, find the last recently used object and flush
3091 * its cache, then find again.
3092 * NB what's here is not very accurate, we actually flush the object
3093 * the last recently used page.
3096 /* With locking we can't assume we can use entry zero */
3103 for (i = 0; i < dev->nShortOpCaches; i++) {
3104 if (dev->srCache[i].object &&
3105 !dev->srCache[i].locked &&
3106 (dev->srCache[i].lastUse < usage || !cache))
3108 usage = dev->srCache[i].lastUse;
3109 theObj = dev->srCache[i].object;
3110 cache = &dev->srCache[i];
3115 if (!cache || cache->dirty) {
3116 /* Flush and try again */
3117 yaffs_FlushFilesChunkCache(theObj);
3118 cache = yaffs_GrabChunkCacheWorker(dev);
3128 /* Find a cached chunk */
3129 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3132 yaffs_Device *dev = obj->myDev;
3134 if (dev->nShortOpCaches > 0) {
3135 for (i = 0; i < dev->nShortOpCaches; i++) {
3136 if (dev->srCache[i].object == obj &&
3137 dev->srCache[i].chunkId == chunkId) {
3140 return &dev->srCache[i];
3147 /* Mark the chunk for the least recently used algorithym */
3148 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3152 if (dev->nShortOpCaches > 0) {
3153 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3154 /* Reset the cache usages */
3156 for (i = 1; i < dev->nShortOpCaches; i++) {
3157 dev->srCache[i].lastUse = 0;
3164 cache->lastUse = dev->srLastUse;
3172 /* Invalidate a single cache page.
3173 * Do this when a whole page gets written,
3174 * ie the short cache for this page is no longer valid.
3176 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3178 if (object->myDev->nShortOpCaches > 0) {
3179 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3182 cache->object = NULL;
3187 /* Invalidate all the cache pages associated with this object
3188 * Do this whenever ther file is deleted or resized.
3190 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3193 yaffs_Device *dev = in->myDev;
3195 if (dev->nShortOpCaches > 0) {
3196 /* Invalidate it. */
3197 for (i = 0; i < dev->nShortOpCaches; i++) {
3198 if (dev->srCache[i].object == in) {
3199 dev->srCache[i].object = NULL;
3205 /*--------------------- File read/write ------------------------
3206 * Read and write have very similar structures.
3207 * In general the read/write has three parts to it
3208 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3209 * Some complete chunks
3210 * An incomplete chunk to end off with
3212 * Curve-balls: the first chunk might also be the last chunk.
3215 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3224 yaffs_ChunkCache *cache;
3231 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3232 start = offset % dev->nBytesPerChunk;
3234 /* OK now check for the curveball where the start and end are in
3237 if ((start + n) < dev->nBytesPerChunk) {
3240 nToCopy = dev->nBytesPerChunk - start;
3243 cache = yaffs_FindChunkCache(in, chunk);
3245 /* If the chunk is already in the cache or it is less than a whole chunk
3246 * then use the cache (if there is caching)
3247 * else bypass the cache.
3249 if (cache || nToCopy != dev->nBytesPerChunk) {
3250 if (dev->nShortOpCaches > 0) {
3252 /* If we can't find the data in the cache, then load it up. */
3255 cache = yaffs_GrabChunkCache(in->myDev);
3257 cache->chunkId = chunk;
3260 yaffs_ReadChunkDataFromObject(in, chunk,
3266 yaffs_UseChunkCache(dev, cache, 0);
3270 #ifdef CONFIG_YAFFS_WINCE
3271 yfsd_UnlockYAFFS(TRUE);
3273 memcpy(buffer, &cache->data[start], nToCopy);
3275 #ifdef CONFIG_YAFFS_WINCE
3276 yfsd_LockYAFFS(TRUE);
3280 /* Read into the local buffer then copy..*/
3283 yaffs_GetTempBuffer(dev, __LINE__);
3284 yaffs_ReadChunkDataFromObject(in, chunk,
3286 #ifdef CONFIG_YAFFS_WINCE
3287 yfsd_UnlockYAFFS(TRUE);
3289 memcpy(buffer, &localBuffer[start], nToCopy);
3291 #ifdef CONFIG_YAFFS_WINCE
3292 yfsd_LockYAFFS(TRUE);
3294 yaffs_ReleaseTempBuffer(dev, localBuffer,
3299 #ifdef CONFIG_YAFFS_WINCE
3300 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3302 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3303 * This is because we otherwise screw up WinCE's memory mapper
3305 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3307 #ifdef CONFIG_YAFFS_WINCE
3308 yfsd_UnlockYAFFS(TRUE);
3310 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3312 #ifdef CONFIG_YAFFS_WINCE
3313 yfsd_LockYAFFS(TRUE);
3314 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3318 /* A full chunk. Read directly into the supplied buffer. */
3319 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3333 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3334 int nBytes, int writeThrough)
3343 int startOfWrite = offset;
3344 int chunkWritten = 0;
3351 while (n > 0 && chunkWritten >= 0) {
3352 chunk = offset / dev->nBytesPerChunk + 1;
3353 start = offset % dev->nBytesPerChunk;
3355 /* OK now check for the curveball where the start and end are in
3359 if ((start + n) < dev->nBytesPerChunk) {
3362 /* Now folks, to calculate how many bytes to write back....
3363 * If we're overwriting and not writing to then end of file then
3364 * we need to write back as much as was there before.
3368 in->variant.fileVariant.fileSize -
3369 ((chunk - 1) * dev->nBytesPerChunk);
3371 if (nBytesRead > dev->nBytesPerChunk) {
3372 nBytesRead = dev->nBytesPerChunk;
3377 (start + n)) ? nBytesRead : (start + n);
3380 nToCopy = dev->nBytesPerChunk - start;
3381 nToWriteBack = dev->nBytesPerChunk;
3384 if (nToCopy != dev->nBytesPerChunk) {
3385 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3386 if (dev->nShortOpCaches > 0) {
3387 yaffs_ChunkCache *cache;
3388 /* If we can't find the data in the cache, then load the cache */
3389 cache = yaffs_FindChunkCache(in, chunk);
3391 && yaffs_CheckSpaceForAllocation(in->
3393 cache = yaffs_GrabChunkCache(in->myDev);
3395 cache->chunkId = chunk;
3398 yaffs_ReadChunkDataFromObject(in, chunk,
3404 yaffs_UseChunkCache(dev, cache, 1);
3406 #ifdef CONFIG_YAFFS_WINCE
3407 yfsd_UnlockYAFFS(TRUE);
3410 memcpy(&cache->data[start], buffer,
3413 #ifdef CONFIG_YAFFS_WINCE
3414 yfsd_LockYAFFS(TRUE);
3417 cache->nBytes = nToWriteBack;
3421 yaffs_WriteChunkDataToObject
3424 cache->data, cache->nBytes,
3430 chunkWritten = -1; /* fail the write */
3433 /* An incomplete start or end chunk (or maybe both start and end chunk)
3434 * Read into the local buffer then copy, then copy over and write back.
3438 yaffs_GetTempBuffer(dev, __LINE__);
3440 yaffs_ReadChunkDataFromObject(in, chunk,
3443 #ifdef CONFIG_YAFFS_WINCE
3444 yfsd_UnlockYAFFS(TRUE);
3447 memcpy(&localBuffer[start], buffer, nToCopy);
3449 #ifdef CONFIG_YAFFS_WINCE
3450 yfsd_LockYAFFS(TRUE);
3453 yaffs_WriteChunkDataToObject(in, chunk,
3458 yaffs_ReleaseTempBuffer(dev, localBuffer,
3465 #ifdef CONFIG_YAFFS_WINCE
3466 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3467 * This is because we otherwise screw up WinCE's memory mapper
3469 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3470 #ifdef CONFIG_YAFFS_WINCE
3471 yfsd_UnlockYAFFS(TRUE);
3473 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3474 #ifdef CONFIG_YAFFS_WINCE
3475 yfsd_LockYAFFS(TRUE);
3478 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3479 dev->nBytesPerChunk,
3481 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3483 /* A full chunk. Write directly from the supplied buffer. */
3485 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3486 dev->nBytesPerChunk,
3489 /* Since we've overwritten the cached data, we better invalidate it. */
3490 yaffs_InvalidateChunkCache(in, chunk);
3493 if (chunkWritten >= 0) {
3502 /* Update file object */
3504 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3505 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3514 /* ---------------------- File resizing stuff ------------------ */
3516 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
3519 yaffs_Device *dev = in->myDev;
3520 int oldFileSize = in->variant.fileVariant.fileSize;
3522 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
3524 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
3525 dev->nBytesPerChunk;
3529 /* Delete backwards so that we don't end up with holes if
3530 * power is lost part-way through the operation.
3532 for (i = lastDel; i >= startDel; i--) {
3533 /* NB this could be optimised somewhat,
3534 * eg. could retrieve the tags and write them without
3535 * using yaffs_DeleteChunk
3538 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3541 (dev->internalStartBlock * dev->nChunksPerBlock)
3543 ((dev->internalEndBlock +
3544 1) * dev->nChunksPerBlock)) {
3545 T(YAFFS_TRACE_ALWAYS,
3546 (TSTR("Found daft chunkId %d for %d" TENDSTR),
3550 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3557 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
3560 int oldFileSize = in->variant.fileVariant.fileSize;
3561 int sizeOfPartialChunk;
3562 yaffs_Device *dev = in->myDev;
3564 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
3566 yaffs_FlushFilesChunkCache(in);
3567 yaffs_InvalidateWholeChunkCache(in);
3569 yaffs_CheckGarbageCollection(dev);
3571 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3572 return yaffs_GetFileSize(in);
3575 if (newSize == oldFileSize) {
3579 if (newSize < oldFileSize) {
3581 yaffs_PruneResizedChunks(in, newSize);
3583 if (sizeOfPartialChunk != 0) {
3584 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
3585 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3587 /* Got to read and rewrite the last chunk with its new size and zero pad */
3588 yaffs_ReadChunkDataFromObject(in, lastChunk,
3591 memset(localBuffer + sizeOfPartialChunk, 0,
3592 dev->nBytesPerChunk - sizeOfPartialChunk);
3594 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
3595 sizeOfPartialChunk, 1);
3597 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3600 in->variant.fileVariant.fileSize = newSize;
3602 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
3604 /* Write a new object header.
3605 * show we've shrunk the file, if need be
3606 * Do this only if the file is not in the deleted directories.
3608 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3609 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
3610 yaffs_UpdateObjectHeader(in, NULL, 0,
3611 (newSize < oldFileSize) ? 1 : 0, 0);
3617 loff_t yaffs_GetFileSize(yaffs_Object * obj)
3619 obj = yaffs_GetEquivalentObject(obj);
3621 switch (obj->variantType) {
3622 case YAFFS_OBJECT_TYPE_FILE:
3623 return obj->variant.fileVariant.fileSize;
3624 case YAFFS_OBJECT_TYPE_SYMLINK:
3625 return yaffs_strlen(obj->variant.symLinkVariant.alias);
3633 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
3637 yaffs_FlushFilesChunkCache(in);
3639 #ifdef CONFIG_YAFFS_WINCE
3640 yfsd_WinFileTimeNow(in->win_mtime);
3643 in->yst_mtime = Y_CURRENT_TIME;
3649 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
3650 0) ? YAFFS_OK : YAFFS_FAIL;
3659 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
3662 /* First off, invalidate the file's data in the cache, without flushing. */
3663 yaffs_InvalidateWholeChunkCache(in);
3665 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3666 /* Move to the unlinked directory so we have a record that it was deleted. */
3667 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
3671 yaffs_RemoveObjectFromDirectory(in);
3672 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
3675 yaffs_FreeObject(in);
3680 /* yaffs_DeleteFile deletes the whole file data
3681 * and the inode associated with the file.
3682 * It does not delete the links associated with the file.
3684 static int yaffs_UnlinkFile(yaffs_Object * in)
3688 int immediateDeletion = 0;
3693 immediateDeletion = 1;
3697 if (in->inUse <= 0) {
3698 immediateDeletion = 1;
3702 if (immediateDeletion) {
3704 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3706 T(YAFFS_TRACE_TRACING,
3707 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3710 in->myDev->nDeletedFiles++;
3711 if (0 && in->myDev->isYaffs2) {
3712 yaffs_ResizeFile(in, 0);
3714 yaffs_SoftDeleteFile(in);
3717 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3725 int yaffs_DeleteFile(yaffs_Object * in)
3727 int retVal = YAFFS_OK;
3729 if (in->nDataChunks > 0) {
3730 /* Use soft deletion if there is data in the file */
3731 if (!in->unlinked) {
3732 retVal = yaffs_UnlinkFile(in);
3734 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3736 in->myDev->nDeletedFiles++;
3737 yaffs_SoftDeleteFile(in);
3739 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3741 /* The file has no data chunks so we toss it immediately */
3742 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3743 in->variant.fileVariant.top = NULL;
3744 yaffs_DoGenericObjectDeletion(in);
3750 static int yaffs_DeleteDirectory(yaffs_Object * in)
3752 /* First check that the directory is empty. */
3753 if (list_empty(&in->variant.directoryVariant.children)) {
3754 return yaffs_DoGenericObjectDeletion(in);
3761 static int yaffs_DeleteSymLink(yaffs_Object * in)
3763 YFREE(in->variant.symLinkVariant.alias);
3765 return yaffs_DoGenericObjectDeletion(in);
3768 static int yaffs_DeleteHardLink(yaffs_Object * in)
3770 /* remove this hardlink from the list assocaited with the equivalent
3773 list_del(&in->hardLinks);
3774 return yaffs_DoGenericObjectDeletion(in);
3777 static void yaffs_DestroyObject(yaffs_Object * obj)
3779 switch (obj->variantType) {
3780 case YAFFS_OBJECT_TYPE_FILE:
3781 yaffs_DeleteFile(obj);
3783 case YAFFS_OBJECT_TYPE_DIRECTORY:
3784 yaffs_DeleteDirectory(obj);
3786 case YAFFS_OBJECT_TYPE_SYMLINK:
3787 yaffs_DeleteSymLink(obj);
3789 case YAFFS_OBJECT_TYPE_HARDLINK:
3790 yaffs_DeleteHardLink(obj);
3792 case YAFFS_OBJECT_TYPE_SPECIAL:
3793 yaffs_DoGenericObjectDeletion(obj);
3795 case YAFFS_OBJECT_TYPE_UNKNOWN:
3796 break; /* should not happen. */
3800 static int yaffs_UnlinkWorker(yaffs_Object * obj)
3803 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3804 return yaffs_DeleteHardLink(obj);
3805 } else if (!list_empty(&obj->hardLinks)) {
3806 /* Curve ball: We're unlinking an object that has a hardlink.
3808 * This problem arises because we are not strictly following
3809 * The Linux link/inode model.
3811 * We can't really delete the object.
3812 * Instead, we do the following:
3813 * - Select a hardlink.
3814 * - Unhook it from the hard links
3815 * - Unhook it from its parent directory (so that the rename can work)
3816 * - Rename the object to the hardlink's name.
3817 * - Delete the hardlink
3822 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3824 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
3826 list_del_init(&hl->hardLinks);
3827 list_del_init(&hl->siblings);
3829 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3831 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
3833 if (retVal == YAFFS_OK) {
3834 retVal = yaffs_DoGenericObjectDeletion(hl);