2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2010 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.
14 #include "yaffs_trace.h"
16 #include "yaffsinterface.h"
17 #include "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
21 #include "yaffs_tagscompat.h"
23 #include "yaffs_nand.h"
25 #include "yaffs_yaffs1.h"
26 #include "yaffs_yaffs2.h"
27 #include "yaffs_bitmap.h"
28 #include "yaffs_verify.h"
30 #include "yaffs_nand.h"
31 #include "yaffs_packedtags2.h"
33 #include "yaffs_nameval.h"
34 #include "yaffs_allocator.h"
36 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
37 #define YAFFS_GC_GOOD_ENOUGH 2
38 #define YAFFS_GC_PASSIVE_THRESHOLD 4
40 #include "yaffs_ecc.h"
44 /* Robustification (if it ever comes about...) */
45 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
46 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
48 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
50 const yaffs_ExtendedTags *tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
52 const yaffs_ExtendedTags *tags);
54 /* Other local prototypes */
55 static void yaffs_UpdateParent(yaffs_Object *obj);
56 static int yaffs_UnlinkObject(yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
61 yaffs_ExtendedTags *tags,
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66 yaffs_ObjectType type);
69 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
75 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
78 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
81 static int yaffs_UnlinkWorker(yaffs_Object *obj);
83 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
86 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
87 yaffs_BlockInfo **blockUsedPtr);
89 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
91 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
92 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
94 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
95 yaffs_ExtendedTags *tags);
97 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
100 yaffs_ExtendedTags *tags);
102 /* Function to calculate chunk and offset */
104 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
110 chunk = (__u32)(addr >> dev->chunkShift);
112 if (dev->chunkDiv == 1) {
113 /* easy power of 2 case */
114 offset = (__u32)(addr & dev->chunkMask);
116 /* Non power-of-2 case */
120 chunk /= dev->chunkDiv;
122 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
123 offset = (__u32)(addr - chunkBase);
130 /* Function to return the number of shifts for a power of 2 greater than or
131 * equal to the given number
132 * Note we don't try to cater for all possible numbers and this does not have to
133 * be hellishly efficient.
136 static __u32 ShiftsGE(__u32 x)
141 nShifts = extraBits = 0;
156 /* Function to return the number of shifts to get a 1 in bit 0
159 static __u32 Shifts(__u32 x)
179 * Temporary buffer manipulations.
182 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
185 __u8 *buf = (__u8 *)1;
187 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
189 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
190 dev->tempBuffer[i].line = 0; /* not in use */
191 dev->tempBuffer[i].buffer = buf =
192 YMALLOC_DMA(dev->param.totalBytesPerChunk);
195 return buf ? YAFFS_OK : YAFFS_FAIL;
198 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
203 if (dev->tempInUse > dev->maxTemp)
204 dev->maxTemp = dev->tempInUse;
206 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
207 if (dev->tempBuffer[i].line == 0) {
208 dev->tempBuffer[i].line = lineNo;
209 if ((i + 1) > dev->maxTemp) {
210 dev->maxTemp = i + 1;
211 for (j = 0; j <= i; j++)
212 dev->tempBuffer[j].maxLine =
213 dev->tempBuffer[j].line;
216 return dev->tempBuffer[i].buffer;
220 T(YAFFS_TRACE_BUFFERS,
221 (TSTR("Out of temp buffers at line %d, other held by lines:"),
223 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
224 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
226 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
229 * If we got here then we have to allocate an unmanaged one
233 dev->unmanagedTempAllocations++;
234 return YMALLOC(dev->nDataBytesPerChunk);
238 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
245 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
246 if (dev->tempBuffer[i].buffer == buffer) {
247 dev->tempBuffer[i].line = 0;
253 /* assume it is an unmanaged one. */
254 T(YAFFS_TRACE_BUFFERS,
255 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
258 dev->unmanagedTempDeallocations++;
264 * Determine if we have a managed buffer.
266 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
270 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
271 if (dev->tempBuffer[i].buffer == buffer)
275 for (i = 0; i < dev->param.nShortOpCaches; i++) {
276 if (dev->srCache[i].data == buffer)
280 if (buffer == dev->checkpointBuffer)
283 T(YAFFS_TRACE_ALWAYS,
284 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
296 * Simple hash function. Needs to have a reasonable spread
299 static Y_INLINE int yaffs_HashFunction(int n)
302 return n % YAFFS_NOBJECT_BUCKETS;
306 * Access functions to useful fake objects.
307 * Note that root might have a presence in NAND if permissions are set.
310 yaffs_Object *yaffs_Root(yaffs_Device *dev)
315 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
317 return dev->lostNFoundDir;
322 * Erased NAND checking functions
325 int yaffs_CheckFF(__u8 *buffer, int nBytes)
327 /* Horrible, slow implementation */
336 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
339 int retval = YAFFS_OK;
340 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
341 yaffs_ExtendedTags tags;
344 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
346 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
349 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
350 T(YAFFS_TRACE_NANDACCESS,
351 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
355 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
362 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
365 yaffs_ExtendedTags *tags)
367 int retval = YAFFS_OK;
368 yaffs_ExtendedTags tempTags;
369 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
372 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
373 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
374 tempTags.objectId != tags->objectId ||
375 tempTags.chunkId != tags->chunkId ||
376 tempTags.byteCount != tags->byteCount)
379 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
384 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
386 yaffs_ExtendedTags *tags,
393 yaffs2_InvalidateCheckpoint(dev);
396 yaffs_BlockInfo *bi = 0;
399 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
405 /* First check this chunk is erased, if it needs
406 * checking. The checking policy (unless forced
407 * always on) is as follows:
409 * Check the first page we try to write in a block.
410 * If the check passes then we don't need to check any
411 * more. If the check fails, we check again...
412 * If the block has been erased, we don't need to check.
414 * However, if the block has been prioritised for gc,
415 * then we think there might be something odd about
416 * this block and stop using it.
418 * Rationale: We should only ever see chunks that have
419 * not been erased if there was a partially written
420 * chunk due to power loss. This checking policy should
421 * catch that case with very few checks and thus save a
422 * lot of checks that are most likely not needed.
425 * If an erase check fails or the write fails we skip the
429 /* let's give it a try */
432 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
433 bi->skipErasedCheck = 0;
435 if (!bi->skipErasedCheck) {
436 erasedOk = yaffs_CheckChunkErased(dev, chunk);
437 if (erasedOk != YAFFS_OK) {
439 (TSTR("**>> yaffs chunk %d was not erased"
442 /* If not erased, delete this one,
443 * skip rest of block and
444 * try another chunk */
445 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
446 yaffs_SkipRestOfBlock(dev);
451 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
454 if(!bi->skipErasedCheck)
455 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
457 if (writeOk != YAFFS_OK) {
458 /* Clean up aborted write, skip to next block and
459 * try another chunk */
460 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
464 bi->skipErasedCheck = 1;
466 /* Copy the data into the robustification buffer */
467 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
469 } while (writeOk != YAFFS_OK &&
470 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
477 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
480 dev->nRetriedWrites += (attempts - 1);
489 * Block retiring for handling a broken block.
492 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
494 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
496 yaffs2_InvalidateCheckpoint(dev);
498 yaffs2_ClearOldestDirtySequence(dev,bi);
500 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
501 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
502 T(YAFFS_TRACE_ALWAYS, (TSTR(
503 "yaffs: Failed to mark bad and erase block %d"
504 TENDSTR), blockInNAND));
506 yaffs_ExtendedTags tags;
507 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
509 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
511 memset(buffer, 0xff, dev->nDataBytesPerChunk);
512 yaffs_InitialiseTags(&tags);
513 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
514 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
515 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
516 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
517 TCONT("write bad block marker to block %d")
518 TENDSTR), blockInNAND));
520 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
524 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
525 bi->gcPrioritise = 0;
526 bi->needsRetiring = 0;
528 dev->nRetiredBlocks++;
532 * Functions for robustisizing TODO
536 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
538 const yaffs_ExtendedTags *tags)
541 chunkInNAND=chunkInNAND;
546 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
547 const yaffs_ExtendedTags *tags)
550 chunkInNAND=chunkInNAND;
554 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
556 if (!bi->gcPrioritise) {
557 bi->gcPrioritise = 1;
558 dev->hasPendingPrioritisedGCs = 1;
559 bi->chunkErrorStrikes++;
561 if (bi->chunkErrorStrikes > 3) {
562 bi->needsRetiring = 1; /* Too many stikes, so retire this */
563 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
569 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
572 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
573 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
575 yaffs_HandleChunkError(dev, bi);
578 /* Was an actual write failure, so mark the block for retirement */
579 bi->needsRetiring = 1;
580 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
581 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
584 /* Delete the chunk */
585 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
586 yaffs_SkipRestOfBlock(dev);
590 /*---------------- Name handling functions ------------*/
592 static __u16 yaffs_CalcNameSum(const YCHAR *name)
597 const YUCHAR *bname = (const YUCHAR *) name;
599 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
601 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
602 sum += yaffs_toupper(*bname) * i;
613 void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
615 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
616 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
617 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
618 yaffs_strcpy(obj->shortName, name);
620 obj->shortName[0] = _Y('\0');
622 obj->sum = yaffs_CalcNameSum(name);
625 /*-------------------- TNODES -------------------
627 * List of spare tnodes
628 * The list is hooked together using the first pointer
633 yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
635 yaffs_Tnode *tn = yaffs_AllocateRawTnode(dev);
637 memset(tn, 0, dev->tnodeSize);
641 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
646 /* FreeTnode frees up a tnode and puts it back on the free list */
647 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
649 yaffs_FreeRawTnode(dev,tn);
651 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
654 static void yaffs_DeinitialiseTnodesAndObjects(yaffs_Device *dev)
656 yaffs_DeinitialiseRawTnodesAndObjects(dev);
662 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
665 __u32 *map = (__u32 *)tn;
671 pos &= YAFFS_TNODES_LEVEL0_MASK;
672 val >>= dev->chunkGroupBits;
674 bitInMap = pos * dev->tnodeWidth;
675 wordInMap = bitInMap / 32;
676 bitInWord = bitInMap & (32 - 1);
678 mask = dev->tnodeMask << bitInWord;
680 map[wordInMap] &= ~mask;
681 map[wordInMap] |= (mask & (val << bitInWord));
683 if (dev->tnodeWidth > (32 - bitInWord)) {
684 bitInWord = (32 - bitInWord);
686 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
687 map[wordInMap] &= ~mask;
688 map[wordInMap] |= (mask & (val >> bitInWord));
692 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
695 __u32 *map = (__u32 *)tn;
701 pos &= YAFFS_TNODES_LEVEL0_MASK;
703 bitInMap = pos * dev->tnodeWidth;
704 wordInMap = bitInMap / 32;
705 bitInWord = bitInMap & (32 - 1);
707 val = map[wordInMap] >> bitInWord;
709 if (dev->tnodeWidth > (32 - bitInWord)) {
710 bitInWord = (32 - bitInWord);
712 val |= (map[wordInMap] << bitInWord);
715 val &= dev->tnodeMask;
716 val <<= dev->chunkGroupBits;
721 /* ------------------- End of individual tnode manipulation -----------------*/
723 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
724 * The look up tree is represented by the top tnode and the number of topLevel
725 * in the tree. 0 means only the level 0 tnode is in the tree.
728 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
729 yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
730 yaffs_FileStructure *fStruct,
733 yaffs_Tnode *tn = fStruct->top;
735 int requiredTallness;
736 int level = fStruct->topLevel;
740 /* Check sane level and chunk Id */
741 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
744 if (chunkId > YAFFS_MAX_CHUNK_ID)
747 /* First check we're tall enough (ie enough topLevel) */
749 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
750 requiredTallness = 0;
752 i >>= YAFFS_TNODES_INTERNAL_BITS;
756 if (requiredTallness > fStruct->topLevel)
757 return NULL; /* Not tall enough, so we can't find it */
759 /* Traverse down to level 0 */
760 while (level > 0 && tn) {
761 tn = tn->internal[(chunkId >>
762 (YAFFS_TNODES_LEVEL0_BITS +
764 YAFFS_TNODES_INTERNAL_BITS)) &
765 YAFFS_TNODES_INTERNAL_MASK];
772 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
773 * This happens in two steps:
774 * 1. If the tree isn't tall enough, then make it taller.
775 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
777 * Used when modifying the tree.
779 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
780 * be plugged into the ttree.
783 yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
784 yaffs_FileStructure *fStruct,
786 yaffs_Tnode *passedTn)
788 int requiredTallness;
796 /* Check sane level and page Id */
797 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
800 if (chunkId > YAFFS_MAX_CHUNK_ID)
803 /* First check we're tall enough (ie enough topLevel) */
805 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
806 requiredTallness = 0;
808 x >>= YAFFS_TNODES_INTERNAL_BITS;
813 if (requiredTallness > fStruct->topLevel) {
814 /* Not tall enough, gotta make the tree taller */
815 for (i = fStruct->topLevel; i < requiredTallness; i++) {
817 tn = yaffs_GetTnode(dev);
820 tn->internal[0] = fStruct->top;
825 (TSTR("yaffs: no more tnodes" TENDSTR)));
831 /* Traverse down to level 0, adding anything we need */
833 l = fStruct->topLevel;
837 while (l > 0 && tn) {
839 (YAFFS_TNODES_LEVEL0_BITS +
840 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
841 YAFFS_TNODES_INTERNAL_MASK;
844 if ((l > 1) && !tn->internal[x]) {
845 /* Add missing non-level-zero tnode */
846 tn->internal[x] = yaffs_GetTnode(dev);
850 /* Looking from level 1 at level 0 */
852 /* If we already have one, then release it.*/
854 yaffs_FreeTnode(dev, tn->internal[x]);
855 tn->internal[x] = passedTn;
857 } else if (!tn->internal[x]) {
858 /* Don't have one, none passed in */
859 tn->internal[x] = yaffs_GetTnode(dev);
865 tn = tn->internal[x];
871 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
872 yaffs_FreeTnode(dev, passedTn);
879 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
880 yaffs_ExtendedTags *tags, int objectId,
885 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
886 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
887 theChunk % dev->param.nChunksPerBlock)) {
889 if(dev->chunkGroupSize == 1)
892 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
894 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
906 /* Experimental code not being used yet. Might speed up file deletion */
907 /* DeleteWorker scans backwards through the tnode tree and deletes all the
908 * chunks and tnodes in the file.
909 * Returns 1 if the tree was deleted.
910 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
913 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
914 int chunkOffset, int *limit)
919 yaffs_ExtendedTags tags;
921 yaffs_Device *dev = in->myDev;
927 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
929 if (tn->internal[i]) {
930 if (limit && (*limit) < 0) {
934 yaffs_DeleteWorker(in,
942 YAFFS_TNODES_INTERNAL_BITS)
950 tn->internal[i] = NULL;
954 return (allDone) ? 1 : 0;
955 } else if (level == 0) {
958 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
960 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
963 chunkInInode = (chunkOffset <<
964 YAFFS_TNODES_LEVEL0_BITS) + i;
967 yaffs_FindChunkInGroup(dev,
973 if (foundChunk > 0) {
974 yaffs_DeleteChunk(dev,
986 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
990 return (i < 0) ? 1 : 0;
1002 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1004 yaffs_BlockInfo *theBlock;
1007 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1009 blockNo = chunk / dev->param.nChunksPerBlock;
1010 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1012 theBlock->softDeletions++;
1014 yaffs2_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1018 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1019 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1021 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1024 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1025 __u32 level, int chunkOffset)
1030 yaffs_Device *dev = in->myDev;
1035 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1037 if (tn->internal[i]) {
1039 yaffs_SoftDeleteWorker(in,
1045 YAFFS_TNODES_INTERNAL_BITS)
1048 yaffs_FreeTnode(dev,
1051 tn->internal[i] = NULL;
1053 /* Hoosterman... how could this happen? */
1057 return (allDone) ? 1 : 0;
1058 } else if (level == 0) {
1060 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1061 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1063 /* Note this does not find the real chunk, only the chunk group.
1064 * We make an assumption that a chunk group is not larger than
1067 yaffs_SoftDeleteChunk(dev, theChunk);
1068 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1082 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1085 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1086 if (obj->nDataChunks <= 0) {
1087 /* Empty file with no duplicate object headers, just delete it immediately */
1088 yaffs_FreeTnode(obj->myDev,
1089 obj->variant.fileVariant.top);
1090 obj->variant.fileVariant.top = NULL;
1091 T(YAFFS_TRACE_TRACING,
1092 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1094 yaffs_DoGenericObjectDeletion(obj);
1096 yaffs_SoftDeleteWorker(obj,
1097 obj->variant.fileVariant.top,
1098 obj->variant.fileVariant.
1100 obj->softDeleted = 1;
1105 /* Pruning removes any part of the file structure tree that is beyond the
1106 * bounds of the file (ie that does not point to chunks).
1108 * A file should only get pruned when its size is reduced.
1110 * Before pruning, the chunks must be pulled from the tree and the
1111 * level 0 tnode entries must be zeroed out.
1112 * Could also use this for file deletion, but that's probably better handled
1113 * by a special case.
1115 * This function is recursive. For levels > 0 the function is called again on
1116 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1117 * If there is no data in a subtree then it is pruned.
1120 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1121 __u32 level, int del0)
1130 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1131 if (tn->internal[i]) {
1133 yaffs_PruneWorker(dev, tn->internal[i],
1135 (i == 0) ? del0 : 1);
1138 if (tn->internal[i])
1142 int tnodeSize_u32 = dev->tnodeSize/sizeof(__u32);
1143 __u32 *map = (__u32 *)tn;
1145 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1151 if (hasData == 0 && del0) {
1152 /* Free and return NULL */
1154 yaffs_FreeTnode(dev, tn);
1164 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1165 yaffs_FileStructure *fStruct)
1172 if (fStruct->topLevel > 0) {
1174 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1176 /* Now we have a tree with all the non-zero branches NULL but the height
1177 * is the same as it was.
1178 * Let's see if we can trim internal tnodes to shorten the tree.
1179 * We can do this if only the 0th element in the tnode is in use
1180 * (ie all the non-zero are NULL)
1183 while (fStruct->topLevel && !done) {
1187 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1188 if (tn->internal[i])
1193 fStruct->top = tn->internal[0];
1194 fStruct->topLevel--;
1195 yaffs_FreeTnode(dev, tn);
1205 /*-------------------- End of File Structure functions.-------------------*/
1208 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1209 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1211 yaffs_Object *obj = yaffs_AllocateRawObject(dev);
1216 /* Now sweeten it up... */
1218 memset(obj, 0, sizeof(yaffs_Object));
1219 obj->beingCreated = 1;
1223 obj->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1224 YINIT_LIST_HEAD(&(obj->hardLinks));
1225 YINIT_LIST_HEAD(&(obj->hashLink));
1226 YINIT_LIST_HEAD(&obj->siblings);
1229 /* Now make the directory sane */
1231 obj->parent = dev->rootDir;
1232 ylist_add(&(obj->siblings), &dev->rootDir->variant.directoryVariant.children);
1235 /* Add it to the lost and found directory.
1236 * NB Can't put root or lostNFound in lostNFound so
1237 * check if lostNFound exists first
1239 if (dev->lostNFoundDir)
1240 yaffs_AddObjectToDirectory(dev->lostNFoundDir, obj);
1242 obj->beingCreated = 0;
1245 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1250 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1255 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1257 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1258 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1259 obj->unlinkAllowed = 0; /* ... or unlink it */
1262 obj->yst_mode = mode;
1264 obj->hdrChunk = 0; /* Not a valid chunk. */
1271 static void yaffs_UnhashObject(yaffs_Object *obj)
1274 yaffs_Device *dev = obj->myDev;
1276 /* If it is still linked into the bucket list, free from the list */
1277 if (!ylist_empty(&obj->hashLink)) {
1278 ylist_del_init(&obj->hashLink);
1279 bucket = yaffs_HashFunction(obj->objectId);
1280 dev->objectBucket[bucket].count--;
1284 /* FreeObject frees up a Object and puts it back on the free list */
1285 static void yaffs_FreeObject(yaffs_Object *obj)
1287 yaffs_Device *dev = obj->myDev;
1289 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), obj, obj->myInode));
1295 if (!ylist_empty(&obj->siblings))
1300 /* We're still hooked up to a cached inode.
1301 * Don't delete now, but mark for later deletion
1303 obj->deferedFree = 1;
1307 yaffs_UnhashObject(obj);
1309 yaffs_FreeRawObject(dev,obj);
1311 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1315 void yaffs_HandleDeferedFree(yaffs_Object *obj)
1317 if (obj->deferedFree)
1318 yaffs_FreeObject(obj);
1321 static void yaffs_InitialiseTnodesAndObjects(yaffs_Device *dev)
1328 yaffs_InitialiseRawTnodesAndObjects(dev);
1330 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1331 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
1332 dev->objectBucket[i].count = 0;
1336 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1340 int lowest = 999999;
1343 /* Search for the shortest list or one that
1347 for (i = 0; i < 10 && lowest > 4; i++) {
1348 dev->bucketFinder++;
1349 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
1350 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
1351 lowest = dev->objectBucket[dev->bucketFinder].count;
1352 l = dev->bucketFinder;
1360 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1362 int bucket = yaffs_FindNiceObjectBucket(dev);
1364 /* Now find an object value that has not already been taken
1365 * by scanning the list.
1369 struct ylist_head *i;
1371 __u32 n = (__u32) bucket;
1373 /* yaffs_CheckObjectHashSanity(); */
1377 n += YAFFS_NOBJECT_BUCKETS;
1378 if (1 || dev->objectBucket[bucket].count > 0) {
1379 ylist_for_each(i, &dev->objectBucket[bucket].list) {
1380 /* If there is already one in the list */
1381 if (i && ylist_entry(i, yaffs_Object,
1382 hashLink)->objectId == n) {
1392 static void yaffs_HashObject(yaffs_Object *in)
1394 int bucket = yaffs_HashFunction(in->objectId);
1395 yaffs_Device *dev = in->myDev;
1397 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
1398 dev->objectBucket[bucket].count++;
1401 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
1403 int bucket = yaffs_HashFunction(number);
1404 struct ylist_head *i;
1407 ylist_for_each(i, &dev->objectBucket[bucket].list) {
1408 /* Look if it is in the list */
1410 in = ylist_entry(i, yaffs_Object, hashLink);
1411 if (in->objectId == number) {
1413 /* Don't tell the VFS about this one if it is defered free */
1414 if (in->deferedFree)
1425 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
1426 yaffs_ObjectType type)
1428 yaffs_Object *theObject=NULL;
1429 yaffs_Tnode *tn = NULL;
1432 number = yaffs_CreateNewObjectNumber(dev);
1434 if (type == YAFFS_OBJECT_TYPE_FILE) {
1435 tn = yaffs_GetTnode(dev);
1440 theObject = yaffs_AllocateEmptyObject(dev);
1443 yaffs_FreeTnode(dev,tn);
1449 theObject->fake = 0;
1450 theObject->renameAllowed = 1;
1451 theObject->unlinkAllowed = 1;
1452 theObject->objectId = number;
1453 yaffs_HashObject(theObject);
1454 theObject->variantType = type;
1455 #ifdef CONFIG_YAFFS_WINCE
1456 yfsd_WinFileTimeNow(theObject->win_atime);
1457 theObject->win_ctime[0] = theObject->win_mtime[0] =
1458 theObject->win_atime[0];
1459 theObject->win_ctime[1] = theObject->win_mtime[1] =
1460 theObject->win_atime[1];
1464 theObject->yst_atime = theObject->yst_mtime =
1465 theObject->yst_ctime = Y_CURRENT_TIME;
1468 case YAFFS_OBJECT_TYPE_FILE:
1469 theObject->variant.fileVariant.fileSize = 0;
1470 theObject->variant.fileVariant.scannedFileSize = 0;
1471 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1472 theObject->variant.fileVariant.topLevel = 0;
1473 theObject->variant.fileVariant.top = tn;
1475 case YAFFS_OBJECT_TYPE_DIRECTORY:
1476 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
1478 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
1481 case YAFFS_OBJECT_TYPE_SYMLINK:
1482 case YAFFS_OBJECT_TYPE_HARDLINK:
1483 case YAFFS_OBJECT_TYPE_SPECIAL:
1484 /* No action required */
1486 case YAFFS_OBJECT_TYPE_UNKNOWN:
1487 /* todo this should not happen */
1495 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
1497 yaffs_ObjectType type)
1499 yaffs_Object *theObject = NULL;
1502 theObject = yaffs_FindObjectByNumber(dev, number);
1505 theObject = yaffs_CreateNewObject(dev, number, type);
1512 YCHAR *yaffs_CloneString(const YCHAR *str)
1514 YCHAR *newStr = NULL;
1520 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
1521 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
1523 yaffs_strncpy(newStr, str,len);
1531 * Mknod (create) a new object.
1532 * equivalentObject only has meaning for a hard link;
1533 * aliasString only has meaning for a symlink.
1534 * rdev only has meaning for devices (a subset of special objects)
1537 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1538 yaffs_Object *parent,
1543 yaffs_Object *equivalentObject,
1544 const YCHAR *aliasString, __u32 rdev)
1549 yaffs_Device *dev = parent->myDev;
1551 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1552 if (yaffs_FindObjectByName(parent, name))
1555 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
1556 str = yaffs_CloneString(aliasString);
1561 in = yaffs_CreateNewObject(dev, -1, type);
1576 in->variantType = type;
1578 in->yst_mode = mode;
1580 #ifdef CONFIG_YAFFS_WINCE
1581 yfsd_WinFileTimeNow(in->win_atime);
1582 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1583 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1586 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1588 in->yst_rdev = rdev;
1592 in->nDataChunks = 0;
1594 yaffs_SetObjectName(in, name);
1597 yaffs_AddObjectToDirectory(parent, in);
1599 in->myDev = parent->myDev;
1602 case YAFFS_OBJECT_TYPE_SYMLINK:
1603 in->variant.symLinkVariant.alias = str;
1605 case YAFFS_OBJECT_TYPE_HARDLINK:
1606 in->variant.hardLinkVariant.equivalentObject =
1608 in->variant.hardLinkVariant.equivalentObjectId =
1609 equivalentObject->objectId;
1610 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
1612 case YAFFS_OBJECT_TYPE_FILE:
1613 case YAFFS_OBJECT_TYPE_DIRECTORY:
1614 case YAFFS_OBJECT_TYPE_SPECIAL:
1615 case YAFFS_OBJECT_TYPE_UNKNOWN:
1620 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0, NULL) < 0) {
1621 /* Could not create the object header, fail the creation */
1622 yaffs_DeleteObject(in);
1626 yaffs_UpdateParent(parent);
1632 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
1633 __u32 mode, __u32 uid, __u32 gid)
1635 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1636 uid, gid, NULL, NULL, 0);
1639 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
1640 __u32 mode, __u32 uid, __u32 gid)
1642 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1643 mode, uid, gid, NULL, NULL, 0);
1646 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
1647 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1649 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1650 uid, gid, NULL, NULL, rdev);
1653 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
1654 __u32 mode, __u32 uid, __u32 gid,
1657 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1658 uid, gid, NULL, alias, 0);
1661 /* yaffs_Link returns the object id of the equivalent object.*/
1662 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
1663 yaffs_Object *equivalentObject)
1665 /* Get the real object in case we were fed a hard link as an equivalent object */
1666 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1668 if (yaffs_MknodObject
1669 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1670 equivalentObject, NULL, 0)) {
1671 return equivalentObject;
1678 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
1679 const YCHAR *newName, int force, int shadows)
1684 yaffs_Object *existingTarget;
1687 newDir = obj->parent; /* use the old directory */
1689 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1690 T(YAFFS_TRACE_ALWAYS,
1692 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
1697 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1698 if (obj->myDev->param.isYaffs2)
1699 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1701 unlinkOp = (newDir == obj->myDev->unlinkedDir
1702 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1704 deleteOp = (newDir == obj->myDev->deletedDir);
1706 existingTarget = yaffs_FindObjectByName(newDir, newName);
1708 /* If the object is a file going into the unlinked directory,
1709 * then it is OK to just stuff it in since duplicate names are allowed.
1710 * else only proceed if the new name does not exist and if we're putting
1711 * it into a directory.
1718 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1719 yaffs_SetObjectName(obj, newName);
1722 yaffs_AddObjectToDirectory(newDir, obj);
1727 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1728 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows, NULL) >= 0)
1735 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
1736 yaffs_Object *newDir, const YCHAR *newName)
1738 yaffs_Object *obj = NULL;
1739 yaffs_Object *existingTarget = NULL;
1745 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1747 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1750 dev = oldDir->myDev;
1752 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1753 /* Special case for case insemsitive systems (eg. WinCE).
1754 * While look-up is case insensitive, the name isn't.
1755 * Therefore we might want to change x.txt to X.txt
1757 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
1761 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
1765 obj = yaffs_FindObjectByName(oldDir, oldName);
1767 if (obj && obj->renameAllowed) {
1769 /* Now do the handling for an existing target, if there is one */
1771 existingTarget = yaffs_FindObjectByName(newDir, newName);
1772 if (existingTarget &&
1773 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1774 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
1775 /* There is a target that is a non-empty directory, so we fail */
1776 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1777 } else if (existingTarget && existingTarget != obj) {
1778 /* Nuke the target first, using shadowing,
1779 * but only if it isn't the same object.
1781 * Note we must disable gc otherwise it can mess up the shadowing.
1785 yaffs_ChangeObjectName(obj, newDir, newName, force,
1786 existingTarget->objectId);
1787 existingTarget->isShadowed = 1;
1788 yaffs_UnlinkObject(existingTarget);
1792 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1794 yaffs_UpdateParent(oldDir);
1795 if(newDir != oldDir)
1796 yaffs_UpdateParent(newDir);
1803 /*------------------------- Block Management and Page Allocation ----------------*/
1805 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
1807 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1809 dev->blockInfo = NULL;
1810 dev->chunkBits = NULL;
1812 dev->allocationBlock = -1; /* force it to get a new one */
1814 /* If the first allocation strategy fails, thry the alternate one */
1815 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1816 if (!dev->blockInfo) {
1817 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1818 dev->blockInfoAlt = 1;
1820 dev->blockInfoAlt = 0;
1822 if (dev->blockInfo) {
1823 /* Set up dynamic blockinfo stuff. */
1824 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
1825 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1826 if (!dev->chunkBits) {
1827 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1828 dev->chunkBitsAlt = 1;
1830 dev->chunkBitsAlt = 0;
1833 if (dev->blockInfo && dev->chunkBits) {
1834 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1835 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1842 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1844 if (dev->blockInfoAlt && dev->blockInfo)
1845 YFREE_ALT(dev->blockInfo);
1846 else if (dev->blockInfo)
1847 YFREE(dev->blockInfo);
1849 dev->blockInfoAlt = 0;
1851 dev->blockInfo = NULL;
1853 if (dev->chunkBitsAlt && dev->chunkBits)
1854 YFREE_ALT(dev->chunkBits);
1855 else if (dev->chunkBits)
1856 YFREE(dev->chunkBits);
1857 dev->chunkBitsAlt = 0;
1858 dev->chunkBits = NULL;
1861 void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
1863 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1867 /* If the block is still healthy erase it and mark as clean.
1868 * If the block has had a data failure, then retire it.
1871 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
1872 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
1873 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
1875 yaffs2_ClearOldestDirtySequence(dev,bi);
1877 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1879 /* If this is the block being garbage collected then stop gc'ing this block */
1880 if(blockNo == dev->gcBlock)
1883 /* If this block is currently the best candidate for gc then drop as a candidate */
1884 if(blockNo == dev->gcDirtiest){
1885 dev->gcDirtiest = 0;
1886 dev->gcPagesInUse = 0;
1889 if (!bi->needsRetiring) {
1890 yaffs2_InvalidateCheckpoint(dev);
1891 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1893 dev->nErasureFailures++;
1894 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1895 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1900 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
1902 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
1903 if (!yaffs_CheckChunkErased
1904 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
1905 T(YAFFS_TRACE_ERROR,
1907 (">>Block %d erasure supposedly OK, but chunk %d not erased"
1908 TENDSTR), blockNo, i));
1914 /* Clean it up... */
1915 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1916 bi->sequenceNumber = 0;
1917 dev->nErasedBlocks++;
1919 bi->softDeletions = 0;
1920 bi->hasShrinkHeader = 0;
1921 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
1922 bi->gcPrioritise = 0;
1923 yaffs_ClearChunkBits(dev, blockNo);
1925 T(YAFFS_TRACE_ERASE,
1926 (TSTR("Erased block %d" TENDSTR), blockNo));
1928 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
1930 yaffs_RetireBlock(dev, blockNo);
1931 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1932 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
1936 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
1940 yaffs_BlockInfo *bi;
1942 if (dev->nErasedBlocks < 1) {
1943 /* Hoosterman we've got a problem.
1944 * Can't get space to gc
1946 T(YAFFS_TRACE_ERROR,
1947 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
1952 /* Find an empty block. */
1954 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1955 dev->allocationBlockFinder++;
1956 if (dev->allocationBlockFinder < dev->internalStartBlock
1957 || dev->allocationBlockFinder > dev->internalEndBlock) {
1958 dev->allocationBlockFinder = dev->internalStartBlock;
1961 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
1963 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
1964 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1965 dev->sequenceNumber++;
1966 bi->sequenceNumber = dev->sequenceNumber;
1967 dev->nErasedBlocks--;
1968 T(YAFFS_TRACE_ALLOCATE,
1969 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
1970 dev->allocationBlockFinder, dev->sequenceNumber,
1971 dev->nErasedBlocks));
1972 return dev->allocationBlockFinder;
1976 T(YAFFS_TRACE_ALWAYS,
1978 ("yaffs tragedy: no more erased blocks, but there should have been %d"
1979 TENDSTR), dev->nErasedBlocks));
1986 * Check if there's space to allocate...
1987 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
1989 int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
1992 int reservedBlocks = dev->param.nReservedBlocks;
1993 int checkpointBlocks;
1995 checkpointBlocks = yaffs2_CalcCheckpointBlocksRequired(dev);
1997 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
1999 return (dev->nFreeChunks > (reservedChunks + nChunks));
2002 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2003 yaffs_BlockInfo **blockUsedPtr)
2006 yaffs_BlockInfo *bi;
2008 if (dev->allocationBlock < 0) {
2009 /* Get next block to allocate off */
2010 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2011 dev->allocationPage = 0;
2014 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
2015 /* Not enough space to allocate unless we're allowed to use the reserve. */
2019 if (dev->nErasedBlocks < dev->param.nReservedBlocks
2020 && dev->allocationPage == 0) {
2021 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2024 /* Next page please.... */
2025 if (dev->allocationBlock >= 0) {
2026 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2028 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
2029 dev->allocationPage;
2031 yaffs_SetChunkBit(dev, dev->allocationBlock,
2032 dev->allocationPage);
2034 dev->allocationPage++;
2038 /* If the block is full set the state to full */
2039 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
2040 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2041 dev->allocationBlock = -1;
2050 T(YAFFS_TRACE_ERROR,
2051 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2056 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2060 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2062 if (dev->allocationBlock > 0)
2063 n += (dev->param.nChunksPerBlock - dev->allocationPage);
2070 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
2071 * if we don't want to write to it.
2073 void yaffs_SkipRestOfBlock(yaffs_Device *dev)
2075 if(dev->allocationBlock > 0){
2076 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2077 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
2078 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2079 dev->allocationBlock = -1;
2085 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2091 int retVal = YAFFS_OK;
2094 int isCheckpointBlock;
2098 int chunksBefore = yaffs_GetErasedChunks(dev);
2101 yaffs_ExtendedTags tags;
2103 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2105 yaffs_Object *object;
2107 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2110 T(YAFFS_TRACE_TRACING,
2111 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2114 bi->hasShrinkHeader,
2117 /*yaffs_VerifyFreeChunks(dev); */
2119 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
2120 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2122 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2126 if (isCheckpointBlock ||
2127 !yaffs_StillSomeChunkBits(dev, block)) {
2128 T(YAFFS_TRACE_TRACING,
2130 ("Collecting block %d that has no chunks in use" TENDSTR),
2132 yaffs_BlockBecameDirty(dev, block);
2135 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2137 yaffs_VerifyBlock(dev, bi, block);
2139 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
2140 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
2142 for (/* init already done */;
2143 retVal == YAFFS_OK &&
2144 dev->gcChunk < dev->param.nChunksPerBlock &&
2145 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
2147 dev->gcChunk++, oldChunk++) {
2148 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
2150 /* This page is in use and might need to be copied off */
2156 yaffs_InitialiseTags(&tags);
2158 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2162 yaffs_FindObjectByNumber(dev,
2165 T(YAFFS_TRACE_GC_DETAIL,
2167 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
2168 dev->gcChunk, tags.objectId, tags.chunkId,
2171 if (object && !yaffs_SkipVerification(dev)) {
2172 if (tags.chunkId == 0)
2173 matchingChunk = object->hdrChunk;
2174 else if (object->softDeleted)
2175 matchingChunk = oldChunk; /* Defeat the test */
2177 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
2179 if (oldChunk != matchingChunk)
2180 T(YAFFS_TRACE_ERROR,
2181 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2182 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
2187 T(YAFFS_TRACE_ERROR,
2189 ("page %d in gc has no object: %d %d %d "
2191 tags.objectId, tags.chunkId, tags.byteCount));
2196 object->softDeleted &&
2197 tags.chunkId != 0) {
2198 /* Data chunk in a soft deleted file, throw it away
2199 * It's a soft deleted data chunk,
2200 * No need to copy this, just forget about it and
2201 * fix up the object.
2204 /* Free chunks already includes softdeleted chunks.
2205 * How ever this chunk is going to soon be really deleted
2206 * which will increment free chunks.
2207 * We have to decrement free chunks so this works out properly.
2211 object->nDataChunks--;
2213 if (object->nDataChunks <= 0) {
2214 /* remeber to clean up the object */
2215 dev->gcCleanupList[cleanups] =
2221 /* Todo object && object->deleted && object->nDataChunks == 0 */
2222 /* Deleted object header with no data chunks.
2223 * Can be discarded and the file deleted.
2225 object->hdrChunk = 0;
2226 yaffs_FreeTnode(object->myDev,
2229 object->variant.fileVariant.top = NULL;
2230 yaffs_DoGenericObjectDeletion(object);
2232 } else if (object) {
2233 /* It's either a data chunk in a live file or
2234 * an ObjectHeader, so we're interested in it.
2235 * NB Need to keep the ObjectHeaders of deleted files
2236 * until the whole file has been deleted off
2238 tags.serialNumber++;
2242 if (tags.chunkId == 0) {
2243 /* It is an object Id,
2244 * We need to nuke the shrinkheader flags first
2245 * Also need to clean up shadowing.
2246 * We no longer want the shrinkHeader flag since its work is done
2247 * and if it is left in place it will mess up scanning.
2250 yaffs_ObjectHeader *oh;
2251 oh = (yaffs_ObjectHeader *)buffer;
2254 tags.extraIsShrinkHeader = 0;
2256 oh->shadowsObject = 0;
2257 oh->inbandShadowsObject = 0;
2258 tags.extraShadows = 0;
2260 /* Update file size */
2261 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
2262 oh->fileSize = object->variant.fileVariant.fileSize;
2263 tags.extraFileLength = oh->fileSize;
2266 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
2268 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
2271 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2274 retVal = YAFFS_FAIL;
2277 /* Ok, now fix up the Tnodes etc. */
2279 if (tags.chunkId == 0) {
2281 object->hdrChunk = newChunk;
2282 object->serial = tags.serialNumber;
2284 /* It's a data chunk */
2286 ok = yaffs_PutChunkIntoFile
2294 if (retVal == YAFFS_OK)
2295 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2300 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2303 /* Do any required cleanups */
2304 for (i = 0; i < cleanups; i++) {
2305 /* Time to delete the file too */
2307 yaffs_FindObjectByNumber(dev,
2308 dev->gcCleanupList[i]);
2310 yaffs_FreeTnode(dev,
2311 object->variant.fileVariant.
2313 object->variant.fileVariant.top = NULL;
2316 ("yaffs: About to finally delete object %d"
2317 TENDSTR), object->objectId));
2318 yaffs_DoGenericObjectDeletion(object);
2319 object->myDev->nDeletedFiles--;
2326 yaffs_VerifyCollectedBlock(dev, bi, block);
2330 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2332 * The gc did not complete. Set block state back to FULL
2333 * because checkpointing does not restore gc.
2335 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2337 /* The gc completed. */
2338 chunksAfter = yaffs_GetErasedChunks(dev);
2339 if (chunksBefore >= chunksAfter) {
2342 ("gc did not increase free chunks before %d after %d"
2343 TENDSTR), chunksBefore, chunksAfter));
2355 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2356 * for garbage collection.
2359 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2365 unsigned selected = 0;
2366 int prioritised = 0;
2367 int prioritisedExists = 0;
2368 yaffs_BlockInfo *bi;
2371 /* First let's see if we need to grab a prioritised block */
2372 if (dev->hasPendingPrioritisedGCs && !aggressive) {
2373 dev->gcDirtiest = 0;
2374 bi = dev->blockInfo;
2375 for (i = dev->internalStartBlock;
2376 i <= dev->internalEndBlock && !selected;
2379 if (bi->gcPrioritise) {
2380 prioritisedExists = 1;
2381 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2382 yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2391 * If there is a prioritised block and none was selected then
2392 * this happened because there is at least one old dirty block gumming
2393 * up the works. Let's gc the oldest dirty block.
2396 if(prioritisedExists &&
2398 dev->oldestDirtyBlock > 0)
2399 selected = dev->oldestDirtyBlock;
2401 if (!prioritisedExists) /* None found, so we can clear this */
2402 dev->hasPendingPrioritisedGCs = 0;
2405 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2407 * else (we're doing a leasurely gc), then we only bother to do this if the
2408 * block has only a few pages in use.
2413 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2415 threshold = dev->param.nChunksPerBlock;
2416 iterations = nBlocks;
2418 int maxThreshold = dev->param.nChunksPerBlock/2;
2419 threshold = background ?
2420 (dev->gcNotDone + 2) * 2 : 0;
2421 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
2422 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2423 if(threshold > maxThreshold)
2424 threshold = maxThreshold;
2426 iterations = nBlocks / 16 + 1;
2427 if (iterations > 100)
2433 (dev->gcDirtiest < 1 ||
2434 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
2436 dev->gcBlockFinder++;
2437 if (dev->gcBlockFinder < dev->internalStartBlock ||
2438 dev->gcBlockFinder > dev->internalEndBlock)
2439 dev->gcBlockFinder = dev->internalStartBlock;
2441 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
2443 pagesUsed = bi->pagesInUse - bi->softDeletions;
2445 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2446 pagesUsed < dev->param.nChunksPerBlock &&
2447 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
2448 yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2449 dev->gcDirtiest = dev->gcBlockFinder;
2450 dev->gcPagesInUse = pagesUsed;
2454 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
2455 selected = dev->gcDirtiest;
2459 * If nothing has been selected for a while, try selecting the oldest dirty
2460 * because that's gumming up the works.
2463 if(!selected && dev->param.isYaffs2 &&
2464 dev->gcNotDone >= ( background ? 10 : 20)){
2465 yaffs2_FindOldestDirtySequence(dev);
2466 if(dev->oldestDirtyBlock > 0) {
2467 selected = dev->oldestDirtyBlock;
2468 dev->gcDirtiest = selected;
2469 dev->oldestDirtyGCs++;
2470 bi = yaffs_GetBlockInfo(dev, selected);
2471 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
2478 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
2480 dev->param.nChunksPerBlock - dev->gcPagesInUse,
2484 dev->backgroundGCs++;
2485 dev->gcDirtiest = 0;
2486 dev->gcPagesInUse = 0;
2488 if(dev->refreshSkip > 0)
2493 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
2494 dev->gcBlockFinder, dev->gcNotDone,
2496 dev->gcDirtiest, dev->gcPagesInUse,
2497 dev->oldestDirtyBlock,
2498 background ? " bg" : ""));
2504 /* New garbage collector
2505 * If we're very low on erased blocks then we do aggressive garbage collection
2506 * otherwise we do "leasurely" garbage collection.
2507 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2508 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2510 * The idea is to help clear out space in a more spread-out manner.
2511 * Dunno if it really does anything useful.
2513 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
2516 int gcOk = YAFFS_OK;
2522 int checkpointBlockAdjust;
2524 if(dev->param.gcControl &&
2525 (dev->param.gcControl(dev) & 1) == 0)
2528 if (dev->gcDisable) {
2529 /* Bail out so we don't get recursive gc */
2533 /* This loop should pass the first time.
2534 * We'll only see looping here if the collection does not increase space.
2540 checkpointBlockAdjust = yaffs2_CalcCheckpointBlocksRequired(dev);
2542 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
2543 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2545 /* If we need a block soon then do aggressive gc.*/
2546 if (dev->nErasedBlocks < minErased)
2549 if(dev->gcSkip > 20)
2551 if(erasedChunks < dev->nFreeChunks/2 ||
2563 /* If we don't already have a block being gc'd then see if we should start another */
2565 if (dev->gcBlock < 1 && !aggressive) {
2566 dev->gcBlock = yaffs2_FindRefreshBlock(dev);
2569 if (dev->gcBlock < 1) {
2570 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
2574 if (dev->gcBlock > 0) {
2581 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2582 dev->nErasedBlocks, aggressive));
2584 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
2587 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
2590 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2591 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
2593 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
2594 (dev->gcBlock > 0) &&
2597 return aggressive ? gcOk : YAFFS_OK;
2601 * yaffs_BackgroundGarbageCollect()
2602 * Garbage collects. Intended to be called from a background thread.
2603 * Returns non-zero if at least half the free chunks are erased.
2605 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
2607 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2609 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
2611 yaffs_CheckGarbageCollection(dev, 1);
2612 return erasedChunks > dev->nFreeChunks/2;
2615 /*------------------------- TAGS --------------------------------*/
2617 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
2620 return (tags->chunkId == chunkInObject &&
2621 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2626 /*-------------------- Data file manipulation -----------------*/
2628 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
2629 yaffs_ExtendedTags *tags)
2631 /*Get the Tnode, then get the level 0 offset chunk offset */
2634 yaffs_ExtendedTags localTags;
2637 yaffs_Device *dev = in->myDev;
2640 /* Passed a NULL, so use our own tags space */
2644 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2647 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2650 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2656 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
2657 yaffs_ExtendedTags *tags)
2659 /* Get the Tnode, then get the level 0 offset chunk offset */
2662 yaffs_ExtendedTags localTags;
2664 yaffs_Device *dev = in->myDev;
2668 /* Passed a NULL, so use our own tags space */
2672 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2676 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2679 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2682 /* Delete the entry in the filestructure (if found) */
2684 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
2691 int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
2692 int chunkInNAND, int inScan)
2694 /* NB inScan is zero unless scanning.
2695 * For forward scanning, inScan is > 0;
2696 * for backward scanning inScan is < 0
2698 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
2702 yaffs_Device *dev = in->myDev;
2704 yaffs_ExtendedTags existingTags;
2705 yaffs_ExtendedTags newTags;
2706 unsigned existingSerial, newSerial;
2708 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2709 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2710 * If it is not during Scanning then something went wrong!
2713 T(YAFFS_TRACE_ERROR,
2715 ("yaffs tragedy:attempt to put data chunk into a non-file"
2720 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2724 tn = yaffs_AddOrFindLevel0Tnode(dev,
2725 &in->variant.fileVariant,
2732 /* Dummy insert, bail now */
2735 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2738 /* If we're scanning then we need to test for duplicates
2739 * NB This does not need to be efficient since it should only ever
2740 * happen when the power fails during a write, then only one
2741 * chunk should ever be affected.
2743 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2744 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2747 if (existingChunk > 0) {
2748 /* NB Right now existing chunk will not be real chunkId if the chunk group size > 1
2749 * thus we have to do a FindChunkInFile to get the real chunk id.
2751 * We have a duplicate now we need to decide which one to use:
2753 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2754 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2755 * YAFFS1: Get both sets of tags and compare serial numbers.
2759 /* Only do this for forward scanning */
2760 yaffs_ReadChunkWithTagsFromNAND(dev,
2764 /* Do a proper find */
2766 yaffs_FindChunkInFile(in, chunkInInode,
2770 if (existingChunk <= 0) {
2771 /*Hoosterman - how did this happen? */
2773 T(YAFFS_TRACE_ERROR,
2775 ("yaffs tragedy: existing chunk < 0 in scan"
2780 /* NB The deleted flags should be false, otherwise the chunks will
2781 * not be loaded during a scan
2785 newSerial = newTags.serialNumber;
2786 existingSerial = existingTags.serialNumber;
2790 (existingChunk <= 0 ||
2791 ((existingSerial + 1) & 3) == newSerial)) {
2792 /* Forward scanning.
2794 * Delete the old one and drop through to update the tnode
2796 yaffs_DeleteChunk(dev, existingChunk, 1,
2799 /* Backward scanning or we want to use the existing one
2801 * Delete the new one and return early so that the tnode isn't changed
2803 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2811 if (existingChunk == 0)
2814 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
2819 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
2822 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2824 if (chunkInNAND >= 0)
2825 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2828 T(YAFFS_TRACE_NANDACCESS,
2829 (TSTR("Chunk %d not found zero instead" TENDSTR),
2831 /* get sane (zero) data if you read a hole */
2832 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2838 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
2842 yaffs_ExtendedTags tags;
2843 yaffs_BlockInfo *bi;
2849 block = chunkId / dev->param.nChunksPerBlock;
2850 page = chunkId % dev->param.nChunksPerBlock;
2853 if (!yaffs_CheckChunkBit(dev, block, page))
2854 T(YAFFS_TRACE_VERIFY,
2855 (TSTR("Deleting invalid chunk %d"TENDSTR),
2858 bi = yaffs_GetBlockInfo(dev, block);
2860 yaffs2_UpdateOldestDirtySequence(dev, block, bi);
2862 T(YAFFS_TRACE_DELETION,
2863 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2865 if (!dev->param.isYaffs2 && markNAND &&
2866 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
2868 yaffs_InitialiseTags(&tags);
2870 tags.chunkDeleted = 1;
2872 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2873 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2875 dev->nUnmarkedDeletions++;
2878 /* Pull out of the management area.
2879 * If the whole block became dirty, this will kick off an erasure.
2881 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2882 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2883 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2884 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2887 yaffs_ClearChunkBit(dev, block, page);
2891 if (bi->pagesInUse == 0 &&
2892 !bi->hasShrinkHeader &&
2893 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2894 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2895 yaffs_BlockBecameDirty(dev, block);
2902 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
2903 const __u8 *buffer, int nBytes,
2906 /* Find old chunk Need to do this to get serial number
2907 * Write new one and patch into tree.
2908 * Invalidate old tags.
2912 yaffs_ExtendedTags prevTags;
2915 yaffs_ExtendedTags newTags;
2917 yaffs_Device *dev = in->myDev;
2919 yaffs_CheckGarbageCollection(dev,0);
2921 /* Get the previous chunk at this location in the file if it exists.
2922 * If it does not exist then put a zero into the tree. This creates
2923 * the tnode now, rather than later when it is harder to clean up.
2925 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2926 if(prevChunkId < 1 &&
2927 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
2930 /* Set up new tags */
2931 yaffs_InitialiseTags(&newTags);
2933 newTags.chunkId = chunkInInode;
2934 newTags.objectId = in->objectId;
2935 newTags.serialNumber =
2936 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
2937 newTags.byteCount = nBytes;
2939 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
2940 T(YAFFS_TRACE_ERROR,
2941 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
2947 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2950 if (newChunkId > 0) {
2951 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2953 if (prevChunkId > 0)
2954 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2956 yaffs_VerifyFileSanity(in);
2962 /* UpdateObjectHeader updates the header on NAND for an object.
2963 * If name is not NULL, then that new name is used.
2965 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
2966 int isShrink, int shadows, yaffs_XAttrMod *xmod)
2969 yaffs_BlockInfo *bi;
2971 yaffs_Device *dev = in->myDev;
2978 yaffs_ExtendedTags newTags;
2979 yaffs_ExtendedTags oldTags;
2980 YCHAR *alias = NULL;
2982 __u8 *buffer = NULL;
2983 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2985 yaffs_ObjectHeader *oh = NULL;
2987 yaffs_strcpy(oldName, _Y("silly old name"));
2991 in == dev->rootDir || /* The rootDir should also be saved */
2994 yaffs_CheckGarbageCollection(dev,0);
2995 yaffs_CheckObjectDetailsLoaded(in);
2997 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2998 oh = (yaffs_ObjectHeader *) buffer;
3000 prevChunkId = in->hdrChunk;
3002 if (prevChunkId > 0) {
3003 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3006 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3008 memcpy(oldName, oh->name, sizeof(oh->name));
3009 memset(buffer, 0xFF, sizeof(yaffs_ObjectHeader));
3011 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3013 oh->type = in->variantType;
3014 oh->yst_mode = in->yst_mode;
3015 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3017 #ifdef CONFIG_YAFFS_WINCE
3018 oh->win_atime[0] = in->win_atime[0];
3019 oh->win_ctime[0] = in->win_ctime[0];
3020 oh->win_mtime[0] = in->win_mtime[0];
3021 oh->win_atime[1] = in->win_atime[1];
3022 oh->win_ctime[1] = in->win_ctime[1];
3023 oh->win_mtime[1] = in->win_mtime[1];
3025 oh->yst_uid = in->yst_uid;
3026 oh->yst_gid = in->yst_gid;
3027 oh->yst_atime = in->yst_atime;
3028 oh->yst_mtime = in->yst_mtime;
3029 oh->yst_ctime = in->yst_ctime;
3030 oh->yst_rdev = in->yst_rdev;
3033 oh->parentObjectId = in->parent->objectId;
3035 oh->parentObjectId = 0;
3037 if (name && *name) {
3038 memset(oh->name, 0, sizeof(oh->name));
3039 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3040 } else if (prevChunkId > 0)
3041 memcpy(oh->name, oldName, sizeof(oh->name));
3043 memset(oh->name, 0, sizeof(oh->name));
3045 oh->isShrink = isShrink;
3047 switch (in->variantType) {
3048 case YAFFS_OBJECT_TYPE_UNKNOWN:
3049 /* Should not happen */
3051 case YAFFS_OBJECT_TYPE_FILE:
3053 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3054 || oh->parentObjectId ==
3055 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3056 fileVariant.fileSize;
3058 case YAFFS_OBJECT_TYPE_HARDLINK:
3059 oh->equivalentObjectId =
3060 in->variant.hardLinkVariant.equivalentObjectId;
3062 case YAFFS_OBJECT_TYPE_SPECIAL:
3065 case YAFFS_OBJECT_TYPE_DIRECTORY:
3068 case YAFFS_OBJECT_TYPE_SYMLINK:
3069 alias = in->variant.symLinkVariant.alias;
3071 alias = _Y("no alias");
3072 yaffs_strncpy(oh->alias,
3074 YAFFS_MAX_ALIAS_LENGTH);
3075 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3079 /* process any xattrib modifications */
3081 yaffs_ApplyXMod(dev, (char *)buffer, xmod);
3085 yaffs_InitialiseTags(&newTags);
3087 newTags.chunkId = 0;
3088 newTags.objectId = in->objectId;
3089 newTags.serialNumber = in->serial;
3091 /* Add extra info for file header */
3093 newTags.extraHeaderInfoAvailable = 1;
3094 newTags.extraParentObjectId = oh->parentObjectId;
3095 newTags.extraFileLength = oh->fileSize;
3096 newTags.extraIsShrinkHeader = oh->isShrink;
3097 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3098 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3099 newTags.extraObjectType = in->variantType;
3101 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3103 /* Create new chunk in NAND */
3105 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3106 (prevChunkId > 0) ? 1 : 0);
3108 if (newChunkId >= 0) {
3110 in->hdrChunk = newChunkId;
3112 if (prevChunkId > 0) {
3113 yaffs_DeleteChunk(dev, prevChunkId, 1,
3117 if (!yaffs_ObjectHasCachedWriteData(in))
3120 /* If this was a shrink, then mark the block that the chunk lives on */
3122 bi = yaffs_GetBlockInfo(in->myDev,
3123 newChunkId / in->myDev->param.nChunksPerBlock);
3124 bi->hasShrinkHeader = 1;
3129 retVal = newChunkId;
3134 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3139 /*------------------------ Short Operations Cache ----------------------------------------
3140 * In many situations where there is no high level buffering (eg WinCE) a lot of
3141 * reads might be short sequential reads, and a lot of writes may be short
3142 * sequential writes. eg. scanning/writing a jpeg file.
3143 * In these cases, a short read/write cache can provide a huge perfomance benefit
3144 * with dumb-as-a-rock code.
3145 * In Linux, the page cache provides read buffering aand the short op cache provides write
3148 * There are a limited number (~10) of cache chunks per device so that we don't
3149 * need a very intelligent search.
3152 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3154 yaffs_Device *dev = obj->myDev;
3156 yaffs_ChunkCache *cache;
3157 int nCaches = obj->myDev->param.nShortOpCaches;
3159 for (i = 0; i < nCaches; i++) {
3160 cache = &dev->srCache[i];
3161 if (cache->object == obj &&
3170 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3172 yaffs_Device *dev = obj->myDev;
3173 int lowest = -99; /* Stop compiler whining. */
3175 yaffs_ChunkCache *cache;
3176 int chunkWritten = 0;
3177 int nCaches = obj->myDev->param.nShortOpCaches;
3183 /* Find the dirty cache for this object with the lowest chunk id. */
3184 for (i = 0; i < nCaches; i++) {
3185 if (dev->srCache[i].object == obj &&
3186 dev->srCache[i].dirty) {
3188 || dev->srCache[i].chunkId <
3190 cache = &dev->srCache[i];
3191 lowest = cache->chunkId;
3196 if (cache && !cache->locked) {
3197 /* Write it out and free it up */
3200 yaffs_WriteChunkDataToObject(cache->object,
3206 cache->object = NULL;
3209 } while (cache && chunkWritten > 0);
3212 /* Hoosterman, disk full while writing cache out. */
3213 T(YAFFS_TRACE_ERROR,
3214 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3221 /*yaffs_FlushEntireDeviceCache(dev)
3226 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3229 int nCaches = dev->param.nShortOpCaches;
3232 /* Find a dirty object in the cache and flush it...
3233 * until there are no further dirty objects.
3237 for (i = 0; i < nCaches && !obj; i++) {
3238 if (dev->srCache[i].object &&
3239 dev->srCache[i].dirty)
3240 obj = dev->srCache[i].object;
3244 yaffs_FlushFilesChunkCache(obj);
3251 /* Grab us a cache chunk for use.
3252 * First look for an empty one.
3253 * Then look for the least recently used non-dirty one.
3254 * Then look for the least recently used dirty one...., flush and look again.
3256 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3260 if (dev->param.nShortOpCaches > 0) {
3261 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3262 if (!dev->srCache[i].object)
3263 return &dev->srCache[i];
3270 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3272 yaffs_ChunkCache *cache;
3273 yaffs_Object *theObj;
3278 if (dev->param.nShortOpCaches > 0) {
3279 /* Try find a non-dirty one... */
3281 cache = yaffs_GrabChunkCacheWorker(dev);
3284 /* They were all dirty, find the last recently used object and flush
3285 * its cache, then find again.
3286 * NB what's here is not very accurate, we actually flush the object
3287 * the last recently used page.
3290 /* With locking we can't assume we can use entry zero */
3297 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3298 if (dev->srCache[i].object &&
3299 !dev->srCache[i].locked &&
3300 (dev->srCache[i].lastUse < usage || !cache)) {
3301 usage = dev->srCache[i].lastUse;
3302 theObj = dev->srCache[i].object;
3303 cache = &dev->srCache[i];
3308 if (!cache || cache->dirty) {
3309 /* Flush and try again */
3310 yaffs_FlushFilesChunkCache(theObj);
3311 cache = yaffs_GrabChunkCacheWorker(dev);
3321 /* Find a cached chunk */
3322 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
3325 yaffs_Device *dev = obj->myDev;
3327 if (dev->param.nShortOpCaches > 0) {
3328 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3329 if (dev->srCache[i].object == obj &&
3330 dev->srCache[i].chunkId == chunkId) {
3333 return &dev->srCache[i];
3340 /* Mark the chunk for the least recently used algorithym */
3341 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
3345 if (dev->param.nShortOpCaches > 0) {
3346 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3347 /* Reset the cache usages */
3349 for (i = 1; i < dev->param.nShortOpCaches; i++)
3350 dev->srCache[i].lastUse = 0;
3357 cache->lastUse = dev->srLastUse;
3364 /* Invalidate a single cache page.
3365 * Do this when a whole page gets written,
3366 * ie the short cache for this page is no longer valid.
3368 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3370 if (object->myDev->param.nShortOpCaches > 0) {
3371 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3374 cache->object = NULL;
3378 /* Invalidate all the cache pages associated with this object
3379 * Do this whenever ther file is deleted or resized.
3381 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3384 yaffs_Device *dev = in->myDev;
3386 if (dev->param.nShortOpCaches > 0) {
3387 /* Invalidate it. */
3388 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3389 if (dev->srCache[i].object == in)
3390 dev->srCache[i].object = NULL;
3396 /*--------------------- File read/write ------------------------
3397 * Read and write have very similar structures.
3398 * In general the read/write has three parts to it
3399 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3400 * Some complete chunks
3401 * An incomplete chunk to end off with
3403 * Curve-balls: the first chunk might also be the last chunk.
3406 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
3415 yaffs_ChunkCache *cache;
3422 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
3423 /* start = offset % dev->nDataBytesPerChunk; */
3424 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3427 /* OK now check for the curveball where the start and end are in
3430 if ((start + n) < dev->nDataBytesPerChunk)
3433 nToCopy = dev->nDataBytesPerChunk - start;
3435 cache = yaffs_FindChunkCache(in, chunk);
3437 /* If the chunk is already in the cache or it is less than a whole chunk
3438 * or we're using inband tags then use the cache (if there is caching)
3439 * else bypass the cache.
3441 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3442 if (dev->param.nShortOpCaches > 0) {
3444 /* If we can't find the data in the cache, then load it up. */
3447 cache = yaffs_GrabChunkCache(in->myDev);
3449 cache->chunkId = chunk;
3452 yaffs_ReadChunkDataFromObject(in, chunk,
3458 yaffs_UseChunkCache(dev, cache, 0);
3463 memcpy(buffer, &cache->data[start], nToCopy);
3467 /* Read into the local buffer then copy..*/
3470 yaffs_GetTempBuffer(dev, __LINE__);
3471 yaffs_ReadChunkDataFromObject(in, chunk,
3474 memcpy(buffer, &localBuffer[start], nToCopy);
3477 yaffs_ReleaseTempBuffer(dev, localBuffer,
3483 /* A full chunk. Read directly into the supplied buffer. */
3484 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3498 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3499 int nBytes, int writeThrough)
3508 int startOfWrite = offset;
3509 int chunkWritten = 0;
3517 while (n > 0 && chunkWritten >= 0) {
3518 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3520 if (chunk * dev->nDataBytesPerChunk + start != offset ||
3521 start >= dev->nDataBytesPerChunk) {
3522 T(YAFFS_TRACE_ERROR, (
3523 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
3525 (int)offset, chunk, start));
3527 chunk++; /* File pos to chunk in file offset */
3529 /* OK now check for the curveball where the start and end are in
3533 if ((start + n) < dev->nDataBytesPerChunk) {
3536 /* Now folks, to calculate how many bytes to write back....
3537 * If we're overwriting and not writing to then end of file then
3538 * we need to write back as much as was there before.
3541 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
3543 if (chunkStart > in->variant.fileVariant.fileSize)
3544 nBytesRead = 0; /* Past end of file */
3546 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
3548 if (nBytesRead > dev->nDataBytesPerChunk)
3549 nBytesRead = dev->nDataBytesPerChunk;
3553 (start + n)) ? nBytesRead : (start + n);
3555 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
3559 nToCopy = dev->nDataBytesPerChunk - start;
3560 nToWriteBack = dev->nDataBytesPerChunk;
3563 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3564 /* An incomplete start or end chunk (or maybe both start and end chunk),
3565 * or we're using inband tags, so we want to use the cache buffers.
3567 if (dev->param.nShortOpCaches > 0) {
3568 yaffs_ChunkCache *cache;
3569 /* If we can't find the data in the cache, then load the cache */
3570 cache = yaffs_FindChunkCache(in, chunk);
3573 && yaffs_CheckSpaceForAllocation(dev, 1)) {
3574 cache = yaffs_GrabChunkCache(dev);
3576 cache->chunkId = chunk;
3579 yaffs_ReadChunkDataFromObject(in, chunk,
3583 !yaffs_CheckSpaceForAllocation(dev, 1)) {
3584 /* Drop the cache if it was a read cache item and
3585 * no space check has been made for it.
3591 yaffs_UseChunkCache(dev, cache, 1);
3595 memcpy(&cache->data[start], buffer,
3600 cache->nBytes = nToWriteBack;
3604 yaffs_WriteChunkDataToObject
3607 cache->data, cache->nBytes,
3613 chunkWritten = -1; /* fail the write */
3616 /* An incomplete start or end chunk (or maybe both start and end chunk)
3617 * Read into the local buffer then copy, then copy over and write back.
3621 yaffs_GetTempBuffer(dev, __LINE__);
3623 yaffs_ReadChunkDataFromObject(in, chunk,
3628 memcpy(&localBuffer[start], buffer, nToCopy);
3631 yaffs_WriteChunkDataToObject(in, chunk,
3636 yaffs_ReleaseTempBuffer(dev, localBuffer,
3642 /* A full chunk. Write directly from the supplied buffer. */
3647 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3648 dev->nDataBytesPerChunk,
3651 /* Since we've overwritten the cached data, we better invalidate it. */
3652 yaffs_InvalidateChunkCache(in, chunk);
3655 if (chunkWritten >= 0) {
3664 /* Update file object */
3666 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3667 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3674 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3675 int nBytes, int writeThrough)
3677 yaffs2_HandleHole(in,offset);
3678 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
3683 /* ---------------------- File resizing stuff ------------------ */
3685 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
3688 yaffs_Device *dev = in->myDev;
3689 int oldFileSize = in->variant.fileVariant.fileSize;
3691 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
3693 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
3694 dev->nDataBytesPerChunk;
3698 /* Delete backwards so that we don't end up with holes if
3699 * power is lost part-way through the operation.
3701 for (i = lastDel; i >= startDel; i--) {
3702 /* NB this could be optimised somewhat,
3703 * eg. could retrieve the tags and write them without
3704 * using yaffs_DeleteChunk
3707 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3710 (dev->internalStartBlock * dev->param.nChunksPerBlock)
3712 ((dev->internalEndBlock +
3713 1) * dev->param.nChunksPerBlock)) {
3714 T(YAFFS_TRACE_ALWAYS,
3715 (TSTR("Found daft chunkId %d for %d" TENDSTR),
3719 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3727 void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
3730 __u32 newSizeOfPartialChunk;
3731 yaffs_Device *dev = obj->myDev;
3733 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
3735 yaffs_PruneResizedChunks(obj, newSize);
3737 if (newSizeOfPartialChunk != 0) {
3738 int lastChunk = 1 + newFullChunks;
3739 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3741 /* Got to read and rewrite the last chunk with its new size and zero pad */
3742 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
3743 memset(localBuffer + newSizeOfPartialChunk, 0,
3744 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
3746 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
3747 newSizeOfPartialChunk, 1);
3749 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3752 obj->variant.fileVariant.fileSize = newSize;
3754 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
3758 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
3760 yaffs_Device *dev = in->myDev;
3761 int oldFileSize = in->variant.fileVariant.fileSize;
3763 yaffs_FlushFilesChunkCache(in);
3764 yaffs_InvalidateWholeChunkCache(in);
3766 yaffs_CheckGarbageCollection(dev,0);
3768 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3771 if (newSize == oldFileSize)
3774 if(newSize > oldFileSize){
3775 yaffs2_HandleHole(in,newSize);
3776 in->variant.fileVariant.fileSize = newSize;
3778 /* newSize < oldFileSize */
3779 yaffs_ResizeDown(in, newSize);
3782 /* Write a new object header to reflect the resize.
3783 * show we've shrunk the file, if need be
3784 * Do this only if the file is not in the deleted directories
3785 * and is not shadowed.
3789 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3790 in->parent->objectId != YAFFS_OBJECTID_DELETED)
3791 yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL);
3797 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3799 YCHAR *alias = NULL;
3800 obj = yaffs_GetEquivalentObject(obj);
3802 switch (obj->variantType) {
3803 case YAFFS_OBJECT_TYPE_FILE:
3804 return obj->variant.fileVariant.fileSize;
3805 case YAFFS_OBJECT_TYPE_SYMLINK:
3806 alias = obj->variant.symLinkVariant.alias;
3809 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
3817 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
3821 yaffs_FlushFilesChunkCache(in);
3822 if(dataSync) /* Only sync data */
3826 #ifdef CONFIG_YAFFS_WINCE
3827 yfsd_WinFileTimeNow(in->win_mtime);
3830 in->yst_mtime = Y_CURRENT_TIME;
3835 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL) >=
3836 0) ? YAFFS_OK : YAFFS_FAIL;
3846 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3849 /* First off, invalidate the file's data in the cache, without flushing. */
3850 yaffs_InvalidateWholeChunkCache(in);
3852 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3853 /* Move to the unlinked directory so we have a record that it was deleted. */
3854 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
3858 yaffs_RemoveObjectFromDirectory(in);
3859 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
3862 yaffs_FreeObject(in);
3867 /* yaffs_DeleteFile deletes the whole file data
3868 * and the inode associated with the file.
3869 * It does not delete the links associated with the file.
3871 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
3875 int immediateDeletion = 0;
3876 yaffs_Device *dev = in->myDev;
3879 immediateDeletion = 1;
3881 if (immediateDeletion) {
3883 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3884 _Y("deleted"), 0, 0);
3885 T(YAFFS_TRACE_TRACING,
3886 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3889 in->myDev->nDeletedFiles++;
3890 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3891 yaffs_ResizeFile(in, 0);
3892 yaffs_SoftDeleteFile(in);
3895 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3896 _Y("unlinked"), 0, 0);
3903 int yaffs_DeleteFile(yaffs_Object *in)
3905 int retVal = YAFFS_OK;
3906 int deleted; /* Need to cache value on stack if in is freed */
3907 yaffs_Device *dev = in->myDev;
3909 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3910 yaffs_ResizeFile(in, 0);
3912 if (in->nDataChunks > 0) {
3913 /* Use soft deletion if there is data in the file.
3914 * That won't be the case if it has been resized to zero.
3917 retVal = yaffs_UnlinkFileIfNeeded(in);
3919 deleted = in->deleted;
3921 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3924 in->myDev->nDeletedFiles++;
3925 yaffs_SoftDeleteFile(in);
3927 return deleted ? YAFFS_OK : YAFFS_FAIL;
3929 /* The file has no data chunks so we toss it immediately */
3930 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3931 in->variant.fileVariant.top = NULL;
3932 yaffs_DoGenericObjectDeletion(in);
3938 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
3940 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3941 !(ylist_empty(&obj->variant.directoryVariant.children));
3944 static int yaffs_DeleteDirectory(yaffs_Object *obj)
3946 /* First check that the directory is empty. */
3947 if (yaffs_IsNonEmptyDirectory(obj))
3950 return yaffs_DoGenericObjectDeletion(obj);
3953 static int yaffs_DeleteSymLink(yaffs_Object *in)
3955 if(in->variant.symLinkVariant.alias)
3956 YFREE(in->variant.symLinkVariant.alias);
3957 in->variant.symLinkVariant.alias=NULL;
3959 return yaffs_DoGenericObjectDeletion(in);
3962 static int yaffs_DeleteHardLink(yaffs_Object *in)
3964 /* remove this hardlink from the list assocaited with the equivalent
3967 ylist_del_init(&in->hardLinks);
3968 return yaffs_DoGenericObjectDeletion(in);
3971 int yaffs_DeleteObject(yaffs_Object *obj)
3974 switch (obj->variantType) {
3975 case YAFFS_OBJECT_TYPE_FILE:
3976 retVal = yaffs_DeleteFile(obj);
3978 case YAFFS_OBJECT_TYPE_DIRECTORY:
3979 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
3980 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
3981 ylist_del_init(&obj->variant.directoryVariant.dirty);
3983 return yaffs_DeleteDirectory(obj);
3985 case YAFFS_OBJECT_TYPE_SYMLINK:
3986 retVal = yaffs_DeleteSymLink(obj);
3988 case YAFFS_OBJECT_TYPE_HARDLINK:
3989 retVal = yaffs_DeleteHardLink(obj);
3991 case YAFFS_OBJECT_TYPE_SPECIAL:
3992 retVal = yaffs_DoGenericObjectDeletion(obj);
3994 case YAFFS_OBJECT_TYPE_UNKNOWN:
3996 break; /* should not happen. */
4002 static int yaffs_UnlinkWorker(yaffs_Object *obj)
4005 int immediateDeletion = 0;
4008 immediateDeletion = 1;
4011 yaffs_UpdateParent(obj->parent);
4013 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4014 return yaffs_DeleteHardLink(obj);
4015 } else if (!ylist_empty(&obj->hardLinks)) {
4016 /* Curve ball: We're unlinking an object that has a hardlink.
4018 * This problem arises because we are not strictly following
4019 * The Linux link/inode model.
4021 * We can't really delete the object.
4022 * Instead, we do the following:
4023 * - Select a hardlink.
4024 * - Unhook it from the hard links
4025 * - Move it from its parent directory (so that the rename can work)
4026 * - Rename the object to the hardlink's name.
4027 * - Delete the hardlink
4031 yaffs_Object *parent;
4033 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4035 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4037 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4038 parent = hl->parent;
4040 ylist_del_init(&hl->hardLinks);
4042 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
4044 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
4046 if (retVal == YAFFS_OK)
4047 retVal = yaffs_DoGenericObjectDeletion(hl);
4051 } else if (immediateDeletion) {
4052 switch (obj->variantType) {
4053 case YAFFS_OBJECT_TYPE_FILE:
4054 return yaffs_DeleteFile(obj);
4056 case YAFFS_OBJECT_TYPE_DIRECTORY:
4057 ylist_del_init(&obj->variant.directoryVariant.dirty);
4058 return yaffs_DeleteDirectory(obj);
4060 case YAFFS_OBJECT_TYPE_SYMLINK:
4061 return yaffs_DeleteSymLink(obj);
4063 case YAFFS_OBJECT_TYPE_SPECIAL:
4064 return yaffs_DoGenericObjectDeletion(obj);
4066 case YAFFS_OBJECT_TYPE_HARDLINK:
4067 case YAFFS_OBJECT_TYPE_UNKNOWN:
4071 } else if(yaffs_IsNonEmptyDirectory(obj))
4074 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
4075 _Y("unlinked"), 0, 0);
4079 static int yaffs_UnlinkObject(yaffs_Object *obj)
4082 if (obj && obj->unlinkAllowed)
4083 return yaffs_UnlinkWorker(obj);
4088 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
4092 obj = yaffs_FindObjectByName(dir, name);
4093 return yaffs_UnlinkObject(obj);
4096 /*----------------------- Initialisation Scanning ---------------------- */
4098 void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
4099 int backwardScanning)
4103 if (!backwardScanning) {
4104 /* Handle YAFFS1 forward scanning case
4105 * For YAFFS1 we always do the deletion
4109 /* Handle YAFFS2 case (backward scanning)
4110 * If the shadowed object exists then ignore.
4112 obj = yaffs_FindObjectByNumber(dev, objId);
4117 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4118 * We put it in unlinked dir to be cleaned up after the scanning
4121 yaffs_FindOrCreateObjectByNumber(dev, objId,
4122 YAFFS_OBJECT_TYPE_FILE);
4125 obj->isShadowed = 1;
4126 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4127 obj->variant.fileVariant.shrinkSize = 0;
4128 obj->valid = 1; /* So that we don't read any other info for this file */
4133 void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4140 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4142 in = yaffs_FindObjectByNumber(dev,
4143 hl->variant.hardLinkVariant.
4144 equivalentObjectId);
4147 /* Add the hardlink pointers */
4148 hl->variant.hardLinkVariant.equivalentObject = in;
4149 ylist_add(&hl->hardLinks, &in->hardLinks);
4151 /* Todo Need to report/handle this better.
4152 * Got a problem... hardlink to a non-existant object
4154 hl->variant.hardLinkVariant.equivalentObject = NULL;
4155 YINIT_LIST_HEAD(&hl->hardLinks);
4162 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
4165 * Sort out state of unlinked and deleted objects after scanning.
4167 struct ylist_head *i;
4168 struct ylist_head *n;
4171 /* Soft delete all the unlinked files */
4172 ylist_for_each_safe(i, n,
4173 &dev->unlinkedDir->variant.directoryVariant.children) {
4175 l = ylist_entry(i, yaffs_Object, siblings);
4176 yaffs_DeleteObject(l);
4180 ylist_for_each_safe(i, n,
4181 &dev->deletedDir->variant.directoryVariant.children) {
4183 l = ylist_entry(i, yaffs_Object, siblings);
4184 yaffs_DeleteObject(l);
4191 * This code iterates through all the objects making sure that they are rooted.
4192 * Any unrooted objects are re-rooted in lost+found.
4193 * An object needs to be in one of:
4194 * - Directly under deleted, unlinked
4195 * - Directly or indirectly under root.
4198 * This code assumes that we don't ever change the current relationships between
4200 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
4201 * lostNfound->parent == rootDir
4203 * This fixes the problem where directories might have inadvertently been deleted
4204 * leaving the object "hanging" without being rooted in the directory tree.
4207 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
4209 return (obj == dev->deletedDir ||
4210 obj == dev->unlinkedDir||
4211 obj == dev->rootDir);
4214 static void yaffs_FixHangingObjects(yaffs_Device *dev)
4217 yaffs_Object *parent;
4219 struct ylist_head *lh;
4220 struct ylist_head *n;
4225 /* Iterate through the objects in each hash entry,
4226 * looking at each object.
4227 * Make sure it is rooted.
4230 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
4231 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
4233 obj = ylist_entry(lh, yaffs_Object, hashLink);
4234 parent= obj->parent;
4236 if(yaffs_HasNULLParent(dev,obj)){
4237 /* These directories are not hanging */
4240 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4242 else if(yaffs_HasNULLParent(dev,parent))
4246 * Need to follow the parent chain to see if it is hanging.
4251 while(parent != dev->rootDir &&
4253 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
4255 parent = parent->parent;
4258 if(parent != dev->rootDir)
4263 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
4265 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
4274 * Delete directory contents for cleaning up lost and found.
4276 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
4279 struct ylist_head *lh;
4280 struct ylist_head *n;
4282 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4285 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
4287 obj = ylist_entry(lh, yaffs_Object, siblings);
4288 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
4289 yaffs_DeleteDirectoryContents(obj);
4292 (TSTR("Deleting lost_found object %d" TENDSTR),
4295 /* Need to use UnlinkObject since Delete would not handle
4296 * hardlinked objects correctly.
4298 yaffs_UnlinkObject(obj);
4304 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
4306 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
4309 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4312 yaffs_ObjectHeader *oh;
4314 yaffs_ExtendedTags tags;
4316 int alloc_failed = 0;
4324 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
4326 in->lazyLoaded ? "not yet" : "already"));
4329 if (in->lazyLoaded && in->hdrChunk > 0) {
4331 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4333 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
4334 oh = (yaffs_ObjectHeader *) chunkData;
4336 in->yst_mode = oh->yst_mode;
4337 #ifdef CONFIG_YAFFS_WINCE
4338 in->win_atime[0] = oh->win_atime[0];
4339 in->win_ctime[0] = oh->win_ctime[0];
4340 in->win_mtime[0] = oh->win_mtime[0];
4341 in->win_atime[1] = oh->win_atime[1];
4342 in->win_ctime[1] = oh->win_ctime[1];
4343 in->win_mtime[1] = oh->win_mtime[1];
4345 in->yst_uid = oh->yst_uid;
4346 in->yst_gid = oh->yst_gid;
4347 in->yst_atime = oh->yst_atime;
4348 in->yst_mtime = oh->yst_mtime;
4349 in->yst_ctime = oh->yst_ctime;
4350 in->yst_rdev = oh->yst_rdev;
4353 yaffs_SetObjectName(in, oh->name);
4355 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
4356 in->variant.symLinkVariant.alias =
4357 yaffs_CloneString(oh->alias);
4358 if (!in->variant.symLinkVariant.alias)
4359 alloc_failed = 1; /* Not returned to caller */
4362 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4366 /*------------------------------ Directory Functions ----------------------------- */
4369 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
4370 * link (ie. name) is created or deleted in the directory.
4373 * create dir/a : update dir's mtime/ctime
4374 * rm dir/a: update dir's mtime/ctime
4375 * modify dir/a: don't update dir's mtimme/ctime
4377 * This can be handled immediately or defered. Defering helps reduce the number
4378 * of updates when many files in a directory are changed within a brief period.
4380 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
4381 * called periodically.
4384 static void yaffs_UpdateParent(yaffs_Object *obj)
4392 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
4393 if(dev->param.deferDirectoryUpdate){
4394 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
4396 if(ylist_empty(link)){
4397 ylist_add(link,&dev->dirtyDirectories);
4398 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
4402 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4405 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
4407 struct ylist_head *link;
4409 yaffs_DirectoryStructure *dS;
4410 yaffs_ObjectVariant *oV;
4412 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
4414 while(!ylist_empty(&dev->dirtyDirectories)){
4415 link = dev->dirtyDirectories.next;
4416 ylist_del_init(link);
4418 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
4419 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
4420 obj = ylist_entry(oV,yaffs_Object,variant);
4422 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
4425 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4429 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4431 yaffs_Device *dev = obj->myDev;
4432 yaffs_Object *parent;
4434 yaffs_VerifyObjectInDirectory(obj);
4435 parent = obj->parent;
4437 yaffs_VerifyDirectory(parent);
4439 if (dev && dev->param.removeObjectCallback)
4440 dev->param.removeObjectCallback(obj);
4443 ylist_del_init(&obj->siblings);
4446 yaffs_VerifyDirectory(parent);
4449 void yaffs_AddObjectToDirectory(yaffs_Object *directory,
4453 T(YAFFS_TRACE_ALWAYS,
4455 ("tragedy: Trying to add an object to a null pointer directory"
4460 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4461 T(YAFFS_TRACE_ALWAYS,
4463 ("tragedy: Trying to add an object to a non-directory"
4468 if (obj->siblings.prev == NULL) {
4469 /* Not initialised */
4474 yaffs_VerifyDirectory(directory);
4476 yaffs_RemoveObjectFromDirectory(obj);
4480 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
4481 obj->parent = directory;
4483 if (directory == obj->myDev->unlinkedDir
4484 || directory == obj->myDev->deletedDir) {
4486 obj->myDev->nUnlinkedFiles++;
4487 obj->renameAllowed = 0;
4490 yaffs_VerifyDirectory(directory);
4491 yaffs_VerifyObjectInDirectory(obj);
4494 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
4499 struct ylist_head *i;
4500 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4508 T(YAFFS_TRACE_ALWAYS,
4510 ("tragedy: yaffs_FindObjectByName: null pointer directory"
4515 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4516 T(YAFFS_TRACE_ALWAYS,
4518 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4522 sum = yaffs_CalcNameSum(name);
4524 ylist_for_each(i, &directory->variant.directoryVariant.children) {
4526 l = ylist_entry(i, yaffs_Object, siblings);
4528 if (l->parent != directory)
4531 yaffs_CheckObjectDetailsLoaded(l);
4533 /* Special case for lost-n-found */
4534 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4535 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
4537 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
4538 /* LostnFound chunk called Objxxx
4541 yaffs_GetObjectName(l, buffer,
4542 YAFFS_MAX_NAME_LENGTH + 1);
4543 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
4554 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
4555 int (*fn) (yaffs_Object *))
4557 struct ylist_head *i;
4561 T(YAFFS_TRACE_ALWAYS,
4563 ("tragedy: yaffs_FindObjectByName: null pointer directory"
4568 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4569 T(YAFFS_TRACE_ALWAYS,
4571 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4576 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
4578 l = ylist_entry(i, yaffs_Object, siblings);
4589 /* GetEquivalentObject dereferences any hard links to get to the
4593 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4595 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4596 /* We want the object id of the equivalent object, not this one */
4597 obj = obj->variant.hardLinkVariant.equivalentObject;
4598 yaffs_CheckObjectDetailsLoaded(obj);
4603 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
4605 memset(name, 0, buffSize * sizeof(YCHAR));
4607 yaffs_CheckObjectDetailsLoaded(obj);
4609 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4610 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
4611 } else if (obj->hdrChunk <= 0) {
4613 YCHAR numString[20];
4614 YCHAR *x = &numString[19];
4615 unsigned v = obj->objectId;
4619 *x = '0' + (v % 10);
4622 /* make up a name */
4623 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
4624 yaffs_strcat(locName, x);
4625 yaffs_strncpy(name, locName, buffSize - 1);
4628 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4629 else if (obj->shortName[0])
4630 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
4634 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
4636 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
4638 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
4640 if (obj->hdrChunk > 0) {
4641 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
4642 obj->hdrChunk, buffer,
4645 yaffs_strncpy(name, oh->name, buffSize - 1);
4648 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
4651 return yaffs_strnlen(name,buffSize-1);
4654 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4656 /* Dereference any hard linking */
4657 obj = yaffs_GetEquivalentObject(obj);
4659 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4660 return obj->variant.fileVariant.fileSize;
4661 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
4662 if(!obj->variant.symLinkVariant.alias)
4664 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
4666 /* Only a directory should drop through to here */
4667 return obj->myDev->nDataBytesPerChunk;
4671 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4674 struct ylist_head *i;
4677 count++; /* the object itself */
4679 ylist_for_each(i, &obj->hardLinks)
4680 count++; /* add the hard links; */
4685 int yaffs_GetObjectInode(yaffs_Object *obj)
4687 obj = yaffs_GetEquivalentObject(obj);
4689 return obj->objectId;
4692 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4694 obj = yaffs_GetEquivalentObject(obj);
4696 switch (obj->variantType) {
4697 case YAFFS_OBJECT_TYPE_FILE:
4700 case YAFFS_OBJECT_TYPE_DIRECTORY:
4703 case YAFFS_OBJECT_TYPE_SYMLINK:
4706 case YAFFS_OBJECT_TYPE_HARDLINK:
4709 case YAFFS_OBJECT_TYPE_SPECIAL:
4710 if (S_ISFIFO(obj->yst_mode))
4712 if (S_ISCHR(obj->yst_mode))
4714 if (S_ISBLK(obj->yst_mode))
4716 if (S_ISSOCK(obj->yst_mode))
4724 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4726 obj = yaffs_GetEquivalentObject(obj);
4727 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4728 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4730 return yaffs_CloneString(_Y(""));
4733 #ifndef CONFIG_YAFFS_WINCE
4735 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4737 unsigned int valid = attr->ia_valid;
4739 if (valid & ATTR_MODE)
4740 obj->yst_mode = attr->ia_mode;
4741 if (valid & ATTR_UID)
4742 obj->yst_uid = attr->ia_uid;
4743 if (valid & ATTR_GID)
4744 obj->yst_gid = attr->ia_gid;
4746 if (valid & ATTR_ATIME)
4747 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
4748 if (valid & ATTR_CTIME)
4749 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
4750 if (valid & ATTR_MTIME)
4751 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
4753 if (valid & ATTR_SIZE)
4754 yaffs_ResizeFile(obj, attr->ia_size);
4756 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0, NULL);
4761 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4763 unsigned int valid = 0;
4765 attr->ia_mode = obj->yst_mode;
4767 attr->ia_uid = obj->yst_uid;
4769 attr->ia_gid = obj->yst_gid;
4772 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
4773 valid |= ATTR_ATIME;
4774 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
4775 valid |= ATTR_CTIME;
4776 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
4777 valid |= ATTR_MTIME;
4779 attr->ia_size = yaffs_GetFileSize(obj);
4782 attr->ia_valid = valid;
4790 static int yaffs_DoXMod(yaffs_Object *obj, int set, const char *name, const void *value, int size, int flags)
4792 yaffs_XAttrMod xmod;
4801 xmod.result = -ENOSPC;
4803 result = yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, &xmod);
4811 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod)
4814 int x_offs = sizeof(yaffs_ObjectHeader);
4815 int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4817 char * x_buffer = buffer + x_offs;
4820 retval = nval_set(x_buffer, x_size, xmod->name, xmod->data, xmod->size, xmod->flags);
4822 retval = nval_del(x_buffer, x_size, xmod->name);
4824 xmod->result = retval;
4829 static int yaffs_DoXFetch(yaffs_Object *obj, const char *name, void *value, int size)
4831 char *buffer = NULL;
4833 yaffs_ExtendedTags tags;
4834 yaffs_Device *dev = obj->myDev;
4835 int x_offs = sizeof(yaffs_ObjectHeader);
4836 int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4842 if(obj->hdrChunk < 1)
4845 buffer = yaffs_GetTempBuffer(dev, __LINE__);
4849 result = yaffs_ReadChunkWithTagsFromNAND(dev,obj->hdrChunk, buffer, &tags);
4851 if(result != YAFFS_OK)
4854 x_buffer = buffer + x_offs;
4857 retval = nval_get(x_buffer, x_size, name, value, size);
4859 retval = nval_list(x_buffer, x_size, value,size);
4861 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
4865 int yaffs_SetXAttribute(yaffs_Object *obj, const char *name, const void * value, int size, int flags)
4867 return yaffs_DoXMod(obj, 1, name, value, size, flags);
4870 int yaffs_RemoveXAttribute(yaffs_Object *obj, const char *name)
4872 return yaffs_DoXMod(obj, 0, name, NULL, 0, 0);
4875 int yaffs_GetXAttribute(yaffs_Object *obj, const char *name, void *value, int size)
4877 return yaffs_DoXFetch(obj, name, value, size);
4880 int yaffs_ListXAttributes(yaffs_Object *obj, char *buffer, int size)
4882 return yaffs_DoXFetch(obj, NULL, buffer,size);
4888 int yaffs_DumpObject(yaffs_Object *obj)
4892 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
4894 T(YAFFS_TRACE_ALWAYS,
4896 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
4897 " chunk %d type %d size %d\n"
4898 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
4899 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
4900 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4906 /*---------------------------- Initialisation code -------------------------------------- */
4908 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
4911 /* Common functions, gotta have */
4912 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
4915 #ifdef CONFIG_YAFFS_YAFFS2
4917 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
4918 if (dev->param.writeChunkWithTagsToNAND &&
4919 dev->param.readChunkWithTagsFromNAND &&
4920 !dev->param.writeChunkToNAND &&
4921 !dev->param.readChunkFromNAND &&
4922 dev->param.markNANDBlockBad &&
4923 dev->param.queryNANDBlock)
4927 /* Can use the "spare" style interface for yaffs1 */
4928 if (!dev->param.isYaffs2 &&
4929 !dev->param.writeChunkWithTagsToNAND &&
4930 !dev->param.readChunkWithTagsFromNAND &&
4931 dev->param.writeChunkToNAND &&
4932 dev->param.readChunkFromNAND &&
4933 !dev->param.markNANDBlockBad &&
4934 !dev->param.queryNANDBlock)
4941 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
4943 /* Initialise the unlinked, deleted, root and lost and found directories */
4945 dev->lostNFoundDir = dev->rootDir = NULL;
4946 dev->unlinkedDir = dev->deletedDir = NULL;
4949 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4952 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
4955 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
4956 YAFFS_ROOT_MODE | S_IFDIR);
4957 dev->lostNFoundDir =
4958 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
4959 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4961 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
4962 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
4969 int yaffs_GutsInitialise(yaffs_Device *dev)
4971 int init_failed = 0;
4975 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
4977 /* Check stuff that must be set */
4980 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
4984 dev->internalStartBlock = dev->param.startBlock;
4985 dev->internalEndBlock = dev->param.endBlock;
4986 dev->blockOffset = 0;
4987 dev->chunkOffset = 0;
4988 dev->nFreeChunks = 0;
4992 if (dev->param.startBlock == 0) {
4993 dev->internalStartBlock = dev->param.startBlock + 1;
4994 dev->internalEndBlock = dev->param.endBlock + 1;
4995 dev->blockOffset = 1;
4996 dev->chunkOffset = dev->param.nChunksPerBlock;
4999 /* Check geometry parameters. */
5001 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
5002 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
5003 (dev->param.inbandTags && !dev->param.isYaffs2) ||
5004 dev->param.nChunksPerBlock < 2 ||
5005 dev->param.nReservedBlocks < 2 ||
5006 dev->internalStartBlock <= 0 ||
5007 dev->internalEndBlock <= 0 ||
5008 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
5009 T(YAFFS_TRACE_ALWAYS,
5011 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
5012 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
5016 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5017 T(YAFFS_TRACE_ALWAYS,
5018 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5022 /* Sort out space for inband tags, if required */
5023 if (dev->param.inbandTags)
5024 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
5026 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
5028 /* Got the right mix of functions? */
5029 if (!yaffs_CheckDevFunctions(dev)) {
5030 /* Function missing */
5031 T(YAFFS_TRACE_ALWAYS,
5033 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5038 /* This is really a compilation check. */
5039 if (!yaffs_CheckStructures()) {
5040 T(YAFFS_TRACE_ALWAYS,
5041 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5045 if (dev->isMounted) {
5046 T(YAFFS_TRACE_ALWAYS,
5047 (TSTR("yaffs: device already mounted\n" TENDSTR)));
5051 /* Finished with most checks. One or two more checks happen later on too. */
5055 /* OK now calculate a few things for the device */
5058 * Calculate all the chunk size manipulation numbers:
5060 x = dev->nDataBytesPerChunk;
5061 /* We always use dev->chunkShift and dev->chunkDiv */
5062 dev->chunkShift = Shifts(x);
5063 x >>= dev->chunkShift;
5065 /* We only use chunk mask if chunkDiv is 1 */
5066 dev->chunkMask = (1<<dev->chunkShift) - 1;
5069 * Calculate chunkGroupBits.
5070 * We need to find the next power of 2 > than internalEndBlock
5073 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
5077 /* Set up tnode width if wide tnodes are enabled. */
5078 if (!dev->param.wideTnodesDisabled) {
5079 /* bits must be even so that we end up with 32-bit words */
5083 dev->tnodeWidth = 16;
5085 dev->tnodeWidth = bits;
5087 dev->tnodeWidth = 16;
5089 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5091 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5092 * so if the bitwidth of the
5093 * chunk range we're using is greater than 16 we need
5094 * to figure out chunk shift and chunkGroupSize
5097 if (bits <= dev->tnodeWidth)
5098 dev->chunkGroupBits = 0;
5100 dev->chunkGroupBits = bits - dev->tnodeWidth;
5102 dev->tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
5103 if(dev->tnodeSize < sizeof(yaffs_Tnode))
5104 dev->tnodeSize = sizeof(yaffs_Tnode);
5106 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5108 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
5109 /* We have a problem because the soft delete won't work if
5110 * the chunk group size > chunks per block.
5111 * This can be remedied by using larger "virtual blocks".
5113 T(YAFFS_TRACE_ALWAYS,
5114 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5119 /* OK, we've finished verifying the device, lets continue with initialisation */
5121 /* More device initialisation */
5123 dev->passiveGCs = 0;
5124 dev->oldestDirtyGCs = 0;
5125 dev->backgroundGCs = 0;
5126 dev->gcBlockFinder = 0;
5127 dev->bufferedBlock = -1;
5128 dev->doingBufferedBlockRewrite = 0;
5129 dev->nDeletedFiles = 0;
5130 dev->nBackgroundDeletions = 0;
5131 dev->nUnlinkedFiles = 0;
5133 dev->eccUnfixed = 0;
5134 dev->tagsEccFixed = 0;
5135 dev->tagsEccUnfixed = 0;
5136 dev->nErasureFailures = 0;
5137 dev->nErasedBlocks = 0;
5139 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
5140 YINIT_LIST_HEAD(&dev->dirtyDirectories);
5141 dev->oldestDirtySequence = 0;
5142 dev->oldestDirtyBlock = 0;
5144 /* Initialise temporary buffers and caches. */
5145 if (!yaffs_InitialiseTempBuffers(dev))
5148 dev->srCache = NULL;
5149 dev->gcCleanupList = NULL;
5153 dev->param.nShortOpCaches > 0) {
5156 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
5158 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
5159 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5161 dev->srCache = YMALLOC(srCacheBytes);
5163 buf = (__u8 *) dev->srCache;
5166 memset(dev->srCache, 0, srCacheBytes);
5168 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
5169 dev->srCache[i].object = NULL;
5170 dev->srCache[i].lastUse = 0;
5171 dev->srCache[i].dirty = 0;
5172 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
5183 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
5184 if (!dev->gcCleanupList)
5188 if (dev->param.isYaffs2)
5189 dev->param.useHeaderFileSize = 1;
5191 if (!init_failed && !yaffs_InitialiseBlocks(dev))
5194 yaffs_InitialiseTnodesAndObjects(dev);
5196 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5201 /* Now scan the flash. */
5202 if (dev->param.isYaffs2) {
5203 if (yaffs2_CheckpointRestore(dev)) {
5204 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
5205 T(YAFFS_TRACE_ALWAYS,
5206 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
5209 /* Clean up the mess caused by an aborted checkpoint load
5210 * and scan backwards.
5212 yaffs_DeinitialiseBlocks(dev);
5214 yaffs_DeinitialiseTnodesAndObjects(dev);
5216 dev->nErasedBlocks = 0;
5217 dev->nFreeChunks = 0;
5218 dev->allocationBlock = -1;
5219 dev->allocationPage = -1;
5220 dev->nDeletedFiles = 0;
5221 dev->nUnlinkedFiles = 0;
5222 dev->nBackgroundDeletions = 0;
5224 if (!init_failed && !yaffs_InitialiseBlocks(dev))
5227 yaffs_InitialiseTnodesAndObjects(dev);
5229 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5232 if (!init_failed && !yaffs2_ScanBackwards(dev))
5235 } else if (!yaffs1_Scan(dev))
5238 yaffs_StripDeletedObjects(dev);
5239 yaffs_FixHangingObjects(dev);
5240 if(dev->param.emptyLostAndFound)
5241 yaffs_EmptyLostAndFound(dev);
5245 /* Clean up the mess */
5246 T(YAFFS_TRACE_TRACING,
5247 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
5249 yaffs_Deinitialise(dev);
5253 /* Zero out stats */
5254 dev->nPageReads = 0;
5255 dev->nPageWrites = 0;
5256 dev->nBlockErasures = 0;
5258 dev->nRetriedWrites = 0;
5260 dev->nRetiredBlocks = 0;
5262 yaffs_VerifyFreeChunks(dev);
5263 yaffs_VerifyBlocks(dev);
5265 /* Clean up any aborted checkpoint data */
5266 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
5267 yaffs2_InvalidateCheckpoint(dev);
5269 T(YAFFS_TRACE_TRACING,
5270 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5275 void yaffs_Deinitialise(yaffs_Device *dev)
5277 if (dev->isMounted) {
5280 yaffs_DeinitialiseBlocks(dev);
5281 yaffs_DeinitialiseTnodesAndObjects(dev);
5282 if (dev->param.nShortOpCaches > 0 &&
5285 for (i = 0; i < dev->param.nShortOpCaches; i++) {
5286 if (dev->srCache[i].data)
5287 YFREE(dev->srCache[i].data);
5288 dev->srCache[i].data = NULL;
5291 YFREE(dev->srCache);
5292 dev->srCache = NULL;
5295 YFREE(dev->gcCleanupList);
5297 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5298 YFREE(dev->tempBuffer[i].buffer);
5302 if (dev->param.deinitialiseNAND)
5303 dev->param.deinitialiseNAND(dev);
5307 int yaffs_CountFreeChunks(yaffs_Device *dev)
5312 yaffs_BlockInfo *blk;
5314 blk = dev->blockInfo;
5315 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
5316 switch (blk->blockState) {
5317 case YAFFS_BLOCK_STATE_EMPTY:
5318 case YAFFS_BLOCK_STATE_ALLOCATING:
5319 case YAFFS_BLOCK_STATE_COLLECTING:
5320 case YAFFS_BLOCK_STATE_FULL:
5322 (dev->param.nChunksPerBlock - blk->pagesInUse +
5323 blk->softDeletions);
5334 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
5336 /* This is what we report to the outside world */
5339 int nDirtyCacheChunks;
5340 int blocksForCheckpoint;
5344 nFree = dev->nFreeChunks;
5346 nFree = yaffs_CountFreeChunks(dev);
5349 nFree += dev->nDeletedFiles;
5351 /* Now count the number of dirty chunks in the cache and subtract those */
5353 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
5354 if (dev->srCache[i].dirty)
5355 nDirtyCacheChunks++;
5358 nFree -= nDirtyCacheChunks;
5360 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
5362 /* Now we figure out how much to reserve for the checkpoint and report that... */
5363 blocksForCheckpoint = yaffs2_CalcCheckpointBlocksRequired(dev);
5365 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
5375 /*---------------------------------------- YAFFS test code ----------------------*/
5377 #define yaffs_CheckStruct(structure, syze, name) \
5379 if (sizeof(structure) != syze) { \
5380 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
5381 name, syze, (int) sizeof(structure))); \
5382 return YAFFS_FAIL; \
5386 static int yaffs_CheckStructures(void)
5388 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
5389 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
5390 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
5391 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5392 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
5394 #ifndef CONFIG_YAFFS_WINCE
5395 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");