2 * YAFFS: Yet another FFS. A NAND-flash specific file system.
4 * Copyright (C) 2002 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
15 const char *yaffs_guts_c_version =
16 "$Id: yaffs_guts.c,v 1.30 2006-03-01 08:14:32 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
26 #ifdef CONFIG_YAFFS_WINCE
27 void yfsd_LockYAFFS(BOOL fsLockOnly);
28 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
31 #define YAFFS_PASSIVE_GC_CHUNKS 2
33 #include "yaffs_ecc.h"
37 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev,
40 yaffs_ExtendedTags * tags);
41 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
44 yaffs_ExtendedTags * tags);
45 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo);
46 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
48 yaffs_BlockState * state,
49 unsigned *sequenceNumber);
50 /* Robustification (if it ever comes about...) */
51 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
52 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND);
53 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
55 const yaffs_ExtendedTags * tags);
56 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
57 const yaffs_ExtendedTags * tags);
59 /* Other local prototypes */
60 static int yaffs_UnlinkObject( yaffs_Object *obj);
62 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
64 yaffs_ExtendedTags * tags,
66 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
67 int chunkInNAND, int inScan);
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
70 yaffs_ObjectType type);
71 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
73 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
74 int force, int isShrink, int shadows);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
78 int chunkOffset, int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
83 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
84 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
87 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
90 static int yaffs_UnlinkWorker(yaffs_Object * obj);
91 static void yaffs_DestroyObject(yaffs_Object * obj);
93 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
96 loff_t yaffs_GetFileSize(yaffs_Object * obj);
98 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
100 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
113 * Start of real code.
122 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
124 yaffs_ExtendedTags * tags)
126 chunkInNAND -= dev->chunkOffset;
128 if (dev->readChunkWithTagsFromNAND)
129 return dev->readChunkWithTagsFromNAND(dev, chunkInNAND, buffer,
132 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,
138 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
141 yaffs_ExtendedTags * tags)
143 chunkInNAND -= dev->chunkOffset;
146 tags->sequenceNumber = dev->sequenceNumber;
148 if (!yaffs_ValidateTags(tags)) {
150 (TSTR("Writing uninitialised tags" TENDSTR)));
154 (TSTR("Writing chunk %d tags %d %d" TENDSTR), chunkInNAND,
155 tags->objectId, tags->chunkId));
157 T(YAFFS_TRACE_ERROR, (TSTR("Writing with no tags" TENDSTR)));
161 if (dev->writeChunkWithTagsToNAND)
162 return dev->writeChunkWithTagsToNAND(dev, chunkInNAND, buffer,
165 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,
171 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo)
173 blockNo -= dev->blockOffset;
175 if (dev->markNANDBlockBad)
176 return dev->markNANDBlockBad(dev, blockNo);
178 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev, blockNo);
180 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
182 yaffs_BlockState * state,
183 unsigned *sequenceNumber)
185 blockNo -= dev->blockOffset;
187 if (dev->queryNANDBlock)
188 return dev->queryNANDBlock(dev, blockNo, state, sequenceNumber);
190 return yaffs_TagsCompatabilityQueryNANDBlock(dev, blockNo,
195 static int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,
200 blockInNAND -= dev->blockOffset;
202 dev->nBlockErasures++;
203 result = dev->eraseBlockInNAND(dev, blockInNAND);
205 /* If at first we don't succeed, try again *once*.*/
207 result = dev->eraseBlockInNAND(dev, blockInNAND);
211 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
213 return dev->initialiseNAND(dev);
217 * Temporary buffer manipulations.
220 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
223 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
224 if (dev->tempBuffer[i].line == 0) {
225 dev->tempBuffer[i].line = lineNo;
226 if ((i + 1) > dev->maxTemp) {
227 dev->maxTemp = i + 1;
228 for (j = 0; j <= i; j++)
229 dev->tempBuffer[j].maxLine =
230 dev->tempBuffer[j].line;
233 return dev->tempBuffer[i].buffer;
237 T(YAFFS_TRACE_BUFFERS,
238 (TSTR("Out of temp buffers at line %d, other held by lines:"),
240 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
243 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
246 * If we got here then we have to allocate an unmanaged one
250 dev->unmanagedTempAllocations++;
251 return YMALLOC(dev->nBytesPerChunk);
255 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
259 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
260 if (dev->tempBuffer[i].buffer == buffer) {
261 dev->tempBuffer[i].line = 0;
267 /* assume it is an unmanaged one. */
268 T(YAFFS_TRACE_BUFFERS,
269 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
272 dev->unmanagedTempDeallocations++;
278 * Chunk bitmap manipulations
281 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
283 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
285 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
289 return dev->chunkBits +
290 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
293 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
295 __u8 *blkBits = yaffs_BlockBits(dev, blk);
297 memset(blkBits, 0, dev->chunkBitmapStride);
300 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
302 __u8 *blkBits = yaffs_BlockBits(dev, blk);
304 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
307 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
309 __u8 *blkBits = yaffs_BlockBits(dev, blk);
311 blkBits[chunk / 8] |= (1 << (chunk & 7));
314 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
316 __u8 *blkBits = yaffs_BlockBits(dev, blk);
317 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
320 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
322 __u8 *blkBits = yaffs_BlockBits(dev, blk);
324 for (i = 0; i < dev->chunkBitmapStride; i++) {
333 * Simple hash function. Needs to have a reasonable spread
336 static Y_INLINE int yaffs_HashFunction(int n)
339 return (n % YAFFS_NOBJECT_BUCKETS);
343 * Access functions to useful fake objects
346 yaffs_Object *yaffs_Root(yaffs_Device * dev)
351 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
353 return dev->lostNFoundDir;
358 * Erased NAND checking functions
361 int yaffs_CheckFF(__u8 * buffer, int nBytes)
363 /* Horrible, slow implementation */
372 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
376 int retval = YAFFS_OK;
377 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
378 yaffs_ExtendedTags tags;
380 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
382 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
383 T(YAFFS_TRACE_NANDACCESS,
384 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
388 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
394 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
396 yaffs_ExtendedTags * tags,
405 chunk = yaffs_AllocateChunk(dev, useReserve);
409 /* First check this chunk is erased... */
410 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
411 writeOk = yaffs_CheckChunkErased(dev, chunk);
416 ("**>> yaffs chunk %d was not erased"
420 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
427 * Copy the data into the robustification buffer.
428 * NB We do this at the end to prevent duplicates in the case of a write error.
431 yaffs_HandleWriteChunkOk(dev, chunk, data,
434 yaffs_HandleWriteChunkError(dev, chunk);
438 } while (chunk >= 0 && !writeOk);
442 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
444 dev->nRetriedWrites += (attempts - 1);
451 * Block retiring for handling a broken block.
454 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
457 yaffs_MarkBlockBad(dev, blockInNAND);
459 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
460 YAFFS_BLOCK_STATE_DEAD;
462 dev->nRetiredBlocks++;
466 * Functions for robustisizing TODO
470 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
472 const yaffs_ExtendedTags * tags)
476 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
477 const yaffs_ExtendedTags * tags)
481 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
483 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
485 /* Mark the block for retirement */
486 yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
487 /* Delete the chunk */
488 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
492 /*---------------- Name handling functions ------------*/
494 static __u16 yaffs_CalcNameSum(const YCHAR * name)
499 YUCHAR *bname = (YUCHAR *) name;
501 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
503 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
504 sum += yaffs_toupper(*bname) * i;
515 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
517 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
518 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
519 yaffs_strcpy(obj->shortName, name);
521 obj->shortName[0] = _Y('\0');
524 obj->sum = yaffs_CalcNameSum(name);
527 /*-------------------- TNODES -------------------
529 * List of spare tnodes
530 * The list is hooked together using the first pointer
534 /* yaffs_CreateTnodes creates a bunch more tnodes and
535 * adds them to the tnode free list.
536 * Don't use this function directly
539 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
543 yaffs_Tnode *newTnodes;
547 yaffs_TnodeList *tnl;
552 /* Calculate the tnode size in bytes for variable width tnode support.
553 * Must be a multiple of 32-bits */
554 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
556 /* make these things */
558 newTnodes = YMALLOC(nTnodes * tnodeSize);
559 mem = (__u8 *)newTnodes;
563 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
567 /* Hook them into the free list */
569 for (i = 0; i < nTnodes - 1; i++) {
570 newTnodes[i].internal[0] = &newTnodes[i + 1];
571 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
572 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
576 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
577 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
578 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
580 dev->freeTnodes = newTnodes;
582 /* New hookup for wide tnodes */
583 for(i = 0; i < nTnodes -1; i++) {
584 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
585 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
586 curr->internal[0] = next;
589 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
590 curr->internal[0] = dev->freeTnodes;
591 dev->freeTnodes = (yaffs_Tnode *)mem;
596 dev->nFreeTnodes += nTnodes;
597 dev->nTnodesCreated += nTnodes;
599 /* Now add this bunch of tnodes to a list for freeing up.
600 * NB If we can't add this to the management list it isn't fatal
601 * but it just means we can't free this bunch of tnodes later.
604 tnl = YMALLOC(sizeof(yaffs_TnodeList));
608 ("yaffs: Could not add tnodes to management list" TENDSTR)));
611 tnl->tnodes = newTnodes;
612 tnl->next = dev->allocatedTnodeList;
613 dev->allocatedTnodeList = tnl;
616 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
621 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
623 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
625 yaffs_Tnode *tn = NULL;
627 /* If there are none left make more */
628 if (!dev->freeTnodes) {
629 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
632 if (dev->freeTnodes) {
633 tn = dev->freeTnodes;
634 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
635 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
636 /* Hoosterman, this thing looks like it isn't in the list */
637 T(YAFFS_TRACE_ALWAYS,
638 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
641 dev->freeTnodes = dev->freeTnodes->internal[0];
644 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
650 /* FreeTnode frees up a tnode and puts it back on the free list */
651 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
654 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
655 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
656 /* Hoosterman, this thing looks like it is already in the list */
657 T(YAFFS_TRACE_ALWAYS,
658 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
660 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
662 tn->internal[0] = dev->freeTnodes;
663 dev->freeTnodes = tn;
668 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
670 /* Free the list of allocated tnodes */
671 yaffs_TnodeList *tmp;
673 while (dev->allocatedTnodeList) {
674 tmp = dev->allocatedTnodeList->next;
676 YFREE(dev->allocatedTnodeList->tnodes);
677 YFREE(dev->allocatedTnodeList);
678 dev->allocatedTnodeList = tmp;
682 dev->freeTnodes = NULL;
683 dev->nFreeTnodes = 0;
686 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
688 dev->allocatedTnodeList = NULL;
689 dev->freeTnodes = NULL;
690 dev->nFreeTnodes = 0;
691 dev->nTnodesCreated = 0;
696 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
698 __u32 *map = (__u32 *)tn;
704 pos &= YAFFS_TNODES_LEVEL0_MASK;
705 val >>= dev->chunkGroupBits;
707 bitInMap = pos * dev->tnodeWidth;
708 wordInMap = bitInMap /32;
709 bitInWord = bitInMap & (32 -1);
711 mask = dev->tnodeMask << bitInWord;
713 map[wordInMap] &= ~mask;
714 map[wordInMap] |= (mask & (val << bitInWord));
716 if(dev->tnodeWidth > (32-bitInWord)) {
717 bitInWord = (32 - bitInWord);
719 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
720 map[wordInMap] &= ~mask;
721 map[wordInMap] |= (mask & (val >> bitInWord));
725 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
727 __u32 *map = (__u32 *)tn;
733 pos &= YAFFS_TNODES_LEVEL0_MASK;
735 bitInMap = pos * dev->tnodeWidth;
736 wordInMap = bitInMap /32;
737 bitInWord = bitInMap & (32 -1);
739 val = map[wordInMap] >> bitInWord;
741 if(dev->tnodeWidth > (32-bitInWord)) {
742 bitInWord = (32 - bitInWord);
744 val |= (map[wordInMap] << bitInWord);
747 val &= dev->tnodeMask;
748 val <<= dev->chunkGroupBits;
753 /* ------------------- End of individual tnode manipulation -----------------*/
755 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
756 * The look up tree is represented by the top tnode and the number of topLevel
757 * in the tree. 0 means only the level 0 tnode is in the tree.
760 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
761 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
762 yaffs_FileStructure * fStruct,
766 yaffs_Tnode *tn = fStruct->top;
768 int requiredTallness;
769 int level = fStruct->topLevel;
771 /* Check sane level and chunk Id */
772 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
776 if (chunkId > YAFFS_MAX_CHUNK_ID) {
780 /* First check we're tall enough (ie enough topLevel) */
782 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
783 requiredTallness = 0;
785 i >>= YAFFS_TNODES_INTERNAL_BITS;
789 if (requiredTallness > fStruct->topLevel) {
790 /* Not tall enough, so we can't find it, return NULL. */
794 /* Traverse down to level 0 */
795 while (level > 0 && tn) {
798 ( YAFFS_TNODES_LEVEL0_BITS +
800 YAFFS_TNODES_INTERNAL_BITS)
802 YAFFS_TNODES_INTERNAL_MASK];
810 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
811 * This happens in two steps:
812 * 1. If the tree isn't tall enough, then make it taller.
813 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
815 * Used when modifying the tree.
818 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
819 yaffs_FileStructure * fStruct,
825 int requiredTallness;
832 /* Check sane level and page Id */
833 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
837 if (chunkId > YAFFS_MAX_CHUNK_ID) {
841 /* First check we're tall enough (ie enough topLevel) */
843 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
844 requiredTallness = 0;
846 x >>= YAFFS_TNODES_INTERNAL_BITS;
851 if (requiredTallness > fStruct->topLevel) {
852 /* Not tall enough,gotta make the tree taller */
853 for (i = fStruct->topLevel; i < requiredTallness; i++) {
855 tn = yaffs_GetTnode(dev);
858 tn->internal[0] = fStruct->top;
862 (TSTR("yaffs: no more tnodes" TENDSTR)));
866 fStruct->topLevel = requiredTallness;
869 /* Traverse down to level 0, adding anything we need */
871 l = fStruct->topLevel;
873 while (l > 0 && tn) {
875 ( YAFFS_TNODES_LEVEL0_BITS +
876 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
877 YAFFS_TNODES_INTERNAL_MASK;
880 if (!tn->internal[x])
881 tn->internal[x] = yaffs_GetTnode(dev);
883 tn = tn->internal[x];
891 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
892 yaffs_ExtendedTags * tags, int objectId,
897 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
898 if (yaffs_CheckChunkBit
899 (dev, theChunk / dev->nChunksPerBlock,
900 theChunk % dev->nChunksPerBlock)) {
901 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
903 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
915 /* DeleteWorker scans backwards through the tnode tree and deletes all the
916 * chunks and tnodes in the file
917 * Returns 1 if the tree was deleted.
918 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
921 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
922 int chunkOffset, int *limit)
927 yaffs_ExtendedTags tags;
929 yaffs_Device *dev = in->myDev;
936 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
938 if (tn->internal[i]) {
939 if (limit && (*limit) < 0) {
943 yaffs_DeleteWorker(in,
951 YAFFS_TNODES_INTERNAL_BITS)
959 tn->internal[i] = NULL;
964 return (allDone) ? 1 : 0;
965 } else if (level == 0) {
968 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
970 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
975 YAFFS_TNODES_LEVEL0_BITS) + i;
978 yaffs_FindChunkInGroup(dev,
984 if (foundChunk > 0) {
985 yaffs_DeleteChunk(dev,
998 yaffs_PutLevel0Tnode(dev,tn,i,0);
1002 return (i < 0) ? 1 : 0;
1012 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1015 yaffs_BlockInfo *theBlock;
1017 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1019 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1021 theBlock->softDeletions++;
1026 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1027 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1029 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1032 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1033 __u32 level, int chunkOffset)
1038 yaffs_Device *dev = in->myDev;
1043 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1045 if (tn->internal[i]) {
1047 yaffs_SoftDeleteWorker(in,
1053 YAFFS_TNODES_INTERNAL_BITS)
1056 yaffs_FreeTnode(dev,
1059 tn->internal[i] = NULL;
1061 /* Hoosterman... how could this happen? */
1065 return (allDone) ? 1 : 0;
1066 } else if (level == 0) {
1068 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1069 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1071 /* Note this does not find the real chunk, only the chunk group.
1072 * We make an assumption that a chunk group is not larger than
1075 yaffs_SoftDeleteChunk(dev, theChunk);
1076 yaffs_PutLevel0Tnode(dev,tn,i,0);
1090 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1093 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1094 if (obj->nDataChunks <= 0) {
1095 /* Empty file with no duplicate object headers, just delete it immediately */
1096 yaffs_FreeTnode(obj->myDev,
1097 obj->variant.fileVariant.top);
1098 obj->variant.fileVariant.top = NULL;
1099 T(YAFFS_TRACE_TRACING,
1100 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1102 yaffs_DoGenericObjectDeletion(obj);
1104 yaffs_SoftDeleteWorker(obj,
1105 obj->variant.fileVariant.top,
1106 obj->variant.fileVariant.
1108 obj->softDeleted = 1;
1113 /* Pruning removes any part of the file structure tree that is beyond the
1114 * bounds of the file (ie that does not point to chunks).
1116 * A file should only get pruned when its size is reduced.
1118 * Before pruning, the chunks must be pulled from the tree and the
1119 * level 0 tnode entries must be zeroed out.
1120 * Could also use this for file deletion, but that's probably better handled
1121 * by a special case.
1124 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1125 __u32 level, int del0)
1133 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1134 if (tn->internal[i] && level > 0) {
1136 yaffs_PruneWorker(dev, tn->internal[i],
1138 (i == 0) ? del0 : 1);
1141 if (tn->internal[i]) {
1146 if (hasData == 0 && del0) {
1147 /* Free and return NULL */
1149 yaffs_FreeTnode(dev, tn);
1159 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1160 yaffs_FileStructure * fStruct)
1167 if (fStruct->topLevel > 0) {
1169 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1171 /* Now we have a tree with all the non-zero branches NULL but the height
1172 * is the same as it was.
1173 * Let's see if we can trim internal tnodes to shorten the tree.
1174 * We can do this if only the 0th element in the tnode is in use
1175 * (ie all the non-zero are NULL)
1178 while (fStruct->topLevel && !done) {
1182 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1183 if (tn->internal[i]) {
1189 fStruct->top = tn->internal[0];
1190 fStruct->topLevel--;
1191 yaffs_FreeTnode(dev, tn);
1201 /*-------------------- End of File Structure functions.-------------------*/
1203 /* yaffs_CreateFreeObjects creates a bunch more objects and
1204 * adds them to the object free list.
1206 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1209 yaffs_Object *newObjects;
1210 yaffs_ObjectList *list;
1215 /* make these things */
1216 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1219 T(YAFFS_TRACE_ALLOCATE,
1220 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1224 /* Hook them into the free list */
1225 for (i = 0; i < nObjects - 1; i++) {
1226 newObjects[i].siblings.next =
1227 (struct list_head *)(&newObjects[i + 1]);
1230 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1231 dev->freeObjects = newObjects;
1232 dev->nFreeObjects += nObjects;
1233 dev->nObjectsCreated += nObjects;
1235 /* Now add this bunch of Objects to a list for freeing up. */
1237 list = YMALLOC(sizeof(yaffs_ObjectList));
1239 T(YAFFS_TRACE_ALLOCATE,
1240 (TSTR("Could not add objects to management list" TENDSTR)));
1242 list->objects = newObjects;
1243 list->next = dev->allocatedObjectList;
1244 dev->allocatedObjectList = list;
1251 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1252 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1254 yaffs_Object *tn = NULL;
1256 /* If there are none left make more */
1257 if (!dev->freeObjects) {
1258 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1261 if (dev->freeObjects) {
1262 tn = dev->freeObjects;
1264 (yaffs_Object *) (dev->freeObjects->siblings.next);
1265 dev->nFreeObjects--;
1267 /* Now sweeten it up... */
1269 memset(tn, 0, sizeof(yaffs_Object));
1272 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1273 INIT_LIST_HEAD(&(tn->hardLinks));
1274 INIT_LIST_HEAD(&(tn->hashLink));
1275 INIT_LIST_HEAD(&tn->siblings);
1277 /* Add it to the lost and found directory.
1278 * NB Can't put root or lostNFound in lostNFound so
1279 * check if lostNFound exists first
1281 if (dev->lostNFoundDir) {
1282 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1289 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1294 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1296 obj->fake = 1; /* it is fake so it has no NAND presence... */
1297 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1298 obj->unlinkAllowed = 0; /* ... or unlink it */
1301 obj->yst_mode = mode;
1303 obj->chunkId = 0; /* Not a valid chunk. */
1310 static void yaffs_UnhashObject(yaffs_Object * tn)
1313 yaffs_Device *dev = tn->myDev;
1315 /* If it is still linked into the bucket list, free from the list */
1316 if (!list_empty(&tn->hashLink)) {
1317 list_del_init(&tn->hashLink);
1318 bucket = yaffs_HashFunction(tn->objectId);
1319 dev->objectBucket[bucket].count--;
1324 /* FreeObject frees up a Object and puts it back on the free list */
1325 static void yaffs_FreeObject(yaffs_Object * tn)
1328 yaffs_Device *dev = tn->myDev;
1332 /* We're still hooked up to a cached inode.
1333 * Don't delete now, but mark for later deletion
1335 tn->deferedFree = 1;
1340 yaffs_UnhashObject(tn);
1342 /* Link into the free list. */
1343 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1344 dev->freeObjects = tn;
1345 dev->nFreeObjects++;
1350 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1352 if (obj->deferedFree) {
1353 yaffs_FreeObject(obj);
1359 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1361 /* Free the list of allocated Objects */
1363 yaffs_ObjectList *tmp;
1365 while (dev->allocatedObjectList) {
1366 tmp = dev->allocatedObjectList->next;
1367 YFREE(dev->allocatedObjectList->objects);
1368 YFREE(dev->allocatedObjectList);
1370 dev->allocatedObjectList = tmp;
1373 dev->freeObjects = NULL;
1374 dev->nFreeObjects = 0;
1377 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1381 dev->allocatedObjectList = NULL;
1382 dev->freeObjects = NULL;
1383 dev->nFreeObjects = 0;
1385 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1386 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1387 dev->objectBucket[i].count = 0;
1392 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1397 int lowest = 999999;
1399 /* First let's see if we can find one that's empty. */
1401 for (i = 0; i < 10 && lowest > 0; i++) {
1403 x %= YAFFS_NOBJECT_BUCKETS;
1404 if (dev->objectBucket[x].count < lowest) {
1405 lowest = dev->objectBucket[x].count;
1411 /* If we didn't find an empty list, then try
1412 * looking a bit further for a short one
1415 for (i = 0; i < 10 && lowest > 3; i++) {
1417 x %= YAFFS_NOBJECT_BUCKETS;
1418 if (dev->objectBucket[x].count < lowest) {
1419 lowest = dev->objectBucket[x].count;
1428 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1430 int bucket = yaffs_FindNiceObjectBucket(dev);
1432 /* Now find an object value that has not already been taken
1433 * by scanning the list.
1437 struct list_head *i;
1439 __u32 n = (__u32) bucket;
1441 /* yaffs_CheckObjectHashSanity(); */
1445 n += YAFFS_NOBJECT_BUCKETS;
1446 if (1 || dev->objectBucket[bucket].count > 0) {
1447 list_for_each(i, &dev->objectBucket[bucket].list) {
1448 /* If there is already one in the list */
1450 && list_entry(i, yaffs_Object,
1451 hashLink)->objectId == n) {
1462 static void yaffs_HashObject(yaffs_Object * in)
1464 int bucket = yaffs_HashFunction(in->objectId);
1465 yaffs_Device *dev = in->myDev;
1467 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1468 dev->objectBucket[bucket].count++;
1472 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1474 int bucket = yaffs_HashFunction(number);
1475 struct list_head *i;
1478 list_for_each(i, &dev->objectBucket[bucket].list) {
1479 /* Look if it is in the list */
1481 in = list_entry(i, yaffs_Object, hashLink);
1482 if (in->objectId == number) {
1484 /* Don't tell the VFS about this one if it is defered free */
1485 if (in->deferedFree)
1497 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1498 yaffs_ObjectType type)
1501 yaffs_Object *theObject;
1504 number = yaffs_CreateNewObjectNumber(dev);
1507 theObject = yaffs_AllocateEmptyObject(dev);
1510 theObject->fake = 0;
1511 theObject->renameAllowed = 1;
1512 theObject->unlinkAllowed = 1;
1513 theObject->objectId = number;
1514 yaffs_HashObject(theObject);
1515 theObject->variantType = type;
1516 #ifdef CONFIG_YAFFS_WINCE
1517 yfsd_WinFileTimeNow(theObject->win_atime);
1518 theObject->win_ctime[0] = theObject->win_mtime[0] =
1519 theObject->win_atime[0];
1520 theObject->win_ctime[1] = theObject->win_mtime[1] =
1521 theObject->win_atime[1];
1525 theObject->yst_atime = theObject->yst_mtime =
1526 theObject->yst_ctime = Y_CURRENT_TIME;
1529 case YAFFS_OBJECT_TYPE_FILE:
1530 theObject->variant.fileVariant.fileSize = 0;
1531 theObject->variant.fileVariant.scannedFileSize = 0;
1532 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1533 theObject->variant.fileVariant.topLevel = 0;
1534 theObject->variant.fileVariant.top =
1535 yaffs_GetTnode(dev);
1537 case YAFFS_OBJECT_TYPE_DIRECTORY:
1538 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1541 case YAFFS_OBJECT_TYPE_SYMLINK:
1542 case YAFFS_OBJECT_TYPE_HARDLINK:
1543 case YAFFS_OBJECT_TYPE_SPECIAL:
1544 /* No action required */
1546 case YAFFS_OBJECT_TYPE_UNKNOWN:
1547 /* todo this should not happen */
1555 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1557 yaffs_ObjectType type)
1559 yaffs_Object *theObject = NULL;
1562 theObject = yaffs_FindObjectByNumber(dev, number);
1566 theObject = yaffs_CreateNewObject(dev, number, type);
1573 static YCHAR *yaffs_CloneString(const YCHAR * str)
1575 YCHAR *newStr = NULL;
1578 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1579 yaffs_strcpy(newStr, str);
1587 * Mknod (create) a new object.
1588 * equivalentObject only has meaning for a hard link;
1589 * aliasString only has meaning for a sumlink.
1590 * rdev only has meaning for devices (a subset of special objects)
1593 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1594 yaffs_Object * parent,
1599 yaffs_Object * equivalentObject,
1600 const YCHAR * aliasString, __u32 rdev)
1604 yaffs_Device *dev = parent->myDev;
1606 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1607 if (yaffs_FindObjectByName(parent, name)) {
1611 in = yaffs_CreateNewObject(dev, -1, type);
1616 in->variantType = type;
1618 in->yst_mode = mode;
1620 #ifdef CONFIG_YAFFS_WINCE
1621 yfsd_WinFileTimeNow(in->win_atime);
1622 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1623 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1626 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1628 in->yst_rdev = rdev;
1632 in->nDataChunks = 0;
1634 yaffs_SetObjectName(in, name);
1637 yaffs_AddObjectToDirectory(parent, in);
1639 in->myDev = parent->myDev;
1642 case YAFFS_OBJECT_TYPE_SYMLINK:
1643 in->variant.symLinkVariant.alias =
1644 yaffs_CloneString(aliasString);
1646 case YAFFS_OBJECT_TYPE_HARDLINK:
1647 in->variant.hardLinkVariant.equivalentObject =
1649 in->variant.hardLinkVariant.equivalentObjectId =
1650 equivalentObject->objectId;
1651 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1653 case YAFFS_OBJECT_TYPE_FILE:
1654 case YAFFS_OBJECT_TYPE_DIRECTORY:
1655 case YAFFS_OBJECT_TYPE_SPECIAL:
1656 case YAFFS_OBJECT_TYPE_UNKNOWN:
1661 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1662 /* Could not create the object header, fail the creation */
1663 yaffs_DestroyObject(in);
1672 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1673 __u32 mode, __u32 uid, __u32 gid)
1675 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1676 uid, gid, NULL, NULL, 0);
1679 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1680 __u32 mode, __u32 uid, __u32 gid)
1682 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1683 mode, uid, gid, NULL, NULL, 0);
1686 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1687 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1689 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1690 uid, gid, NULL, NULL, rdev);
1693 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1694 __u32 mode, __u32 uid, __u32 gid,
1695 const YCHAR * alias)
1697 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1698 uid, gid, NULL, alias, 0);
1701 /* yaffs_Link returns the object id of the equivalent object.*/
1702 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1703 yaffs_Object * equivalentObject)
1705 /* Get the real object in case we were fed a hard link as an equivalent object */
1706 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1708 if (yaffs_MknodObject
1709 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1710 equivalentObject, NULL, 0)) {
1711 return equivalentObject;
1718 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1719 const YCHAR * newName, int force, int shadows)
1724 yaffs_Object *existingTarget;
1726 if (newDir == NULL) {
1727 newDir = obj->parent; /* use the old directory */
1730 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1731 T(YAFFS_TRACE_ALWAYS,
1733 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1738 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1739 if (obj->myDev->isYaffs2) {
1740 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1742 unlinkOp = (newDir == obj->myDev->unlinkedDir
1743 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1746 deleteOp = (newDir == obj->myDev->deletedDir);
1748 existingTarget = yaffs_FindObjectByName(newDir, newName);
1750 /* If the object is a file going into the unlinked directory,
1751 * then it is OK to just stuff it in since duplicate names are allowed.
1752 * else only proceed if the new name does not exist and if we're putting
1753 * it into a directory.
1760 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1761 yaffs_SetObjectName(obj, newName);
1764 yaffs_AddObjectToDirectory(newDir, obj);
1769 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1770 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1777 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1778 yaffs_Object * newDir, const YCHAR * newName)
1781 yaffs_Object *existingTarget;
1784 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1785 /* Special case for case insemsitive systems (eg. WinCE).
1786 * While look-up is case insensitive, the name isn't.
1787 * Therefore we might want to change x.txt to X.txt
1789 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1794 obj = yaffs_FindObjectByName(oldDir, oldName);
1796 if (obj && obj->renameAllowed) {
1798 /* Now do the handling for an existing target, if there is one */
1800 existingTarget = yaffs_FindObjectByName(newDir, newName);
1801 if (existingTarget &&
1802 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1803 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1804 /* There is a target that is a non-empty directory, so we fail */
1805 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1806 } else if (existingTarget && existingTarget != obj) {
1807 /* Nuke the target first, using shadowing,
1808 * but only if it isn't the same object
1810 yaffs_ChangeObjectName(obj, newDir, newName, force,
1811 existingTarget->objectId);
1812 yaffs_UnlinkObject(existingTarget);
1815 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1820 /*------------------------- Block Management and Page Allocation ----------------*/
1822 static int yaffs_InitialiseBlocks(yaffs_Device * dev, int nBlocks)
1824 dev->allocationBlock = -1; /* force it to get a new one */
1826 /* Todo we're assuming the malloc will pass. */
1827 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1828 if(!dev->blockInfo){
1829 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1830 dev->blockInfoAlt = 1;
1833 dev->blockInfoAlt = 0;
1835 /* Set up dynamic blockinfo stuff. */
1836 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8;
1837 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1838 if(!dev->chunkBits){
1839 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1840 dev->chunkBitsAlt = 1;
1843 dev->chunkBitsAlt = 0;
1845 if (dev->blockInfo && dev->chunkBits) {
1846 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1847 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1855 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1857 if(dev->blockInfoAlt)
1858 YFREE_ALT(dev->blockInfo);
1860 YFREE(dev->blockInfo);
1861 dev->blockInfoAlt = 0;
1863 dev->blockInfo = NULL;
1865 if(dev->chunkBitsAlt)
1866 YFREE_ALT(dev->chunkBits);
1868 YFREE(dev->chunkBits);
1869 dev->chunkBitsAlt = 0;
1870 dev->chunkBits = NULL;
1873 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1874 yaffs_BlockInfo * bi)
1881 return 1; /* disqualification only applies to yaffs2. */
1883 if (!bi->hasShrinkHeader)
1884 return 1; /* can gc */
1886 /* Find the oldest dirty sequence number if we don't know it and save it
1887 * so we don't have to keep recomputing it.
1889 if (!dev->oldestDirtySequence) {
1890 seq = dev->sequenceNumber;
1892 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1894 b = yaffs_GetBlockInfo(dev, i);
1895 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1896 (b->pagesInUse - b->softDeletions) <
1897 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1898 seq = b->sequenceNumber;
1901 dev->oldestDirtySequence = seq;
1904 /* Can't do gc of this block if there are any blocks older than this one that have
1907 return (bi->sequenceNumber <= dev->oldestDirtySequence);
1913 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1914 * for garbage collection.
1917 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1921 int b = dev->currentDirtyChecker;
1927 yaffs_BlockInfo *bi;
1928 static int nonAggressiveSkip = 0;
1930 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1932 * else (we're doing a leasurely gc), then we only bother to do this if the
1933 * block has only a few pages in use.
1936 nonAggressiveSkip--;
1938 if (!aggressive && (nonAggressiveSkip > 0)) {
1943 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1947 dev->internalEndBlock - dev->internalStartBlock + 1;
1950 dev->internalEndBlock - dev->internalStartBlock + 1;
1951 iterations = iterations / 16;
1952 if (iterations > 200) {
1957 for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1959 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1960 b = dev->internalStartBlock;
1963 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1964 T(YAFFS_TRACE_ERROR,
1965 (TSTR("**>> Block %d is not valid" TENDSTR), b));
1969 bi = yaffs_GetBlockInfo(dev, b);
1971 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1972 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1973 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1975 pagesInUse = (bi->pagesInUse - bi->softDeletions);
1979 dev->currentDirtyChecker = b;
1983 (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1984 dev->nChunksPerBlock - pagesInUse));
1987 dev->oldestDirtySequence = 0;
1990 nonAggressiveSkip = 4;
1996 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1998 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2002 /* If the block is still healthy erase it and mark as clean.
2003 * If the block has had a data failure, then retire it.
2005 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2007 if (!bi->needsRetiring) {
2008 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2010 dev->nErasureFailures++;
2011 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2012 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2016 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2018 for (i = 0; i < dev->nChunksPerBlock; i++) {
2019 if (!yaffs_CheckChunkErased
2020 (dev, blockNo * dev->nChunksPerBlock + i)) {
2021 T(YAFFS_TRACE_ERROR,
2023 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2024 TENDSTR), blockNo, i));
2030 /* Clean it up... */
2031 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2032 dev->nErasedBlocks++;
2034 bi->softDeletions = 0;
2035 bi->hasShrinkHeader = 0;
2036 yaffs_ClearChunkBits(dev, blockNo);
2038 T(YAFFS_TRACE_ERASE,
2039 (TSTR("Erased block %d" TENDSTR), blockNo));
2041 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2043 yaffs_RetireBlock(dev, blockNo);
2044 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2045 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2049 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2053 yaffs_BlockInfo *bi;
2055 if (dev->nErasedBlocks < 1) {
2056 /* Hoosterman we've got a problem.
2057 * Can't get space to gc
2059 T(YAFFS_TRACE_ERROR,
2060 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2065 /* Find an empty block. */
2067 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2068 dev->allocationBlockFinder++;
2069 if (dev->allocationBlockFinder < dev->internalStartBlock
2070 || dev->allocationBlockFinder > dev->internalEndBlock) {
2071 dev->allocationBlockFinder = dev->internalStartBlock;
2074 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2076 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2077 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2078 dev->sequenceNumber++;
2079 bi->sequenceNumber = dev->sequenceNumber;
2080 dev->nErasedBlocks--;
2081 T(YAFFS_TRACE_ALLOCATE,
2082 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2083 dev->allocationBlockFinder, dev->sequenceNumber,
2084 dev->nErasedBlocks));
2085 return dev->allocationBlockFinder;
2089 T(YAFFS_TRACE_ALWAYS,
2091 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2092 TENDSTR), dev->nErasedBlocks));
2099 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2101 int reservedChunks = (dev->nReservedBlocks * dev->nChunksPerBlock);
2102 return (dev->nFreeChunks > reservedChunks);
2105 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2108 yaffs_BlockInfo *bi;
2110 if (dev->allocationBlock < 0) {
2111 /* Get next block to allocate off */
2112 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2113 dev->allocationPage = 0;
2116 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2117 /* Not enough space to allocate unless we're allowed to use the reserve. */
2121 if (dev->nErasedBlocks < dev->nReservedBlocks
2122 && dev->allocationPage == 0) {
2123 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2126 /* Next page please.... */
2127 if (dev->allocationBlock >= 0) {
2128 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2130 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2131 dev->allocationPage;
2133 yaffs_SetChunkBit(dev, dev->allocationBlock,
2134 dev->allocationPage);
2136 dev->allocationPage++;
2140 /* If the block is full set the state to full */
2141 if (dev->allocationPage >= dev->nChunksPerBlock) {
2142 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2143 dev->allocationBlock = -1;
2149 T(YAFFS_TRACE_ERROR,
2150 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2155 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2159 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2161 if (dev->allocationBlock > 0) {
2162 n += (dev->nChunksPerBlock - dev->allocationPage);
2169 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2175 int retVal = YAFFS_OK;
2179 int chunksBefore = yaffs_GetErasedChunks(dev);
2182 yaffs_ExtendedTags tags;
2184 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2186 yaffs_Object *object;
2188 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2190 T(YAFFS_TRACE_TRACING,
2191 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2192 bi->pagesInUse, bi->hasShrinkHeader));
2194 /*yaffs_VerifyFreeChunks(dev); */
2196 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2198 /* Take off the number of soft deleted entries because
2199 * they're going to get really deleted during GC.
2201 dev->nFreeChunks -= bi->softDeletions;
2205 if (!yaffs_StillSomeChunkBits(dev, block)) {
2206 T(YAFFS_TRACE_TRACING,
2208 ("Collecting block %d that has no chunks in use" TENDSTR),
2210 yaffs_BlockBecameDirty(dev, block);
2213 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2215 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2216 chunkInBlock < dev->nChunksPerBlock
2217 && yaffs_StillSomeChunkBits(dev, block);
2218 chunkInBlock++, oldChunk++) {
2219 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2221 /* This page is in use and might need to be copied off */
2225 yaffs_InitialiseTags(&tags);
2227 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2231 yaffs_FindObjectByNumber(dev,
2234 T(YAFFS_TRACE_GC_DETAIL,
2236 ("Collecting page %d, %d %d %d " TENDSTR),
2237 chunkInBlock, tags.objectId, tags.chunkId,
2241 T(YAFFS_TRACE_ERROR,
2243 ("page %d in gc has no object "
2244 TENDSTR), oldChunk));
2247 if (object && object->deleted
2248 && tags.chunkId != 0) {
2249 /* Data chunk in a deleted file, throw it away
2250 * It's a soft deleted data chunk,
2251 * No need to copy this, just forget about it and
2252 * fix up the object.
2255 object->nDataChunks--;
2257 if (object->nDataChunks <= 0) {
2258 /* remeber to clean up the object */
2259 dev->gcCleanupList[cleanups] =
2265 /* Todo object && object->deleted && object->nDataChunks == 0 */
2267 /* Deleted object header with no data chunks.
2268 * Can be discarded and the file deleted.
2270 object->chunkId = 0;
2271 yaffs_FreeTnode(object->myDev,
2274 object->variant.fileVariant.top = NULL;
2275 yaffs_DoGenericObjectDeletion(object);
2277 } else if (object) {
2278 /* It's either a data chunk in a live file or
2279 * an ObjectHeader, so we're interested in it.
2280 * NB Need to keep the ObjectHeaders of deleted files
2281 * until the whole file has been deleted off
2283 tags.serialNumber++;
2287 if (tags.chunkId == 0) {
2288 /* It is an object Id,
2289 * We need to nuke the shrinkheader flags first
2290 * We no longer want the shrinkHeader flag since its work is done
2291 * and if it is left in place it will mess up scanning.
2292 * Also, clear out any shadowing stuff
2295 yaffs_ObjectHeader *oh;
2296 oh = (yaffs_ObjectHeader *)buffer;
2298 oh->shadowsObject = -1;
2299 tags.extraShadows = 0;
2300 tags.extraIsShrinkHeader = 0;
2304 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2307 retVal = YAFFS_FAIL;
2310 /* Ok, now fix up the Tnodes etc. */
2312 if (tags.chunkId == 0) {
2314 object->chunkId = newChunk;
2315 object->serial = tags.serialNumber;
2317 /* It's a data chunk */
2318 yaffs_PutChunkIntoFile
2326 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2331 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2334 /* Do any required cleanups */
2335 for (i = 0; i < cleanups; i++) {
2336 /* Time to delete the file too */
2338 yaffs_FindObjectByNumber(dev,
2339 dev->gcCleanupList[i]);
2341 yaffs_FreeTnode(dev,
2342 object->variant.fileVariant.
2344 object->variant.fileVariant.top = NULL;
2347 ("yaffs: About to finally delete object %d"
2348 TENDSTR), object->objectId));
2349 yaffs_DoGenericObjectDeletion(object);
2350 object->myDev->nDeletedFiles--;
2357 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2360 ("gc did not increase free chunks before %d after %d"
2361 TENDSTR), chunksBefore, chunksAfter));
2369 /* New garbage collector
2370 * If we're very low on erased blocks then we do aggressive garbage collection
2371 * otherwise we do "leasurely" garbage collection.
2372 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2373 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2375 * The idea is to help clear out space in a more spread-out manner.
2376 * Dunno if it really does anything useful.
2378 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2382 int gcOk = YAFFS_OK;
2385 if (dev->isDoingGC) {
2386 /* Bail out so we don't get recursive gc */
2390 /* This loop should pass the first time.
2391 * We'll only see looping here if the erase of the collected block fails.
2396 if (dev->nErasedBlocks < dev->nReservedBlocks) {
2397 /* We need a block soon...*/
2400 /* We're in no hurry */
2404 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2407 dev->garbageCollections++;
2409 dev->passiveGarbageCollections++;
2414 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2415 dev->nErasedBlocks, aggressive));
2417 gcOk = yaffs_GarbageCollectBlock(dev, block);
2420 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2423 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2424 TENDSTR), dev->nErasedBlocks, maxTries, block));
2426 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2429 return aggressive ? gcOk : YAFFS_OK;
2432 /*------------------------- TAGS --------------------------------*/
2434 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2437 return (tags->chunkId == chunkInObject &&
2438 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2443 /*-------------------- Data file manipulation -----------------*/
2445 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2446 yaffs_ExtendedTags * tags)
2448 /*Get the Tnode, then get the level 0 offset chunk offset */
2451 yaffs_ExtendedTags localTags;
2454 yaffs_Device *dev = in->myDev;
2457 /* Passed a NULL, so use our own tags space */
2461 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2464 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2467 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2473 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2474 yaffs_ExtendedTags * tags)
2476 /* Get the Tnode, then get the level 0 offset chunk offset */
2479 yaffs_ExtendedTags localTags;
2481 yaffs_Device *dev = in->myDev;
2485 /* Passed a NULL, so use our own tags space */
2489 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2493 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2496 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2499 /* Delete the entry in the filestructure (if found) */
2501 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2504 /*T(("No level 0 found for %d\n", chunkInInode)); */
2508 /* T(("Could not find %d to delete\n",chunkInInode)); */
2513 #ifdef YAFFS_PARANOID
2515 static int yaffs_CheckFileSanity(yaffs_Object * in)
2523 yaffs_Tags localTags;
2524 yaffs_Tags *tags = &localTags;
2528 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2529 /* T(("Object not a file\n")); */
2533 objId = in->objectId;
2534 fSize = in->variant.fileVariant.fileSize;
2536 (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2538 for (chunk = 1; chunk <= nChunks; chunk++) {
2539 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2544 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2546 if (yaffs_CheckChunkBits
2547 (dev, theChunk / dev->nChunksPerBlock,
2548 theChunk % dev->nChunksPerBlock)) {
2550 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2554 (tags, in->objectId, chunk, chunkDeleted)) {
2564 /* T(("No level 0 found for %d\n", chunk)); */
2568 return failed ? YAFFS_FAIL : YAFFS_OK;
2573 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2574 int chunkInNAND, int inScan)
2576 /* NB inScan is zero unless scanning.
2577 * For forward scanning, inScan is > 0;
2578 * for backward scanning inScan is < 0
2582 yaffs_Device *dev = in->myDev;
2584 yaffs_ExtendedTags existingTags;
2585 yaffs_ExtendedTags newTags;
2586 unsigned existingSerial, newSerial;
2588 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2589 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2590 * If it is not during Scanning then something went wrong!
2593 T(YAFFS_TRACE_ERROR,
2595 ("yaffs tragedy:attempt to put data chunk into a non-file"
2600 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2604 tn = yaffs_AddOrFindLevel0Tnode(dev, &in->variant.fileVariant,
2610 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2613 /* If we're scanning then we need to test for duplicates
2614 * NB This does not need to be efficient since it should only ever
2615 * happen when the power fails during a write, then only one
2616 * chunk should ever be affected.
2618 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2619 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2622 if (existingChunk != 0) {
2623 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2624 * thus we have to do a FindChunkInFile to get the real chunk id.
2626 * We have a duplicate now we need to decide which one to use:
2628 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2629 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2630 * YAFFS1: Get both sets of tags and compare serial numbers.
2634 /* Only do this for forward scanning */
2635 yaffs_ReadChunkWithTagsFromNAND(dev,
2639 /* Do a proper find */
2641 yaffs_FindChunkInFile(in, chunkInInode,
2645 if (existingChunk <= 0) {
2646 /*Hoosterman - how did this happen? */
2648 T(YAFFS_TRACE_ERROR,
2650 ("yaffs tragedy: existing chunk < 0 in scan"
2655 /* NB The deleted flags should be false, otherwise the chunks will
2656 * not be loaded during a scan
2659 newSerial = newTags.serialNumber;
2660 existingSerial = existingTags.serialNumber;
2663 (in->myDev->isYaffs2 ||
2664 existingChunk <= 0 ||
2665 ((existingSerial + 1) & 3) == newSerial)) {
2666 /* Forward scanning.
2668 * Delete the old one and drop through to update the tnode
2670 yaffs_DeleteChunk(dev, existingChunk, 1,
2673 /* Backward scanning or we want to use the existing one
2675 * Delete the new one and return early so that the tnode isn't changed
2677 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2685 if (existingChunk == 0) {
2689 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2694 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2697 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2699 if (chunkInNAND >= 0) {
2700 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2703 T(YAFFS_TRACE_NANDACCESS,
2704 (TSTR("Chunk %d not found zero instead" TENDSTR),
2706 /* get sane (zero) data if you read a hole */
2707 memset(buffer, 0, in->myDev->nBytesPerChunk);
2713 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2717 yaffs_ExtendedTags tags;
2718 yaffs_BlockInfo *bi;
2724 block = chunkId / dev->nChunksPerBlock;
2725 page = chunkId % dev->nChunksPerBlock;
2727 bi = yaffs_GetBlockInfo(dev, block);
2729 T(YAFFS_TRACE_DELETION,
2730 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2733 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2735 yaffs_InitialiseTags(&tags);
2737 tags.chunkDeleted = 1;
2739 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2740 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2742 dev->nUnmarkedDeletions++;
2745 /* Pull out of the management area.
2746 * If the whole block became dirty, this will kick off an erasure.
2748 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2749 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2750 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2751 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2754 yaffs_ClearChunkBit(dev, block, page);
2758 if (bi->pagesInUse == 0 &&
2759 !bi->hasShrinkHeader &&
2760 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2761 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2762 yaffs_BlockBecameDirty(dev, block);
2766 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2771 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2772 const __u8 * buffer, int nBytes,
2775 /* Find old chunk Need to do this to get serial number
2776 * Write new one and patch into tree.
2777 * Invalidate old tags.
2781 yaffs_ExtendedTags prevTags;
2784 yaffs_ExtendedTags newTags;
2786 yaffs_Device *dev = in->myDev;
2788 yaffs_CheckGarbageCollection(dev);
2790 /* Get the previous chunk at this location in the file if it exists */
2791 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2793 /* Set up new tags */
2794 yaffs_InitialiseTags(&newTags);
2796 newTags.chunkId = chunkInInode;
2797 newTags.objectId = in->objectId;
2798 newTags.serialNumber =
2799 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2800 newTags.byteCount = nBytes;
2803 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2806 if (newChunkId >= 0) {
2807 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2809 if (prevChunkId >= 0) {
2810 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2814 yaffs_CheckFileSanity(in);
2820 /* UpdateObjectHeader updates the header on NAND for an object.
2821 * If name is not NULL, then that new name is used.
2823 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2824 int isShrink, int shadows)
2827 yaffs_BlockInfo *bi;
2829 yaffs_Device *dev = in->myDev;
2835 yaffs_ExtendedTags newTags;
2837 __u8 *buffer = NULL;
2838 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2840 yaffs_ObjectHeader *oh = NULL;
2842 if (!in->fake || force) {
2844 yaffs_CheckGarbageCollection(dev);
2846 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2847 oh = (yaffs_ObjectHeader *) buffer;
2849 prevChunkId = in->chunkId;
2851 if (prevChunkId >= 0) {
2852 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2854 memcpy(oldName, oh->name, sizeof(oh->name));
2857 memset(buffer, 0xFF, dev->nBytesPerChunk);
2859 oh->type = in->variantType;
2860 oh->yst_mode = in->yst_mode;
2861 oh->shadowsObject = shadows;
2863 #ifdef CONFIG_YAFFS_WINCE
2864 oh->win_atime[0] = in->win_atime[0];
2865 oh->win_ctime[0] = in->win_ctime[0];
2866 oh->win_mtime[0] = in->win_mtime[0];
2867 oh->win_atime[1] = in->win_atime[1];
2868 oh->win_ctime[1] = in->win_ctime[1];
2869 oh->win_mtime[1] = in->win_mtime[1];
2871 oh->yst_uid = in->yst_uid;
2872 oh->yst_gid = in->yst_gid;
2873 oh->yst_atime = in->yst_atime;
2874 oh->yst_mtime = in->yst_mtime;
2875 oh->yst_ctime = in->yst_ctime;
2876 oh->yst_rdev = in->yst_rdev;
2879 oh->parentObjectId = in->parent->objectId;
2881 oh->parentObjectId = 0;
2884 if (name && *name) {
2885 memset(oh->name, 0, sizeof(oh->name));
2886 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2887 } else if (prevChunkId) {
2888 memcpy(oh->name, oldName, sizeof(oh->name));
2890 memset(oh->name, 0, sizeof(oh->name));
2893 oh->isShrink = isShrink;
2895 switch (in->variantType) {
2896 case YAFFS_OBJECT_TYPE_UNKNOWN:
2897 /* Should not happen */
2899 case YAFFS_OBJECT_TYPE_FILE:
2901 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2902 || oh->parentObjectId ==
2903 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2904 fileVariant.fileSize;
2906 case YAFFS_OBJECT_TYPE_HARDLINK:
2907 oh->equivalentObjectId =
2908 in->variant.hardLinkVariant.equivalentObjectId;
2910 case YAFFS_OBJECT_TYPE_SPECIAL:
2913 case YAFFS_OBJECT_TYPE_DIRECTORY:
2916 case YAFFS_OBJECT_TYPE_SYMLINK:
2917 yaffs_strncpy(oh->alias,
2918 in->variant.symLinkVariant.alias,
2919 YAFFS_MAX_ALIAS_LENGTH);
2920 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2925 yaffs_InitialiseTags(&newTags);
2927 newTags.chunkId = 0;
2928 newTags.objectId = in->objectId;
2929 newTags.serialNumber = in->serial;
2931 /* Add extra info for file header */
2933 newTags.extraHeaderInfoAvailable = 1;
2934 newTags.extraParentObjectId = oh->parentObjectId;
2935 newTags.extraFileLength = oh->fileSize;
2936 newTags.extraIsShrinkHeader = oh->isShrink;
2937 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2938 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2939 newTags.extraObjectType = in->variantType;
2941 /* Create new chunk in NAND */
2943 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2944 (prevChunkId >= 0) ? 1 : 0);
2946 if (newChunkId >= 0) {
2948 in->chunkId = newChunkId;
2950 if (prevChunkId >= 0) {
2951 yaffs_DeleteChunk(dev, prevChunkId, 1,
2957 /* If this was a shrink, then mark the block that the chunk lives on */
2959 bi = yaffs_GetBlockInfo(in->myDev,
2960 newChunkId /in->myDev-> nChunksPerBlock);
2961 bi->hasShrinkHeader = 1;
2966 retVal = newChunkId;
2971 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2976 /*------------------------ Short Operations Cache ----------------------------------------
2977 * In many situations where there is no high level buffering (eg WinCE) a lot of
2978 * reads might be short sequential reads, and a lot of writes may be short
2979 * sequential writes. eg. scanning/writing a jpeg file.
2980 * In these cases, a short read/write cache can provide a huge perfomance benefit
2981 * with dumb-as-a-rock code.
2982 * In Linux, the page cache provides read buffering aand the short op cache provides write
2985 * There are a limited number (~10) of cache chunks per device so that we don't
2986 * need a very intelligent search.
2989 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2991 yaffs_Device *dev = obj->myDev;
2992 int lowest = -99; /* Stop compiler whining. */
2994 yaffs_ChunkCache *cache;
2995 int chunkWritten = 0;
2996 int nCaches = obj->myDev->nShortOpCaches;
3002 /* Find the dirty cache for this object with the lowest chunk id. */
3003 for (i = 0; i < nCaches; i++) {
3004 if (dev->srCache[i].object == obj &&
3005 dev->srCache[i].dirty) {
3007 || dev->srCache[i].chunkId <
3009 cache = &dev->srCache[i];
3010 lowest = cache->chunkId;
3015 if (cache && !cache->locked) {
3016 /* Write it out and free it up */
3019 yaffs_WriteChunkDataToObject(cache->object,
3025 cache->object = NULL;
3028 } while (cache && chunkWritten > 0);
3031 /* Hoosterman, disk full while writing cache out. */
3032 T(YAFFS_TRACE_ERROR,
3033 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3040 /* Grab us a cache chunk for use.
3041 * First look for an empty one.
3042 * Then look for the least recently used non-dirty one.
3043 * Then look for the least recently used dirty one...., flush and look again.
3045 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3051 if (dev->nShortOpCaches > 0) {
3052 for (i = 0; i < dev->nShortOpCaches; i++) {
3053 if (!dev->srCache[i].object)
3054 return &dev->srCache[i];
3060 usage = 0; /* just to stop the compiler grizzling */
3062 for (i = 0; i < dev->nShortOpCaches; i++) {
3063 if (!dev->srCache[i].dirty &&
3064 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3066 usage = dev->srCache[i].lastUse;
3072 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3079 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3081 yaffs_ChunkCache *cache;
3082 yaffs_Object *theObj;
3087 if (dev->nShortOpCaches > 0) {
3088 /* Try find a non-dirty one... */
3090 cache = yaffs_GrabChunkCacheWorker(dev);
3093 /* They were all dirty, find the last recently used object and flush
3094 * its cache, then find again.
3095 * NB what's here is not very accurate, we actually flush the object
3096 * the last recently used page.
3099 /* With locking we can't assume we can use entry zero */
3106 for (i = 0; i < dev->nShortOpCaches; i++) {
3107 if (dev->srCache[i].object &&
3108 !dev->srCache[i].locked &&
3109 (dev->srCache[i].lastUse < usage || !cache))
3111 usage = dev->srCache[i].lastUse;
3112 theObj = dev->srCache[i].object;
3113 cache = &dev->srCache[i];
3118 if (!cache || cache->dirty) {
3119 /* Flush and try again */
3120 yaffs_FlushFilesChunkCache(theObj);
3121 cache = yaffs_GrabChunkCacheWorker(dev);
3131 /* Find a cached chunk */
3132 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3135 yaffs_Device *dev = obj->myDev;
3137 if (dev->nShortOpCaches > 0) {
3138 for (i = 0; i < dev->nShortOpCaches; i++) {
3139 if (dev->srCache[i].object == obj &&
3140 dev->srCache[i].chunkId == chunkId) {
3143 return &dev->srCache[i];
3150 /* Mark the chunk for the least recently used algorithym */
3151 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3155 if (dev->nShortOpCaches > 0) {
3156 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3157 /* Reset the cache usages */
3159 for (i = 1; i < dev->nShortOpCaches; i++) {
3160 dev->srCache[i].lastUse = 0;
3167 cache->lastUse = dev->srLastUse;
3175 /* Invalidate a single cache page.
3176 * Do this when a whole page gets written,
3177 * ie the short cache for this page is no longer valid.
3179 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3181 if (object->myDev->nShortOpCaches > 0) {
3182 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3185 cache->object = NULL;
3190 /* Invalidate all the cache pages associated with this object
3191 * Do this whenever ther file is deleted or resized.
3193 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3196 yaffs_Device *dev = in->myDev;
3198 if (dev->nShortOpCaches > 0) {
3199 /* Invalidate it. */
3200 for (i = 0; i < dev->nShortOpCaches; i++) {
3201 if (dev->srCache[i].object == in) {
3202 dev->srCache[i].object = NULL;
3208 /*--------------------- File read/write ------------------------
3209 * Read and write have very similar structures.
3210 * In general the read/write has three parts to it
3211 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3212 * Some complete chunks
3213 * An incomplete chunk to end off with
3215 * Curve-balls: the first chunk might also be the last chunk.
3218 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3227 yaffs_ChunkCache *cache;
3234 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3235 start = offset % dev->nBytesPerChunk;
3237 /* OK now check for the curveball where the start and end are in
3240 if ((start + n) < dev->nBytesPerChunk) {
3243 nToCopy = dev->nBytesPerChunk - start;
3246 cache = yaffs_FindChunkCache(in, chunk);
3248 /* If the chunk is already in the cache or it is less than a whole chunk
3249 * then use the cache (if there is caching)
3250 * else bypass the cache.
3252 if (cache || nToCopy != dev->nBytesPerChunk) {
3253 if (dev->nShortOpCaches > 0) {
3255 /* If we can't find the data in the cache, then load it up. */
3258 cache = yaffs_GrabChunkCache(in->myDev);
3260 cache->chunkId = chunk;
3263 yaffs_ReadChunkDataFromObject(in, chunk,
3269 yaffs_UseChunkCache(dev, cache, 0);
3273 #ifdef CONFIG_YAFFS_WINCE
3274 yfsd_UnlockYAFFS(TRUE);
3276 memcpy(buffer, &cache->data[start], nToCopy);
3278 #ifdef CONFIG_YAFFS_WINCE
3279 yfsd_LockYAFFS(TRUE);
3283 /* Read into the local buffer then copy..*/
3286 yaffs_GetTempBuffer(dev, __LINE__);
3287 yaffs_ReadChunkDataFromObject(in, chunk,
3289 #ifdef CONFIG_YAFFS_WINCE
3290 yfsd_UnlockYAFFS(TRUE);
3292 memcpy(buffer, &localBuffer[start], nToCopy);
3294 #ifdef CONFIG_YAFFS_WINCE
3295 yfsd_LockYAFFS(TRUE);
3297 yaffs_ReleaseTempBuffer(dev, localBuffer,
3302 #ifdef CONFIG_YAFFS_WINCE
3303 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3305 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3306 * This is because we otherwise screw up WinCE's memory mapper
3308 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3310 #ifdef CONFIG_YAFFS_WINCE
3311 yfsd_UnlockYAFFS(TRUE);
3313 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3315 #ifdef CONFIG_YAFFS_WINCE
3316 yfsd_LockYAFFS(TRUE);
3317 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3321 /* A full chunk. Read directly into the supplied buffer. */
3322 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3336 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3337 int nBytes, int writeThrough)
3346 int startOfWrite = offset;
3347 int chunkWritten = 0;
3354 while (n > 0 && chunkWritten >= 0) {
3355 chunk = offset / dev->nBytesPerChunk + 1;
3356 start = offset % dev->nBytesPerChunk;
3358 /* OK now check for the curveball where the start and end are in
3362 if ((start + n) < dev->nBytesPerChunk) {
3365 /* Now folks, to calculate how many bytes to write back....
3366 * If we're overwriting and not writing to then end of file then
3367 * we need to write back as much as was there before.
3371 in->variant.fileVariant.fileSize -
3372 ((chunk - 1) * dev->nBytesPerChunk);
3374 if (nBytesRead > dev->nBytesPerChunk) {
3375 nBytesRead = dev->nBytesPerChunk;
3380 (start + n)) ? nBytesRead : (start + n);
3383 nToCopy = dev->nBytesPerChunk - start;
3384 nToWriteBack = dev->nBytesPerChunk;
3387 if (nToCopy != dev->nBytesPerChunk) {
3388 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3389 if (dev->nShortOpCaches > 0) {
3390 yaffs_ChunkCache *cache;
3391 /* If we can't find the data in the cache, then load the cache */
3392 cache = yaffs_FindChunkCache(in, chunk);
3394 && yaffs_CheckSpaceForAllocation(in->
3396 cache = yaffs_GrabChunkCache(in->myDev);
3398 cache->chunkId = chunk;
3401 yaffs_ReadChunkDataFromObject(in, chunk,
3407 yaffs_UseChunkCache(dev, cache, 1);
3409 #ifdef CONFIG_YAFFS_WINCE
3410 yfsd_UnlockYAFFS(TRUE);
3413 memcpy(&cache->data[start], buffer,
3416 #ifdef CONFIG_YAFFS_WINCE
3417 yfsd_LockYAFFS(TRUE);
3420 cache->nBytes = nToWriteBack;
3424 yaffs_WriteChunkDataToObject
3427 cache->data, cache->nBytes,
3433 chunkWritten = -1; /* fail the write */
3436 /* An incomplete start or end chunk (or maybe both start and end chunk)
3437 * Read into the local buffer then copy, then copy over and write back.
3441 yaffs_GetTempBuffer(dev, __LINE__);
3443 yaffs_ReadChunkDataFromObject(in, chunk,
3446 #ifdef CONFIG_YAFFS_WINCE
3447 yfsd_UnlockYAFFS(TRUE);
3450 memcpy(&localBuffer[start], buffer, nToCopy);
3452 #ifdef CONFIG_YAFFS_WINCE
3453 yfsd_LockYAFFS(TRUE);
3456 yaffs_WriteChunkDataToObject(in, chunk,
3461 yaffs_ReleaseTempBuffer(dev, localBuffer,
3468 #ifdef CONFIG_YAFFS_WINCE
3469 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3470 * This is because we otherwise screw up WinCE's memory mapper
3472 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3473 #ifdef CONFIG_YAFFS_WINCE
3474 yfsd_UnlockYAFFS(TRUE);
3476 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3477 #ifdef CONFIG_YAFFS_WINCE
3478 yfsd_LockYAFFS(TRUE);
3481 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3482 dev->nBytesPerChunk,
3484 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3486 /* A full chunk. Write directly from the supplied buffer. */
3488 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3489 dev->nBytesPerChunk,
3492 /* Since we've overwritten the cached data, we better invalidate it. */
3493 yaffs_InvalidateChunkCache(in, chunk);
3496 if (chunkWritten >= 0) {
3505 /* Update file object */
3507 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3508 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3517 /* ---------------------- File resizing stuff ------------------ */
3519 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
3522 yaffs_Device *dev = in->myDev;
3523 int oldFileSize = in->variant.fileVariant.fileSize;
3525 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
3527 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
3528 dev->nBytesPerChunk;
3532 /* Delete backwards so that we don't end up with holes if
3533 * power is lost part-way through the operation.
3535 for (i = lastDel; i >= startDel; i--) {
3536 /* NB this could be optimised somewhat,
3537 * eg. could retrieve the tags and write them without
3538 * using yaffs_DeleteChunk
3541 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3544 (dev->internalStartBlock * dev->nChunksPerBlock)
3546 ((dev->internalEndBlock +
3547 1) * dev->nChunksPerBlock)) {
3548 T(YAFFS_TRACE_ALWAYS,
3549 (TSTR("Found daft chunkId %d for %d" TENDSTR),
3553 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3560 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
3563 int oldFileSize = in->variant.fileVariant.fileSize;
3564 int sizeOfPartialChunk;
3565 yaffs_Device *dev = in->myDev;
3567 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
3569 yaffs_FlushFilesChunkCache(in);
3570 yaffs_InvalidateWholeChunkCache(in);
3572 yaffs_CheckGarbageCollection(dev);
3574 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3575 return yaffs_GetFileSize(in);
3578 if (newSize == oldFileSize) {
3582 if (newSize < oldFileSize) {
3584 yaffs_PruneResizedChunks(in, newSize);
3586 if (sizeOfPartialChunk != 0) {
3587 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
3588 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3590 /* Got to read and rewrite the last chunk with its new size and zero pad */
3591 yaffs_ReadChunkDataFromObject(in, lastChunk,
3594 memset(localBuffer + sizeOfPartialChunk, 0,
3595 dev->nBytesPerChunk - sizeOfPartialChunk);
3597 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
3598 sizeOfPartialChunk, 1);
3600 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3603 in->variant.fileVariant.fileSize = newSize;
3605 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
3607 /* Write a new object header.
3608 * show we've shrunk the file, if need be
3609 * Do this only if the file is not in the deleted directories.
3611 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3612 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
3613 yaffs_UpdateObjectHeader(in, NULL, 0,
3614 (newSize < oldFileSize) ? 1 : 0, 0);
3620 loff_t yaffs_GetFileSize(yaffs_Object * obj)
3622 obj = yaffs_GetEquivalentObject(obj);
3624 switch (obj->variantType) {
3625 case YAFFS_OBJECT_TYPE_FILE:
3626 return obj->variant.fileVariant.fileSize;
3627 case YAFFS_OBJECT_TYPE_SYMLINK:
3628 return yaffs_strlen(obj->variant.symLinkVariant.alias);
3636 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
3640 yaffs_FlushFilesChunkCache(in);
3642 #ifdef CONFIG_YAFFS_WINCE
3643 yfsd_WinFileTimeNow(in->win_mtime);
3646 in->yst_mtime = Y_CURRENT_TIME;
3652 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
3653 0) ? YAFFS_OK : YAFFS_FAIL;
3662 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
3665 /* First off, invalidate the file's data in the cache, without flushing. */
3666 yaffs_InvalidateWholeChunkCache(in);
3668 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3669 /* Move to the unlinked directory so we have a record that it was deleted. */
3670 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
3674 yaffs_RemoveObjectFromDirectory(in);
3675 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
3678 yaffs_FreeObject(in);
3683 /* yaffs_DeleteFile deletes the whole file data
3684 * and the inode associated with the file.
3685 * It does not delete the links associated with the file.
3687 static int yaffs_UnlinkFile(yaffs_Object * in)
3691 int immediateDeletion = 0;
3696 immediateDeletion = 1;
3700 if (in->inUse <= 0) {
3701 immediateDeletion = 1;
3705 if (immediateDeletion) {
3707 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3709 T(YAFFS_TRACE_TRACING,
3710 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3713 in->myDev->nDeletedFiles++;
3714 if (0 && in->myDev->isYaffs2) {
3715 yaffs_ResizeFile(in, 0);
3717 yaffs_SoftDeleteFile(in);
3720 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3728 int yaffs_DeleteFile(yaffs_Object * in)
3730 int retVal = YAFFS_OK;
3732 if (in->nDataChunks > 0) {
3733 /* Use soft deletion if there is data in the file */
3734 if (!in->unlinked) {
3735 retVal = yaffs_UnlinkFile(in);
3737 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3739 in->myDev->nDeletedFiles++;
3740 yaffs_SoftDeleteFile(in);
3742 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3744 /* The file has no data chunks so we toss it immediately */
3745 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3746 in->variant.fileVariant.top = NULL;
3747 yaffs_DoGenericObjectDeletion(in);
3753 static int yaffs_DeleteDirectory(yaffs_Object * in)
3755 /* First check that the directory is empty. */
3756 if (list_empty(&in->variant.directoryVariant.children)) {
3757 return yaffs_DoGenericObjectDeletion(in);
3764 static int yaffs_DeleteSymLink(yaffs_Object * in)
3766 YFREE(in->variant.symLinkVariant.alias);
3768 return yaffs_DoGenericObjectDeletion(in);
3771 static int yaffs_DeleteHardLink(yaffs_Object * in)
3773 /* remove this hardlink from the list assocaited with the equivalent
3776 list_del(&in->hardLinks);
3777 return yaffs_DoGenericObjectDeletion(in);
3780 static void yaffs_DestroyObject(yaffs_Object * obj)
3782 switch (obj->variantType) {
3783 case YAFFS_OBJECT_TYPE_FILE:
3784 yaffs_DeleteFile(obj);
3786 case YAFFS_OBJECT_TYPE_DIRECTORY:
3787 yaffs_DeleteDirectory(obj);
3789 case YAFFS_OBJECT_TYPE_SYMLINK:
3790 yaffs_DeleteSymLink(obj);
3792 case YAFFS_OBJECT_TYPE_HARDLINK:
3793 yaffs_DeleteHardLink(obj);
3795 case YAFFS_OBJECT_TYPE_SPECIAL:
3796 yaffs_DoGenericObjectDeletion(obj);
3798 case YAFFS_OBJECT_TYPE_UNKNOWN:
3799 break; /* should not happen. */
3803 static int yaffs_UnlinkWorker(yaffs_Object * obj)
3806 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3807 return yaffs_DeleteHardLink(obj);
3808 } else if (!list_empty(&obj->hardLinks)) {
3809 /* Curve ball: We're unlinking an object that has a hardlink.
3811 * This problem arises because we are not strictly following
3812 * The Linux link/inode model.
3814 * We can't really delete the object.
3815 * Instead, we do the following:
3816 * - Select a hardlink.
3817 * - Unhook it from the hard links
3818 * - Unhook it from its parent directory (so that the rename can work)
3819 * - Rename the object to the hardlink's name.
3820 * - Delete the hardlink
3825 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3827 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
3829 list_del_init(&hl->hardLinks);
3830 list_del_init(&hl->siblings);
3832 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3834 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
3836 if (retVal == YAFFS_OK) {
3837 retVal = yaffs_DoGenericObjectDeletion(hl);
3842 switch (obj->variantType) {
3843 case YAFFS_OBJECT_TYPE_FILE:
3844 return yaffs_UnlinkFile(obj);
3846 case YAFFS_OBJECT_TYPE_DIRECTORY:
3847 return yaffs_DeleteDirectory(obj);
3849 case YAFFS_OBJECT_TYPE_SYMLINK:
3850 return yaffs_DeleteSymLink(obj);
3852 case YAFFS_OBJECT_TYPE_SPECIAL:
3853 return yaffs_DoGenericObjectDeletion(obj);
3855 case YAFFS_OBJECT_TYPE_HARDLINK:
3856 case YAFFS_OBJECT_TYPE_UNKNOWN:
3864 static int yaffs_UnlinkObject( yaffs_Object *obj)
3867 if (obj && obj->unlinkAllowed) {
3868 return yaffs_UnlinkWorker(obj);
3874 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
3878 obj = yaffs_FindObjectByName(dir, name);
3879 return yaffs_UnlinkObject(obj);
3882 /*----------------------- Initialisation Scanning ---------------------- */
3884 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
3885 int backwardScanning)
3889 if (!backwardScanning) {
3890 /* Handle YAFFS1 forward scanning case
3891 * For YAFFS1 we always do the deletion
3895 /* Handle YAFFS2 case (backward scanning)
3896 * If the shadowed object exists then ignore.
3898 if (yaffs_FindObjectByNumber(dev, objId)) {
3903 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
3904 * We put it in unlinked dir to be cleaned up after the scanning
3907 yaffs_FindOrCreateObjectByNumber(dev, objId,
3908 YAFFS_OBJECT_TYPE_FILE);
3909 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
3910 obj->variant.fileVariant.shrinkSize = 0;
3911 obj->valid = 1; /* So that we don't read any other info for this file */
3920 static int yaffs_Scan(yaffs_Device * dev)
3922 yaffs_ExtendedTags tags;
3927 int nBlocksToScan = 0;
3932 yaffs_BlockState state;
3933 yaffs_Object *hardList = NULL;
3935 yaffs_BlockInfo *bi;
3937 yaffs_ObjectHeader *oh;
3939 yaffs_Object *parent;
3940 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3944 yaffs_BlockIndex *blockIndex = NULL;
3947 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
3948 dev->internalStartBlock, dev->internalEndBlock));
3950 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
3952 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
3954 if (dev->isYaffs2) {
3955 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
3958 /* Scan all the blocks to determine their state */
3959 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
3960 bi = yaffs_GetBlockInfo(dev, blk);
3961 yaffs_ClearChunkBits(dev, blk);
3963 bi->softDeletions = 0;
3965 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
3967 bi->blockState = state;
3968 bi->sequenceNumber = sequenceNumber;
3970 T(YAFFS_TRACE_SCAN_DEBUG,
3971 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
3972 state, sequenceNumber));
3974 if (state == YAFFS_BLOCK_STATE_DEAD) {
3975 T(YAFFS_TRACE_BAD_BLOCKS,
3976 (TSTR("block %d is bad" TENDSTR), blk));
3977 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
3978 T(YAFFS_TRACE_SCAN_DEBUG,
3979 (TSTR("Block empty " TENDSTR)));
3980 dev->nErasedBlocks++;
3981 dev->nFreeChunks += dev->nChunksPerBlock;
3982 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3984 /* Determine the highest sequence number */
3985 if (dev->isYaffs2 &&
3986 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
3987 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
3989 blockIndex[nBlocksToScan].seq = sequenceNumber;
3990 blockIndex[nBlocksToScan].block = blk;
3994 if (sequenceNumber >= dev->sequenceNumber) {
3995 dev->sequenceNumber = sequenceNumber;
3997 } else if (dev->isYaffs2) {
3998 /* TODO: Nasty sequence number! */
4001 ("Block scanning block %d has bad sequence number %d"
4002 TENDSTR), blk, sequenceNumber));
4009 * Dungy old bubble sort for now...
4011 if (dev->isYaffs2) {
4012 yaffs_BlockIndex temp;
4016 for (i = 0; i < nBlocksToScan; i++)
4017 for (j = i + 1; j < nBlocksToScan; j++)
4018 if (blockIndex[i].seq > blockIndex[j].seq) {
4019 temp = blockIndex[j];
4020 blockIndex[j] = blockIndex[i];
4021 blockIndex[i] = temp;
4025 /* Now scan the blocks looking at the data. */
4026 if (dev->isYaffs2) {
4028 endIterator = nBlocksToScan - 1;
4029 T(YAFFS_TRACE_SCAN_DEBUG,
4030 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4032 startIterator = dev->internalStartBlock;
4033 endIterator = dev->internalEndBlock;
4036 /* For each block.... */
4037 for (blockIterator = startIterator; blockIterator <= endIterator;
4040 if (dev->isYaffs2) {
4041 /* get the block to scan in the correct order */
4042 blk = blockIndex[blockIterator].block;
4044 blk = blockIterator;
4047 bi = yaffs_GetBlockInfo(dev, blk);
4048 state = bi->blockState;
4052 /* For each chunk in each block that needs scanning....*/
4053 for (c = 0; c < dev->nChunksPerBlock &&
4054 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4055 /* Read the tags and decide what to do */
4056 chunk = blk * dev->nChunksPerBlock + c;
4058 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4061 /* Let's have a good look at this chunk... */
4063 if (!dev->isYaffs2 && tags.chunkDeleted) {
4069 /*T((" %d %d deleted\n",blk,c)); */
4070 } else if (!tags.chunkUsed) {
4071 /* An unassigned chunk in the block
4072 * This means that either the block is empty or
4073 * this is the one being allocated from
4077 /* We're looking at the first chunk in the block so the block is unused */
4078 state = YAFFS_BLOCK_STATE_EMPTY;
4079 dev->nErasedBlocks++;
4081 /* this is the block being allocated from */
4084 (" Allocating from %d %d" TENDSTR),
4086 state = YAFFS_BLOCK_STATE_ALLOCATING;
4087 dev->allocationBlock = blk;
4088 dev->allocationPage = c;
4089 dev->allocationBlockFinder = blk;
4090 /* Set it to here to encourage the allocator to go forth from here. */
4092 /* Yaffs2 sanity check:
4093 * This should be the one with the highest sequence number
4096 && (dev->sequenceNumber !=
4097 bi->sequenceNumber)) {
4098 T(YAFFS_TRACE_ALWAYS,
4100 ("yaffs: Allocation block %d was not highest sequence id:"
4101 " block seq = %d, dev seq = %d"
4102 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4106 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4107 } else if (tags.chunkId > 0) {
4108 /* chunkId > 0 so it is a data chunk... */
4109 unsigned int endpos;
4111 yaffs_SetChunkBit(dev, blk, c);
4114 in = yaffs_FindOrCreateObjectByNumber(dev,
4117 YAFFS_OBJECT_TYPE_FILE);
4118 /* PutChunkIntoFile checks for a clash (two data chunks with
4119 * the same chunkId).
4121 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4124 (tags.chunkId - 1) * dev->nBytesPerChunk +
4126 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4127 && in->variant.fileVariant.scannedFileSize <
4129 in->variant.fileVariant.
4130 scannedFileSize = endpos;
4131 if (!dev->useHeaderFileSize) {
4132 in->variant.fileVariant.
4134 in->variant.fileVariant.
4139 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4141 /* chunkId == 0, so it is an ObjectHeader.
4142 * Thus, we read in the object header and make the object
4144 yaffs_SetChunkBit(dev, blk, c);
4147 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4151 oh = (yaffs_ObjectHeader *) chunkData;
4153 in = yaffs_FindObjectByNumber(dev,
4155 if (in && in->variantType != oh->type) {
4156 /* This should not happen, but somehow
4157 * Wev'e ended up with an objectId that has been reused but not yet
4158 * deleted, and worse still it has changed type. Delete the old object.
4161 yaffs_DestroyObject(in);
4166 in = yaffs_FindOrCreateObjectByNumber(dev,
4171 if (oh->shadowsObject > 0) {
4172 yaffs_HandleShadowedObject(dev,
4179 /* We have already filled this one. We have a duplicate and need to resolve it. */
4181 unsigned existingSerial = in->serial;
4182 unsigned newSerial = tags.serialNumber;
4184 if (dev->isYaffs2 ||
4185 ((existingSerial + 1) & 3) ==
4187 /* Use new one - destroy the exisiting one */
4188 yaffs_DeleteChunk(dev,
4193 /* Use existing - destroy this one. */
4194 yaffs_DeleteChunk(dev, chunk, 1,
4200 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4201 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4202 /* We only load some info, don't fiddle with directory structure */
4204 in->variantType = oh->type;
4206 in->yst_mode = oh->yst_mode;
4207 #ifdef CONFIG_YAFFS_WINCE
4208 in->win_atime[0] = oh->win_atime[0];
4209 in->win_ctime[0] = oh->win_ctime[0];
4210 in->win_mtime[0] = oh->win_mtime[0];
4211 in->win_atime[1] = oh->win_atime[1];
4212 in->win_ctime[1] = oh->win_ctime[1];
4213 in->win_mtime[1] = oh->win_mtime[1];
4215 in->yst_uid = oh->yst_uid;
4216 in->yst_gid = oh->yst_gid;
4217 in->yst_atime = oh->yst_atime;
4218 in->yst_mtime = oh->yst_mtime;
4219 in->yst_ctime = oh->yst_ctime;
4220 in->yst_rdev = oh->yst_rdev;
4222 in->chunkId = chunk;
4224 } else if (!in->valid) {
4225 /* we need to load this info */
4228 in->variantType = oh->type;
4230 in->yst_mode = oh->yst_mode;
4231 #ifdef CONFIG_YAFFS_WINCE
4232 in->win_atime[0] = oh->win_atime[0];
4233 in->win_ctime[0] = oh->win_ctime[0];
4234 in->win_mtime[0] = oh->win_mtime[0];
4235 in->win_atime[1] = oh->win_atime[1];
4236 in->win_ctime[1] = oh->win_ctime[1];
4237 in->win_mtime[1] = oh->win_mtime[1];
4239 in->yst_uid = oh->yst_uid;
4240 in->yst_gid = oh->yst_gid;
4241 in->yst_atime = oh->yst_atime;
4242 in->yst_mtime = oh->yst_mtime;
4243 in->yst_ctime = oh->yst_ctime;
4244 in->yst_rdev = oh->yst_rdev;
4246 in->chunkId = chunk;
4248 yaffs_SetObjectName(in, oh->name);
4251 /* directory stuff...
4256 yaffs_FindOrCreateObjectByNumber
4257 (dev, oh->parentObjectId,
4258 YAFFS_OBJECT_TYPE_DIRECTORY);
4259 if (parent->variantType ==
4260 YAFFS_OBJECT_TYPE_UNKNOWN) {
4261 /* Set up as a directory */
4262 parent->variantType =
4263 YAFFS_OBJECT_TYPE_DIRECTORY;
4264 INIT_LIST_HEAD(&parent->variant.
4267 } else if (parent->variantType !=
4268 YAFFS_OBJECT_TYPE_DIRECTORY)
4270 /* Hoosterman, another problem....
4271 * We're trying to use a non-directory as a directory
4274 T(YAFFS_TRACE_ERROR,
4276 ("yaffs tragedy: attempting to use non-directory as"
4277 " a directory in scan. Put in lost+found."
4279 parent = dev->lostNFoundDir;
4282 yaffs_AddObjectToDirectory(parent, in);
4284 if (0 && (parent == dev->deletedDir ||
4285 parent == dev->unlinkedDir)) {
4286 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
4287 dev->nDeletedFiles++;
4289 /* Note re hardlinks.
4290 * Since we might scan a hardlink before its equivalent object is scanned
4291 * we put them all in a list.
4292 * After scanning is complete, we should have all the objects, so we run through this
4293 * list and fix up all the chains.
4296 switch (in->variantType) {
4297 case YAFFS_OBJECT_TYPE_UNKNOWN:
4298 /* Todo got a problem */
4300 case YAFFS_OBJECT_TYPE_FILE:
4303 /* Prune back the shrunken chunks */
4304 yaffs_PruneResizedChunks
4306 /* Mark the block as having a shrinkHeader */
4307 bi->hasShrinkHeader = 1;
4310 if (dev->useHeaderFileSize)
4312 in->variant.fileVariant.
4317 case YAFFS_OBJECT_TYPE_HARDLINK:
4318 in->variant.hardLinkVariant.
4319 equivalentObjectId =
4320 oh->equivalentObjectId;
4321 in->hardLinks.next =
4322 (struct list_head *)
4326 case YAFFS_OBJECT_TYPE_DIRECTORY:
4329 case YAFFS_OBJECT_TYPE_SPECIAL:
4332 case YAFFS_OBJECT_TYPE_SYMLINK:
4333 in->variant.symLinkVariant.
4335 yaffs_CloneString(oh->alias);
4339 if (parent == dev->deletedDir) {
4340 yaffs_DestroyObject(in);
4341 bi->hasShrinkHeader = 1;
4347 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4348 /* If we got this far while scanning, then the block is fully allocated.*/
4349 state = YAFFS_BLOCK_STATE_FULL;
4352 bi->blockState = state;
4354 /* Now let's see if it was dirty */
4355 if (bi->pagesInUse == 0 &&
4356 !bi->hasShrinkHeader &&
4357 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4358 yaffs_BlockBecameDirty(dev, blk);
4367 /* Ok, we've done all the scanning.
4368 * Fix up the hard link chains.
4369 * We should now have scanned all the objects, now it's time to add these
4374 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4376 in = yaffs_FindObjectByNumber(dev,
4377 hl->variant.hardLinkVariant.
4378 equivalentObjectId);
4381 /* Add the hardlink pointers */
4382 hl->variant.hardLinkVariant.equivalentObject = in;
4383 list_add(&hl->hardLinks, &in->hardLinks);
4385 /* Todo Need to report/handle this better.
4386 * Got a problem... hardlink to a non-existant object
4388 hl->variant.hardLinkVariant.equivalentObject = NULL;
4389 INIT_LIST_HEAD(&hl->hardLinks);
4395 /* Handle the unlinked files. Since they were left in an unlinked state we should
4399 struct list_head *i;
4400 struct list_head *n;
4403 /* Soft delete all the unlinked files */
4404 list_for_each_safe(i, n,
4405 &dev->unlinkedDir->variant.directoryVariant.
4408 l = list_entry(i, yaffs_Object, siblings);
4409 yaffs_DestroyObject(l);
4414 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4416 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4421 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4424 yaffs_ObjectHeader *oh;
4425 yaffs_Device *dev = in->myDev;
4429 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4431 yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,NULL);
4432 oh = (yaffs_ObjectHeader *) chunkData;
4434 in->yst_mode = oh->yst_mode;
4435 #ifdef CONFIG_YAFFS_WINCE
4436 in->win_atime[0] = oh->win_atime[0];
4437 in->win_ctime[0] = oh->win_ctime[0];
4438 in->win_mtime[0] = oh->win_mtime[0];
4439 in->win_atime[1] = oh->win_atime[1];
4440 in->win_ctime[1] = oh->win_ctime[1];
4441 in->win_mtime[1] = oh->win_mtime[1];
4443 in->yst_uid = oh->yst_uid;
4444 in->yst_gid = oh->yst_gid;
4445 in->yst_atime = oh->yst_atime;
4446 in->yst_mtime = oh->yst_mtime;
4447 in->yst_ctime = oh->yst_ctime;
4448 in->yst_rdev = oh->yst_rdev;
4451 yaffs_SetObjectName(in, oh->name);
4453 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4454 in->variant.symLinkVariant.alias =
4455 yaffs_CloneString(oh->alias);
4457 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
4461 static int yaffs_ScanBackwards(yaffs_Device * dev)
4463 yaffs_ExtendedTags tags;
4468 int nBlocksToScan = 0;
4473 yaffs_BlockState state;
4474 yaffs_Object *hardList = NULL;
4476 yaffs_BlockInfo *bi;
4478 yaffs_ObjectHeader *oh;
4480 yaffs_Object *parent;
4481 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4487 int equivalentObjectId;
4490 yaffs_BlockIndex *blockIndex = NULL;
4492 if (!dev->isYaffs2) {
4494 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
4500 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
4501 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
4503 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4505 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4507 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4509 /* Scan all the blocks to determine their state */
4510 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4511 bi = yaffs_GetBlockInfo(dev, blk);
4512 yaffs_ClearChunkBits(dev, blk);
4514 bi->softDeletions = 0;
4516 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4518 bi->blockState = state;
4519 bi->sequenceNumber = sequenceNumber;
4521 T(YAFFS_TRACE_SCAN_DEBUG,
4522 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4523 state, sequenceNumber));
4525 if (state == YAFFS_BLOCK_STATE_DEAD) {
4526 T(YAFFS_TRACE_BAD_BLOCKS,
4527 (TSTR("block %d is bad" TENDSTR), blk));
4528 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4529 T(YAFFS_TRACE_SCAN_DEBUG,
4530 (TSTR("Block empty " TENDSTR)));
4531 dev->nErasedBlocks++;
4532 dev->nFreeChunks += dev->nChunksPerBlock;
4533 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4535 /* Determine the highest sequence number */
4536 if (dev->isYaffs2 &&
4537 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4538 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4540 blockIndex[nBlocksToScan].seq = sequenceNumber;
4541 blockIndex[nBlocksToScan].block = blk;
4545 if (sequenceNumber >= dev->sequenceNumber) {
4546 dev->sequenceNumber = sequenceNumber;
4548 } else if (dev->isYaffs2) {
4549 /* TODO: Nasty sequence number! */
4552 ("Block scanning block %d has bad sequence number %d"
4553 TENDSTR), blk, sequenceNumber));
4561 * Dungy old bubble sort for now...
4564 yaffs_BlockIndex temp;
4568 for (i = 0; i < nBlocksToScan; i++)
4569 for (j = i + 1; j < nBlocksToScan; j++)
4570 if (blockIndex[i].seq > blockIndex[j].seq) {
4571 temp = blockIndex[j];
4572 blockIndex[j] = blockIndex[i];
4573 blockIndex[i] = temp;
4577 /* Now scan the blocks looking at the data. */
4579 endIterator = nBlocksToScan - 1;
4580 T(YAFFS_TRACE_SCAN_DEBUG,
4581 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4583 /* For each block.... backwards */
4584 for (blockIterator = endIterator; blockIterator >= startIterator;
4587 /* get the block to scan in the correct order */
4588 blk = blockIndex[blockIterator].block;
4590 bi = yaffs_GetBlockInfo(dev, blk);
4591 state = bi->blockState;
4595 /* For each chunk in each block that needs scanning.... */
4596 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
4597 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
4598 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
4599 /* Scan backwards...
4600 * Read the tags and decide what to do
4602 chunk = blk * dev->nChunksPerBlock + c;
4604 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4607 /* Let's have a good look at this chunk... */
4609 if (!tags.chunkUsed) {
4610 // An unassigned chunk in the block
4611 // This means that either the block is empty or
4612 // this is the one being allocated from
4615 /* We're looking at the first chunk in the block so the block is unused */
4616 state = YAFFS_BLOCK_STATE_EMPTY;
4617 dev->nErasedBlocks++;
4619 /* this is the block being allocated from */
4621 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4624 (" Allocating from %d %d"
4627 state = YAFFS_BLOCK_STATE_ALLOCATING;
4628 dev->allocationBlock = blk;
4629 dev->allocationPage = c;
4630 dev->allocationBlockFinder = blk;
4631 /* Set it to here to encourage the allocator to
4632 * go forth from here.
4635 /* Yaffs2 sanity check:
4636 * This should be the one with the highest sequence number
4639 && (dev->sequenceNumber !=
4640 bi->sequenceNumber)) {
4641 T(YAFFS_TRACE_ALWAYS,
4643 ("yaffs: Allocation block %d was not highest sequence "
4644 "id: block seq = %d, dev seq = %d"
4647 dev->sequenceNumber));
4652 } else if (tags.chunkId > 0) {
4653 /* chunkId > 0 so it is a data chunk... */
4654 unsigned int endpos;
4657 (tags.chunkId - 1) * dev->nBytesPerChunk;
4659 yaffs_SetChunkBit(dev, blk, c);
4662 in = yaffs_FindOrCreateObjectByNumber(dev,
4665 YAFFS_OBJECT_TYPE_FILE);
4666 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4668 in->variant.fileVariant.shrinkSize) {
4669 /* This has not been invalidated by a resize */
4670 yaffs_PutChunkIntoFile(in, tags.chunkId,
4673 /* File size is calculated by looking at the data chunks if we have not
4674 * seen an object header yet. Stop this practice once we find an object header.
4678 1) * dev->nBytesPerChunk +
4681 if (!in->valid && /* have not got an object header yet */
4682 in->variant.fileVariant.
4683 scannedFileSize < endpos) {
4684 in->variant.fileVariant.
4685 scannedFileSize = endpos;
4686 in->variant.fileVariant.
4688 in->variant.fileVariant.
4693 /* This chunk has been invalidated by a resize, so delete */
4694 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4698 /* chunkId == 0, so it is an ObjectHeader.
4699 * Thus, we read in the object header and make the object
4701 yaffs_SetChunkBit(dev, blk, c);
4707 if (tags.extraHeaderInfoAvailable) {
4708 in = yaffs_FindOrCreateObjectByNumber
4709 (dev, tags.objectId,
4710 tags.extraObjectType);
4714 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
4717 tags.extraShadows ||
4719 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4720 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
4723 /* If we don't have valid info then we need to read the chunk
4724 * TODO In future we can probably defer reading the chunk and
4725 * living with invalid data until needed.
4728 yaffs_ReadChunkWithTagsFromNAND(dev,
4733 oh = (yaffs_ObjectHeader *) chunkData;
4736 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
4741 /* TODO Hoosterman we have a problem! */
4742 T(YAFFS_TRACE_ERROR,
4744 ("yaffs tragedy: Could not make object for object %d "
4745 "at chunk %d during scan"
4746 TENDSTR), tags.objectId, chunk));
4751 /* We have already filled this one.
4752 * We have a duplicate that will be discarded, but
4753 * we first have to suck out resize info if it is a file.
4756 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
4758 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
4759 (tags.extraHeaderInfoAvailable &&
4760 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
4763 (oh) ? oh->fileSize : tags.
4765 __u32 parentObjectId =
4767 parentObjectId : tags.
4768 extraParentObjectId;
4770 (oh) ? oh->isShrink : tags.
4771 extraIsShrinkHeader;
4773 /* If it is deleted (unlinked at start also means deleted)
4774 * we treat the file size as being zeroed at this point.
4776 if (parentObjectId ==
4777 YAFFS_OBJECTID_DELETED
4778 || parentObjectId ==
4779 YAFFS_OBJECTID_UNLINKED) {
4785 in->variant.fileVariant.
4786 shrinkSize > thisSize) {
4787 in->variant.fileVariant.
4793 bi->hasShrinkHeader = 1;
4797 /* Use existing - destroy this one. */
4798 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4803 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4805 YAFFS_OBJECTID_LOSTNFOUND)) {
4806 /* We only load some info, don't fiddle with directory structure */
4810 in->variantType = oh->type;
4812 in->yst_mode = oh->yst_mode;
4813 #ifdef CONFIG_YAFFS_WINCE
4814 in->win_atime[0] = oh->win_atime[0];
4815 in->win_ctime[0] = oh->win_ctime[0];
4816 in->win_mtime[0] = oh->win_mtime[0];
4817 in->win_atime[1] = oh->win_atime[1];
4818 in->win_ctime[1] = oh->win_ctime[1];
4819 in->win_mtime[1] = oh->win_mtime[1];
4821 in->yst_uid = oh->yst_uid;
4822 in->yst_gid = oh->yst_gid;
4823 in->yst_atime = oh->yst_atime;
4824 in->yst_mtime = oh->yst_mtime;
4825 in->yst_ctime = oh->yst_ctime;
4826 in->yst_rdev = oh->yst_rdev;
4830 in->variantType = tags.extraObjectType;
4834 in->chunkId = chunk;
4836 } else if (!in->valid) {
4837 /* we need to load this info */
4840 in->chunkId = chunk;
4843 in->variantType = oh->type;
4845 in->yst_mode = oh->yst_mode;
4846 #ifdef CONFIG_YAFFS_WINCE
4847 in->win_atime[0] = oh->win_atime[0];
4848 in->win_ctime[0] = oh->win_ctime[0];
4849 in->win_mtime[0] = oh->win_mtime[0];
4850 in->win_atime[1] = oh->win_atime[1];
4851 in->win_ctime[1] = oh->win_ctime[1];
4852 in->win_mtime[1] = oh->win_mtime[1];
4854 in->yst_uid = oh->yst_uid;
4855 in->yst_gid = oh->yst_gid;
4856 in->yst_atime = oh->yst_atime;
4857 in->yst_mtime = oh->yst_mtime;
4858 in->yst_ctime = oh->yst_ctime;
4859 in->yst_rdev = oh->yst_rdev;
4862 if (oh->shadowsObject > 0)
4863 yaffs_HandleShadowedObject(dev,
4869 yaffs_SetObjectName(in, oh->name);
4871 yaffs_FindOrCreateObjectByNumber
4872 (dev, oh->parentObjectId,
4873 YAFFS_OBJECT_TYPE_DIRECTORY);
4875 fileSize = oh->fileSize;
4876 isShrink = oh->isShrink;
4877 equivalentObjectId = oh->equivalentObjectId;
4881 in->variantType = tags.extraObjectType;
4883 yaffs_FindOrCreateObjectByNumber
4884 (dev, tags.extraParentObjectId,
4885 YAFFS_OBJECT_TYPE_DIRECTORY);
4886 fileSize = tags.extraFileLength;
4887 isShrink = tags.extraIsShrinkHeader;
4888 equivalentObjectId = tags.extraEquivalentObjectId;
4894 /* directory stuff...
4898 if (parent->variantType ==
4899 YAFFS_OBJECT_TYPE_UNKNOWN) {
4900 /* Set up as a directory */
4901 parent->variantType =
4902 YAFFS_OBJECT_TYPE_DIRECTORY;
4903 INIT_LIST_HEAD(&parent->variant.
4906 } else if (parent->variantType !=
4907 YAFFS_OBJECT_TYPE_DIRECTORY)
4909 /* Hoosterman, another problem....
4910 * We're trying to use a non-directory as a directory
4913 T(YAFFS_TRACE_ERROR,
4915 ("yaffs tragedy: attempting to use non-directory as"
4916 " a directory in scan. Put in lost+found."
4918 parent = dev->lostNFoundDir;
4921 yaffs_AddObjectToDirectory(parent, in);
4923 itsUnlinked = (parent == dev->deletedDir) ||
4924 (parent == dev->unlinkedDir);
4927 /* Mark the block as having a shrinkHeader */
4928 bi->hasShrinkHeader = 1;
4931 /* Note re hardlinks.
4932 * Since we might scan a hardlink before its equivalent object is scanned
4933 * we put them all in a list.
4934 * After scanning is complete, we should have all the objects, so we run
4935 * through this list and fix up all the chains.
4938 switch (in->variantType) {
4939 case YAFFS_OBJECT_TYPE_UNKNOWN:
4940 /* Todo got a problem */
4942 case YAFFS_OBJECT_TYPE_FILE:
4944 if (in->variant.fileVariant.
4945 scannedFileSize < fileSize) {
4946 /* This covers the case where the file size is greater
4947 * than where the data is
4948 * This will happen if the file is resized to be larger
4949 * than its current data extents.
4951 in->variant.fileVariant.fileSize = fileSize;
4952 in->variant.fileVariant.scannedFileSize =
4953 in->variant.fileVariant.fileSize;
4957 in->variant.fileVariant.shrinkSize > fileSize) {
4958 in->variant.fileVariant.shrinkSize = fileSize;
4962 case YAFFS_OBJECT_TYPE_HARDLINK:
4964 in->variant.hardLinkVariant.equivalentObjectId =
4966 in->hardLinks.next =
4967 (struct list_head *) hardList;
4971 case YAFFS_OBJECT_TYPE_DIRECTORY:
4974 case YAFFS_OBJECT_TYPE_SPECIAL:
4977 case YAFFS_OBJECT_TYPE_SYMLINK:
4979 in->variant.symLinkVariant.alias =
4980 yaffs_CloneString(oh->
4989 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4990 /* If we got this far while scanning, then the block is fully allocated. */
4991 state = YAFFS_BLOCK_STATE_FULL;
4994 bi->blockState = state;
4996 /* Now let's see if it was dirty */
4997 if (bi->pagesInUse == 0 &&
4998 !bi->hasShrinkHeader &&
4999 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5000 yaffs_BlockBecameDirty(dev, blk);
5008 /* Ok, we've done all the scanning.
5009 * Fix up the hard link chains.
5010 * We should now have scanned all the objects, now it's time to add these
5015 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5017 in = yaffs_FindObjectByNumber(dev,
5018 hl->variant.hardLinkVariant.
5019 equivalentObjectId);
5022 /* Add the hardlink pointers */
5023 hl->variant.hardLinkVariant.equivalentObject = in;
5024 list_add(&hl->hardLinks, &in->hardLinks);
5026 /* Todo Need to report/handle this better.
5027 * Got a problem... hardlink to a non-existant object
5029 hl->variant.hardLinkVariant.equivalentObject = NULL;
5030 INIT_LIST_HEAD(&hl->hardLinks);
5037 struct list_head *i;
5038 struct list_head *n;
5042 /* Soft delete all the unlinked files */
5043 list_for_each_safe(i, n,
5044 &dev->unlinkedDir->variant.directoryVariant.
5047 l = list_entry(i, yaffs_Object, siblings);
5048 yaffs_DestroyObject(l);
5052 /* Soft delete all the deletedDir files */
5053 list_for_each_safe(i, n,
5054 &dev->deletedDir->variant.directoryVariant.
5057 l = list_entry(i, yaffs_Object, siblings);
5058 yaffs_DestroyObject(l);
5064 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5066 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5071 /*------------------------------ Directory Functions ----------------------------- */
5073 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5075 yaffs_Device *dev = obj->myDev;
5077 if(dev && dev->removeObjectCallback)
5078 dev->removeObjectCallback(obj);
5080 list_del_init(&obj->siblings);
5085 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5090 T(YAFFS_TRACE_ALWAYS,
5092 ("tragedy: Trying to add an object to a null pointer directory"
5096 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5097 T(YAFFS_TRACE_ALWAYS,
5099 ("tragedy: Trying to add an object to a non-directory"
5104 if (obj->siblings.prev == NULL) {
5105 /* Not initialised */
5106 INIT_LIST_HEAD(&obj->siblings);
5108 } else if (!list_empty(&obj->siblings)) {
5109 /* If it is holed up somewhere else, un hook it */
5110 yaffs_RemoveObjectFromDirectory(obj);
5113 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5114 obj->parent = directory;
5116 if (directory == obj->myDev->unlinkedDir
5117 || directory == obj->myDev->deletedDir) {
5119 obj->myDev->nUnlinkedFiles++;
5120 obj->renameAllowed = 0;
5124 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5129 struct list_head *i;
5130 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5139 T(YAFFS_TRACE_ALWAYS,
5141 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5145 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5146 T(YAFFS_TRACE_ALWAYS,
5148 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5152 sum = yaffs_CalcNameSum(name);
5154 list_for_each(i, &directory->variant.directoryVariant.children) {
5156 l = list_entry(i, yaffs_Object, siblings);
5158 yaffs_CheckObjectDetailsLoaded(l);
5160 /* Special case for lost-n-found */
5161 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5162 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5165 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5167 /* LostnFound cunk called Objxxx
5170 yaffs_GetObjectName(l, buffer,
5171 YAFFS_MAX_NAME_LENGTH);
5172 if (yaffs_strcmp(name, buffer) == 0) {
5185 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5186 int (*fn) (yaffs_Object *))
5188 struct list_head *i;
5192 T(YAFFS_TRACE_ALWAYS,
5194 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5198 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5199 T(YAFFS_TRACE_ALWAYS,
5201 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5205 list_for_each(i, &theDir->variant.directoryVariant.children) {
5207 l = list_entry(i, yaffs_Object, siblings);
5219 /* GetEquivalentObject dereferences any hard links to get to the
5223 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5225 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5226 /* We want the object id of the equivalent object, not this one */
5227 obj = obj->variant.hardLinkVariant.equivalentObject;
5233 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5235 memset(name, 0, buffSize * sizeof(YCHAR));
5237 yaffs_CheckObjectDetailsLoaded(obj);
5239 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5240 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5241 } else if (obj->chunkId <= 0) {
5243 /* make up a name */
5244 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5246 yaffs_strncpy(name, locName, buffSize - 1);
5249 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5250 else if (obj->shortName[0]) {
5251 yaffs_strcpy(name, obj->shortName);
5255 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5257 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5259 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5261 if (obj->chunkId >= 0) {
5262 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5263 obj->chunkId, buffer,
5266 yaffs_strncpy(name, oh->name, buffSize - 1);
5268 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5271 return yaffs_strlen(name);
5274 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5277 /* Dereference any hard linking */
5278 obj = yaffs_GetEquivalentObject(obj);
5280 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5281 return obj->variant.fileVariant.fileSize;
5283 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5284 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5286 /* Only a directory should drop through to here */
5287 return obj->myDev->nBytesPerChunk;
5291 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5294 struct list_head *i;
5296 if (!obj->unlinked) {
5297 count++; /* the object itself */
5299 list_for_each(i, &obj->hardLinks) {
5300 count++; /* add the hard links; */
5306 int yaffs_GetObjectInode(yaffs_Object * obj)
5308 obj = yaffs_GetEquivalentObject(obj);
5310 return obj->objectId;
5313 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5315 obj = yaffs_GetEquivalentObject(obj);
5317 switch (obj->variantType) {
5318 case YAFFS_OBJECT_TYPE_FILE:
5321 case YAFFS_OBJECT_TYPE_DIRECTORY:
5324 case YAFFS_OBJECT_TYPE_SYMLINK:
5327 case YAFFS_OBJECT_TYPE_HARDLINK:
5330 case YAFFS_OBJECT_TYPE_SPECIAL:
5331 if (S_ISFIFO(obj->yst_mode))
5333 if (S_ISCHR(obj->yst_mode))
5335 if (S_ISBLK(obj->yst_mode))
5337 if (S_ISSOCK(obj->yst_mode))
5345 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5347 obj = yaffs_GetEquivalentObject(obj);
5348 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5349 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5351 return yaffs_CloneString(_Y(""));
5355 #ifndef CONFIG_YAFFS_WINCE
5357 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5359 unsigned int valid = attr->ia_valid;
5361 if (valid & ATTR_MODE)
5362 obj->yst_mode = attr->ia_mode;
5363 if (valid & ATTR_UID)
5364 obj->yst_uid = attr->ia_uid;
5365 if (valid & ATTR_GID)
5366 obj->yst_gid = attr->ia_gid;
5368 if (valid & ATTR_ATIME)
5369 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5370 if (valid & ATTR_CTIME)
5371 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5372 if (valid & ATTR_MTIME)
5373 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5375 if (valid & ATTR_SIZE)
5376 yaffs_ResizeFile(obj, attr->ia_size);
5378 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5383 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5385 unsigned int valid = 0;
5387 attr->ia_mode = obj->yst_mode;
5389 attr->ia_uid = obj->yst_uid;
5391 attr->ia_gid = obj->yst_gid;
5394 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5395 valid |= ATTR_ATIME;
5396 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5397 valid |= ATTR_CTIME;
5398 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5399 valid |= ATTR_MTIME;
5401 attr->ia_size = yaffs_GetFileSize(obj);
5404 attr->ia_valid = valid;
5413 int yaffs_DumpObject(yaffs_Object * obj)
5417 yaffs_GetObjectName(obj, name, 256);
5419 T(YAFFS_TRACE_ALWAYS,
5421 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5422 " chunk %d type %d size %d\n"
5423 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5424 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5425 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5431 /*---------------------------- Initialisation code -------------------------------------- */
5433 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5436 /* Common functions, gotta have */
5437 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5440 #ifdef CONFIG_YAFFS_YAFFS2
5442 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5443 if (dev->writeChunkWithTagsToNAND &&
5444 dev->readChunkWithTagsFromNAND &&
5445 !dev->writeChunkToNAND &&
5446 !dev->readChunkFromNAND &&
5447 dev->markNANDBlockBad && dev->queryNANDBlock)
5451 /* Can use the "spare" style interface for yaffs1 */
5452 if (!dev->isYaffs2 &&
5453 !dev->writeChunkWithTagsToNAND &&
5454 !dev->readChunkWithTagsFromNAND &&
5455 dev->writeChunkToNAND &&
5456 dev->readChunkFromNAND &&
5457 !dev->markNANDBlockBad && !dev->queryNANDBlock)
5463 int yaffs_GutsInitialise(yaffs_Device * dev)
5470 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5472 /* Check stuff that must be set */
5475 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5479 dev->internalStartBlock = dev->startBlock;
5480 dev->internalEndBlock = dev->endBlock;
5481 dev->blockOffset = 0;
5482 dev->chunkOffset = 0;
5483 dev->nFreeChunks = 0;
5485 if (dev->startBlock == 0) {
5486 dev->internalStartBlock = dev->startBlock + 1;
5487 dev->internalEndBlock = dev->endBlock + 1;
5488 dev->blockOffset = 1;
5489 dev->chunkOffset = dev->nChunksPerBlock;
5492 /* Check geometry parameters. */
5494 if ((dev->isYaffs2 && dev->nBytesPerChunk < 1024) || (!dev->isYaffs2 && dev->nBytesPerChunk != 512) || dev->nChunksPerBlock < 2 || dev->nReservedBlocks < 2 || dev->internalStartBlock <= 0 || dev->internalEndBlock <= 0 || dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
5496 T(YAFFS_TRACE_ALWAYS,
5498 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
5499 TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
5503 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5504 T(YAFFS_TRACE_ALWAYS,
5505 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5509 /* Got the right mix of functions? */
5510 if (!yaffs_CheckDevFunctions(dev)) {
5511 /* Function missing */
5512 T(YAFFS_TRACE_ALWAYS,
5514 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5519 /* This is really a compilation check. */
5520 if (!yaffs_CheckStructures()) {
5521 T(YAFFS_TRACE_ALWAYS,
5522 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5526 if (dev->isMounted) {
5527 T(YAFFS_TRACE_ALWAYS,
5528 (TSTR("yaffs: device already mounted\n" TENDSTR)));
5532 /* Finished with most checks. One or two more checks happen later on too. */
5536 nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5538 /* OK now calculate a few things for the device
5539 * Calculate chunkGroupBits.
5540 * We need to find the next power of 2 > than internalEndBlock
5543 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
5545 for (bits = extraBits = 0; x > 1; bits++) {
5554 /* Set up tnode width if wide tnodes are enabled. */
5555 if(!dev->wideTnodesDisabled){
5556 /* bits must be even so that we end up with 32-bit words */
5560 dev->tnodeWidth = 16;
5562 dev->tnodeWidth = bits;
5565 dev->tnodeWidth = 16;
5567 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5569 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5570 * so if the bitwidth of the
5571 * chunk range we're using is greater than 16 we need
5572 * to figure out chunk shift and chunkGroupSize
5575 if (bits <= dev->tnodeWidth)
5576 dev->chunkGroupBits = 0;
5578 dev->chunkGroupBits = bits - dev->tnodeWidth;
5581 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5583 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
5584 /* We have a problem because the soft delete won't work if
5585 * the chunk group size > chunks per block.
5586 * This can be remedied by using larger "virtual blocks".
5588 T(YAFFS_TRACE_ALWAYS,
5589 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5594 /* OK, we've finished verifying the device, lets continue with initialisation */
5596 /* More device initialisation */
5597 dev->garbageCollections = 0;
5598 dev->passiveGarbageCollections = 0;
5599 dev->currentDirtyChecker = 0;
5600 dev->bufferedBlock = -1;
5601 dev->doingBufferedBlockRewrite = 0;
5602 dev->nDeletedFiles = 0;
5603 dev->nBackgroundDeletions = 0;
5604 dev->nUnlinkedFiles = 0;
5606 dev->eccUnfixed = 0;
5607 dev->tagsEccFixed = 0;
5608 dev->tagsEccUnfixed = 0;
5609 dev->nErasureFailures = 0;
5610 dev->nErasedBlocks = 0;
5613 /* Initialise temporary buffers */
5616 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5617 dev->tempBuffer[i].line = 0; /* not in use */
5618 dev->tempBuffer[i].buffer =
5619 YMALLOC(dev->nBytesPerChunk);
5623 yaffs_InitialiseBlocks(dev, nBlocks);
5625 yaffs_InitialiseTnodes(dev);
5627 yaffs_InitialiseObjects(dev);
5629 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
5631 if (dev->nShortOpCaches > 0) {
5634 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
5635 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5639 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
5641 for (i = 0; i < dev->nShortOpCaches; i++) {
5642 dev->srCache[i].object = NULL;
5643 dev->srCache[i].lastUse = 0;
5644 dev->srCache[i].dirty = 0;
5645 dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
5652 /* Initialise the unlinked, root and lost and found directories */
5653 dev->lostNFoundDir = dev->rootDir = NULL;
5654 dev->unlinkedDir = dev->deletedDir = NULL;
5657 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5659 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5662 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5663 YAFFS_ROOT_MODE | S_IFDIR);
5664 dev->lostNFoundDir =
5665 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5666 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5667 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5669 if (dev->isYaffs2) {
5670 dev->useHeaderFileSize = 1;
5673 /* Now scan the flash. */
5675 yaffs_ScanBackwards(dev);
5679 /* Zero out stats */
5680 dev->nPageReads = 0;
5681 dev->nPageWrites = 0;
5682 dev->nBlockErasures = 0;
5684 dev->nRetriedWrites = 0;
5686 dev->nRetiredBlocks = 0;
5688 yaffs_VerifyFreeChunks(dev);
5690 T(YAFFS_TRACE_TRACING,
5691 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5696 void yaffs_Deinitialise(yaffs_Device * dev)
5698 if (dev->isMounted) {
5701 yaffs_DeinitialiseBlocks(dev);
5702 yaffs_DeinitialiseTnodes(dev);
5703 yaffs_DeinitialiseObjects(dev);
5704 if (dev->nShortOpCaches > 0) {
5706 for (i = 0; i < dev->nShortOpCaches; i++) {
5707 YFREE(dev->srCache[i].data);
5710 YFREE(dev->srCache);
5713 YFREE(dev->gcCleanupList);
5715 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5716 YFREE(dev->tempBuffer[i].buffer);
5724 static int yaffs_CountFreeChunks(yaffs_Device * dev)
5729 yaffs_BlockInfo *blk;
5731 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
5733 blk = yaffs_GetBlockInfo(dev, b);
5735 switch (blk->blockState) {
5736 case YAFFS_BLOCK_STATE_EMPTY:
5737 case YAFFS_BLOCK_STATE_ALLOCATING:
5738 case YAFFS_BLOCK_STATE_COLLECTING:
5739 case YAFFS_BLOCK_STATE_FULL:
5741 (dev->nChunksPerBlock - blk->pagesInUse +
5742 blk->softDeletions);
5753 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
5755 /* This is what we report to the outside world */
5758 int nDirtyCacheChunks;
5761 nFree = dev->nFreeChunks;
5763 nFree = yaffs_CountFreeChunks(dev);
5766 nFree += dev->nDeletedFiles;
5768 /* Now count the number of dirty chunks in the cache and subtract those */
5772 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
5773 if (dev->srCache[i].dirty)
5774 nDirtyCacheChunks++;
5778 nFree -= nDirtyCacheChunks;
5780 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
5789 static int yaffs_freeVerificationFailures;
5791 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
5793 int counted = yaffs_CountFreeChunks(dev);
5795 int difference = dev->nFreeChunks - counted;
5798 T(YAFFS_TRACE_ALWAYS,
5799 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
5800 dev->nFreeChunks, counted, difference));
5801 yaffs_freeVerificationFailures++;
5805 /*---------------------------------------- YAFFS test code ----------------------*/
5807 #define yaffs_CheckStruct(structure,syze, name) \
5808 if(sizeof(structure) != syze) \
5810 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
5811 name,syze,sizeof(structure))); \
5812 return YAFFS_FAIL; \
5815 static int yaffs_CheckStructures(void)
5817 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
5818 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
5819 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
5820 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5821 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
5823 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")