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.26 2005-12-19 21:46:07 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
26 #ifdef CONFIG_YAFFS_WINCE
27 void yfsd_LockYAFFS(BOOL fsLockOnly);
28 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
31 #define YAFFS_PASSIVE_GC_CHUNKS 2
33 #include "yaffs_ecc.h"
37 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev,
40 yaffs_ExtendedTags * tags);
41 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
44 yaffs_ExtendedTags * tags);
45 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo);
46 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
48 yaffs_BlockState * state,
49 unsigned *sequenceNumber);
50 /* Robustification (if it ever comes about...) */
51 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
52 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND);
53 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
55 const yaffs_ExtendedTags * tags);
56 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
57 const yaffs_ExtendedTags * tags);
59 /* Other local prototypes */
60 static int yaffs_UnlinkObject( yaffs_Object *obj);
62 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
64 yaffs_ExtendedTags * tags,
66 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
67 int chunkInNAND, int inScan);
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
70 yaffs_ObjectType type);
71 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
73 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
74 int force, int isShrink, int shadows);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
78 int chunkOffset, int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
83 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
84 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
87 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
90 static int yaffs_UnlinkWorker(yaffs_Object * obj);
91 static void yaffs_DestroyObject(yaffs_Object * obj);
93 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
96 loff_t yaffs_GetFileSize(yaffs_Object * obj);
98 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
100 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
113 * Start of real code.
122 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
124 yaffs_ExtendedTags * tags)
126 chunkInNAND -= dev->chunkOffset;
128 if (dev->readChunkWithTagsFromNAND)
129 return dev->readChunkWithTagsFromNAND(dev, chunkInNAND, buffer,
132 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,
138 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
141 yaffs_ExtendedTags * tags)
143 chunkInNAND -= dev->chunkOffset;
146 tags->sequenceNumber = dev->sequenceNumber;
148 if (!yaffs_ValidateTags(tags)) {
150 (TSTR("Writing uninitialised tags" TENDSTR)));
154 (TSTR("Writing chunk %d tags %d %d" TENDSTR), chunkInNAND,
155 tags->objectId, tags->chunkId));
157 T(YAFFS_TRACE_ERROR, (TSTR("Writing with no tags" TENDSTR)));
161 if (dev->writeChunkWithTagsToNAND)
162 return dev->writeChunkWithTagsToNAND(dev, chunkInNAND, buffer,
165 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,
171 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo)
173 blockNo -= dev->blockOffset;
175 if (dev->markNANDBlockBad)
176 return dev->markNANDBlockBad(dev, blockNo);
178 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev, blockNo);
180 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
182 yaffs_BlockState * state,
183 unsigned *sequenceNumber)
185 blockNo -= dev->blockOffset;
187 if (dev->queryNANDBlock)
188 return dev->queryNANDBlock(dev, blockNo, state, sequenceNumber);
190 return yaffs_TagsCompatabilityQueryNANDBlock(dev, blockNo,
195 static int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,
200 blockInNAND -= dev->blockOffset;
202 dev->nBlockErasures++;
203 result = dev->eraseBlockInNAND(dev, blockInNAND);
205 /* If at first we don't succeed, try again *once*.*/
207 result = dev->eraseBlockInNAND(dev, blockInNAND);
211 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
213 return dev->initialiseNAND(dev);
217 * Temporary buffer manipulations.
220 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
223 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
224 if (dev->tempBuffer[i].line == 0) {
225 dev->tempBuffer[i].line = lineNo;
226 if ((i + 1) > dev->maxTemp) {
227 dev->maxTemp = i + 1;
228 for (j = 0; j <= i; j++)
229 dev->tempBuffer[j].maxLine =
230 dev->tempBuffer[j].line;
233 return dev->tempBuffer[i].buffer;
237 T(YAFFS_TRACE_BUFFERS,
238 (TSTR("Out of temp buffers at line %d, other held by lines:"),
240 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
243 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
246 * If we got here then we have to allocate an unmanaged one
250 dev->unmanagedTempAllocations++;
251 return YMALLOC(dev->nBytesPerChunk);
255 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
259 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
260 if (dev->tempBuffer[i].buffer == buffer) {
261 dev->tempBuffer[i].line = 0;
267 /* assume it is an unmanaged one. */
268 T(YAFFS_TRACE_BUFFERS,
269 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
272 dev->unmanagedTempDeallocations++;
278 * Chunk bitmap manipulations
281 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
283 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
285 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
289 return dev->chunkBits +
290 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
293 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
295 __u8 *blkBits = yaffs_BlockBits(dev, blk);
297 memset(blkBits, 0, dev->chunkBitmapStride);
300 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
302 __u8 *blkBits = yaffs_BlockBits(dev, blk);
304 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
307 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
309 __u8 *blkBits = yaffs_BlockBits(dev, blk);
311 blkBits[chunk / 8] |= (1 << (chunk & 7));
314 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
316 __u8 *blkBits = yaffs_BlockBits(dev, blk);
317 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
320 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
322 __u8 *blkBits = yaffs_BlockBits(dev, blk);
324 for (i = 0; i < dev->chunkBitmapStride; i++) {
333 * Simple hash function. Needs to have a reasonable spread
336 static Y_INLINE int yaffs_HashFunction(int n)
338 return (n % YAFFS_NOBJECT_BUCKETS);
342 * Access functions to useful fake objects
345 yaffs_Object *yaffs_Root(yaffs_Device * dev)
350 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
352 return dev->lostNFoundDir;
357 * Erased NAND checking functions
360 int yaffs_CheckFF(__u8 * buffer, int nBytes)
362 /* Horrible, slow implementation */
371 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
375 int retval = YAFFS_OK;
376 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
377 yaffs_ExtendedTags tags;
379 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
381 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
382 T(YAFFS_TRACE_NANDACCESS,
383 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
387 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
393 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
395 yaffs_ExtendedTags * tags,
404 chunk = yaffs_AllocateChunk(dev, useReserve);
408 /* First check this chunk is erased... */
409 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
410 writeOk = yaffs_CheckChunkErased(dev, chunk);
415 ("**>> yaffs chunk %d was not erased"
419 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
426 * Copy the data into the robustification buffer.
427 * NB We do this at the end to prevent duplicates in the case of a write error.
430 yaffs_HandleWriteChunkOk(dev, chunk, data,
433 yaffs_HandleWriteChunkError(dev, chunk);
437 } while (chunk >= 0 && !writeOk);
441 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
443 dev->nRetriedWrites += (attempts - 1);
450 * Block retiring for handling a broken block.
453 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
456 yaffs_MarkBlockBad(dev, blockInNAND);
458 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
459 YAFFS_BLOCK_STATE_DEAD;
461 dev->nRetiredBlocks++;
465 * Functions for robustisizing TODO
469 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
471 const yaffs_ExtendedTags * tags)
475 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
476 const yaffs_ExtendedTags * tags)
480 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
482 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
484 /* Mark the block for retirement */
485 yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
486 /* Delete the chunk */
487 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
491 /*---------------- Name handling functions ------------*/
493 static __u16 yaffs_CalcNameSum(const YCHAR * name)
498 YUCHAR *bname = (YUCHAR *) name;
500 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
502 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
503 sum += yaffs_toupper(*bname) * i;
514 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
516 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
517 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
518 yaffs_strcpy(obj->shortName, name);
520 obj->shortName[0] = _Y('\0');
523 obj->sum = yaffs_CalcNameSum(name);
526 /*-------------------- TNODES -------------------
528 * List of spare tnodes
529 * The list is hooked together using the first pointer
533 /* yaffs_CreateTnodes creates a bunch more tnodes and
534 * adds them to the tnode free list.
535 * Don't use this function directly
538 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
542 yaffs_Tnode *newTnodes;
546 yaffs_TnodeList *tnl;
551 /* Calculate the tnode size in bytes for variable width tnode support.
552 * Must be a multiple of 32-bits */
553 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
555 /* make these things */
557 newTnodes = YMALLOC(nTnodes * tnodeSize);
558 mem = (__u8 *)newTnodes;
562 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
566 /* Hook them into the free list */
568 for (i = 0; i < nTnodes - 1; i++) {
569 newTnodes[i].internal[0] = &newTnodes[i + 1];
570 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
571 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
575 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
576 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
577 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
579 dev->freeTnodes = newTnodes;
581 /* New hookup for wide tnodes */
582 for(i = 0; i < nTnodes -1; i++) {
583 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
584 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
585 curr->internal[0] = next;
588 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
589 curr->internal[0] = dev->freeTnodes;
590 dev->freeTnodes = (yaffs_Tnode *)mem;
595 dev->nFreeTnodes += nTnodes;
596 dev->nTnodesCreated += nTnodes;
598 /* Now add this bunch of tnodes to a list for freeing up.
599 * NB If we can't add this to the management list it isn't fatal
600 * but it just means we can't free this bunch of tnodes later.
603 tnl = YMALLOC(sizeof(yaffs_TnodeList));
607 ("yaffs: Could not add tnodes to management list" TENDSTR)));
610 tnl->tnodes = newTnodes;
611 tnl->next = dev->allocatedTnodeList;
612 dev->allocatedTnodeList = tnl;
615 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
620 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
622 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
624 yaffs_Tnode *tn = NULL;
626 /* If there are none left make more */
627 if (!dev->freeTnodes) {
628 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
631 if (dev->freeTnodes) {
632 tn = dev->freeTnodes;
633 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
634 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
635 /* Hoosterman, this thing looks like it isn't in the list */
636 T(YAFFS_TRACE_ALWAYS,
637 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
640 dev->freeTnodes = dev->freeTnodes->internal[0];
643 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
649 /* FreeTnode frees up a tnode and puts it back on the free list */
650 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
653 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
654 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
655 /* Hoosterman, this thing looks like it is already in the list */
656 T(YAFFS_TRACE_ALWAYS,
657 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
659 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
661 tn->internal[0] = dev->freeTnodes;
662 dev->freeTnodes = tn;
667 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
669 /* Free the list of allocated tnodes */
670 yaffs_TnodeList *tmp;
672 while (dev->allocatedTnodeList) {
673 tmp = dev->allocatedTnodeList->next;
675 YFREE(dev->allocatedTnodeList->tnodes);
676 YFREE(dev->allocatedTnodeList);
677 dev->allocatedTnodeList = tmp;
681 dev->freeTnodes = NULL;
682 dev->nFreeTnodes = 0;
685 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
687 dev->allocatedTnodeList = NULL;
688 dev->freeTnodes = NULL;
689 dev->nFreeTnodes = 0;
690 dev->nTnodesCreated = 0;
695 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
697 __u32 *map = (__u32 *)tn;
703 pos &= YAFFS_TNODES_LEVEL0_MASK;
704 val >>= dev->chunkGroupBits;
706 bitInMap = pos * dev->tnodeWidth;
707 wordInMap = bitInMap /32;
708 bitInWord = bitInMap & (32 -1);
710 mask = dev->tnodeMask << bitInWord;
712 map[wordInMap] &= ~mask;
713 map[wordInMap] |= (mask & (val << bitInWord));
715 if(dev->tnodeWidth > (32-bitInWord)) {
716 bitInWord = (32 - bitInWord);
718 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
719 map[wordInMap] &= ~mask;
720 map[wordInMap] |= (mask & (val >> bitInWord));
724 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
726 __u32 *map = (__u32 *)tn;
732 pos &= YAFFS_TNODES_LEVEL0_MASK;
734 bitInMap = pos * dev->tnodeWidth;
735 wordInMap = bitInMap /32;
736 bitInWord = bitInMap & (32 -1);
738 val = map[wordInMap] >> bitInWord;
740 if(dev->tnodeWidth > (32-bitInWord)) {
741 bitInWord = (32 - bitInWord);
743 val |= (map[wordInMap] << bitInWord);
746 val &= dev->tnodeMask;
747 val <<= dev->chunkGroupBits;
752 /* ------------------- End of individual tnode manipulation -----------------*/
754 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
755 * The look up tree is represented by the top tnode and the number of topLevel
756 * in the tree. 0 means only the level 0 tnode is in the tree.
759 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
760 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
761 yaffs_FileStructure * fStruct,
765 yaffs_Tnode *tn = fStruct->top;
767 int requiredTallness;
768 int level = fStruct->topLevel;
770 /* Check sane level and chunk Id */
771 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
775 if (chunkId > YAFFS_MAX_CHUNK_ID) {
779 /* First check we're tall enough (ie enough topLevel) */
781 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
782 requiredTallness = 0;
784 i >>= YAFFS_TNODES_INTERNAL_BITS;
788 if (requiredTallness > fStruct->topLevel) {
789 /* Not tall enough, so we can't find it, return NULL. */
793 /* Traverse down to level 0 */
794 while (level > 0 && tn) {
797 ( YAFFS_TNODES_LEVEL0_BITS +
799 YAFFS_TNODES_INTERNAL_BITS)
801 YAFFS_TNODES_INTERNAL_MASK];
809 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
810 * This happens in two steps:
811 * 1. If the tree isn't tall enough, then make it taller.
812 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
814 * Used when modifying the tree.
817 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
818 yaffs_FileStructure * fStruct,
824 int requiredTallness;
831 /* Check sane level and page Id */
832 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
836 if (chunkId > YAFFS_MAX_CHUNK_ID) {
840 /* First check we're tall enough (ie enough topLevel) */
842 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
843 requiredTallness = 0;
845 x >>= YAFFS_TNODES_INTERNAL_BITS;
850 if (requiredTallness > fStruct->topLevel) {
851 /* Not tall enough,gotta make the tree taller */
852 for (i = fStruct->topLevel; i < requiredTallness; i++) {
854 tn = yaffs_GetTnode(dev);
857 tn->internal[0] = fStruct->top;
861 (TSTR("yaffs: no more tnodes" TENDSTR)));
865 fStruct->topLevel = requiredTallness;
868 /* Traverse down to level 0, adding anything we need */
870 l = fStruct->topLevel;
872 while (l > 0 && tn) {
874 ( YAFFS_TNODES_LEVEL0_BITS +
875 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
876 YAFFS_TNODES_INTERNAL_MASK;
879 if (!tn->internal[x])
880 tn->internal[x] = yaffs_GetTnode(dev);
882 tn = tn->internal[x];
890 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
891 yaffs_ExtendedTags * tags, int objectId,
896 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
897 if (yaffs_CheckChunkBit
898 (dev, theChunk / dev->nChunksPerBlock,
899 theChunk % dev->nChunksPerBlock)) {
900 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
902 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
914 /* DeleteWorker scans backwards through the tnode tree and deletes all the
915 * chunks and tnodes in the file
916 * Returns 1 if the tree was deleted.
917 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
920 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
921 int chunkOffset, int *limit)
926 yaffs_ExtendedTags tags;
928 yaffs_Device *dev = in->myDev;
935 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
937 if (tn->internal[i]) {
938 if (limit && (*limit) < 0) {
942 yaffs_DeleteWorker(in,
950 YAFFS_TNODES_INTERNAL_BITS)
958 tn->internal[i] = NULL;
963 return (allDone) ? 1 : 0;
964 } else if (level == 0) {
967 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
969 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
974 YAFFS_TNODES_LEVEL0_BITS) + i;
977 yaffs_FindChunkInGroup(dev,
983 if (foundChunk > 0) {
984 yaffs_DeleteChunk(dev,
997 yaffs_PutLevel0Tnode(dev,tn,i,0);
1001 return (i < 0) ? 1 : 0;
1011 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1014 yaffs_BlockInfo *theBlock;
1016 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1018 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1020 theBlock->softDeletions++;
1025 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1026 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1028 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1031 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1032 __u32 level, int chunkOffset)
1037 yaffs_Device *dev = in->myDev;
1042 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1044 if (tn->internal[i]) {
1046 yaffs_SoftDeleteWorker(in,
1052 YAFFS_TNODES_INTERNAL_BITS)
1055 yaffs_FreeTnode(dev,
1058 tn->internal[i] = NULL;
1060 /* Hoosterman... how could this happen? */
1064 return (allDone) ? 1 : 0;
1065 } else if (level == 0) {
1067 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1068 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1070 /* Note this does not find the real chunk, only the chunk group.
1071 * We make an assumption that a chunk group is not larger than
1074 yaffs_SoftDeleteChunk(dev, theChunk);
1075 yaffs_PutLevel0Tnode(dev,tn,i,0);
1089 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1092 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1093 if (obj->nDataChunks <= 0) {
1094 /* Empty file with no duplicate object headers, just delete it immediately */
1095 yaffs_FreeTnode(obj->myDev,
1096 obj->variant.fileVariant.top);
1097 obj->variant.fileVariant.top = NULL;
1098 T(YAFFS_TRACE_TRACING,
1099 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1101 yaffs_DoGenericObjectDeletion(obj);
1103 yaffs_SoftDeleteWorker(obj,
1104 obj->variant.fileVariant.top,
1105 obj->variant.fileVariant.
1107 obj->softDeleted = 1;
1112 /* Pruning removes any part of the file structure tree that is beyond the
1113 * bounds of the file (ie that does not point to chunks).
1115 * A file should only get pruned when its size is reduced.
1117 * Before pruning, the chunks must be pulled from the tree and the
1118 * level 0 tnode entries must be zeroed out.
1119 * Could also use this for file deletion, but that's probably better handled
1120 * by a special case.
1123 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1124 __u32 level, int del0)
1132 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1133 if (tn->internal[i] && level > 0) {
1135 yaffs_PruneWorker(dev, tn->internal[i],
1137 (i == 0) ? del0 : 1);
1140 if (tn->internal[i]) {
1145 if (hasData == 0 && del0) {
1146 /* Free and return NULL */
1148 yaffs_FreeTnode(dev, tn);
1158 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1159 yaffs_FileStructure * fStruct)
1166 if (fStruct->topLevel > 0) {
1168 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1170 /* Now we have a tree with all the non-zero branches NULL but the height
1171 * is the same as it was.
1172 * Let's see if we can trim internal tnodes to shorten the tree.
1173 * We can do this if only the 0th element in the tnode is in use
1174 * (ie all the non-zero are NULL)
1177 while (fStruct->topLevel && !done) {
1181 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1182 if (tn->internal[i]) {
1188 fStruct->top = tn->internal[0];
1189 fStruct->topLevel--;
1190 yaffs_FreeTnode(dev, tn);
1200 /*-------------------- End of File Structure functions.-------------------*/
1202 /* yaffs_CreateFreeObjects creates a bunch more objects and
1203 * adds them to the object free list.
1205 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1208 yaffs_Object *newObjects;
1209 yaffs_ObjectList *list;
1214 /* make these things */
1215 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1218 T(YAFFS_TRACE_ALLOCATE,
1219 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1223 /* Hook them into the free list */
1224 for (i = 0; i < nObjects - 1; i++) {
1225 newObjects[i].siblings.next =
1226 (struct list_head *)(&newObjects[i + 1]);
1229 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1230 dev->freeObjects = newObjects;
1231 dev->nFreeObjects += nObjects;
1232 dev->nObjectsCreated += nObjects;
1234 /* Now add this bunch of Objects to a list for freeing up. */
1236 list = YMALLOC(sizeof(yaffs_ObjectList));
1238 T(YAFFS_TRACE_ALLOCATE,
1239 (TSTR("Could not add objects to management list" TENDSTR)));
1241 list->objects = newObjects;
1242 list->next = dev->allocatedObjectList;
1243 dev->allocatedObjectList = list;
1250 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1251 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1253 yaffs_Object *tn = NULL;
1255 /* If there are none left make more */
1256 if (!dev->freeObjects) {
1257 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1260 if (dev->freeObjects) {
1261 tn = dev->freeObjects;
1263 (yaffs_Object *) (dev->freeObjects->siblings.next);
1264 dev->nFreeObjects--;
1266 /* Now sweeten it up... */
1268 memset(tn, 0, sizeof(yaffs_Object));
1271 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1272 INIT_LIST_HEAD(&(tn->hardLinks));
1273 INIT_LIST_HEAD(&(tn->hashLink));
1274 INIT_LIST_HEAD(&tn->siblings);
1276 /* Add it to the lost and found directory.
1277 * NB Can't put root or lostNFound in lostNFound so
1278 * check if lostNFound exists first
1280 if (dev->lostNFoundDir) {
1281 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1288 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1293 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1295 obj->fake = 1; /* it is fake so it has no NAND presence... */
1296 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1297 obj->unlinkAllowed = 0; /* ... or unlink it */
1300 obj->yst_mode = mode;
1302 obj->chunkId = 0; /* Not a valid chunk. */
1309 static void yaffs_UnhashObject(yaffs_Object * tn)
1312 yaffs_Device *dev = tn->myDev;
1314 /* If it is still linked into the bucket list, free from the list */
1315 if (!list_empty(&tn->hashLink)) {
1316 list_del_init(&tn->hashLink);
1317 bucket = yaffs_HashFunction(tn->objectId);
1318 dev->objectBucket[bucket].count--;
1323 /* FreeObject frees up a Object and puts it back on the free list */
1324 static void yaffs_FreeObject(yaffs_Object * tn)
1327 yaffs_Device *dev = tn->myDev;
1331 /* We're still hooked up to a cached inode.
1332 * Don't delete now, but mark for later deletion
1334 tn->deferedFree = 1;
1339 yaffs_UnhashObject(tn);
1341 /* Link into the free list. */
1342 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1343 dev->freeObjects = tn;
1344 dev->nFreeObjects++;
1349 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1351 if (obj->deferedFree) {
1352 yaffs_FreeObject(obj);
1358 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1360 /* Free the list of allocated Objects */
1362 yaffs_ObjectList *tmp;
1364 while (dev->allocatedObjectList) {
1365 tmp = dev->allocatedObjectList->next;
1366 YFREE(dev->allocatedObjectList->objects);
1367 YFREE(dev->allocatedObjectList);
1369 dev->allocatedObjectList = tmp;
1372 dev->freeObjects = NULL;
1373 dev->nFreeObjects = 0;
1376 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1380 dev->allocatedObjectList = NULL;
1381 dev->freeObjects = NULL;
1382 dev->nFreeObjects = 0;
1384 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1385 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1386 dev->objectBucket[i].count = 0;
1391 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1396 int lowest = 999999;
1398 /* First let's see if we can find one that's empty. */
1400 for (i = 0; i < 10 && lowest > 0; i++) {
1402 x %= YAFFS_NOBJECT_BUCKETS;
1403 if (dev->objectBucket[x].count < lowest) {
1404 lowest = dev->objectBucket[x].count;
1410 /* If we didn't find an empty list, then try
1411 * looking a bit further for a short one
1414 for (i = 0; i < 10 && lowest > 3; i++) {
1416 x %= YAFFS_NOBJECT_BUCKETS;
1417 if (dev->objectBucket[x].count < lowest) {
1418 lowest = dev->objectBucket[x].count;
1427 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1429 int bucket = yaffs_FindNiceObjectBucket(dev);
1431 /* Now find an object value that has not already been taken
1432 * by scanning the list.
1436 struct list_head *i;
1438 __u32 n = (__u32) bucket;
1440 /* yaffs_CheckObjectHashSanity(); */
1444 n += YAFFS_NOBJECT_BUCKETS;
1445 if (1 || dev->objectBucket[bucket].count > 0) {
1446 list_for_each(i, &dev->objectBucket[bucket].list) {
1447 /* If there is already one in the list */
1449 && list_entry(i, yaffs_Object,
1450 hashLink)->objectId == n) {
1461 static void yaffs_HashObject(yaffs_Object * in)
1463 int bucket = yaffs_HashFunction(in->objectId);
1464 yaffs_Device *dev = in->myDev;
1466 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1467 dev->objectBucket[bucket].count++;
1471 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1473 int bucket = yaffs_HashFunction(number);
1474 struct list_head *i;
1477 list_for_each(i, &dev->objectBucket[bucket].list) {
1478 /* Look if it is in the list */
1480 in = list_entry(i, yaffs_Object, hashLink);
1481 if (in->objectId == number) {
1483 /* Don't tell the VFS about this one if it is defered free */
1484 if (in->deferedFree)
1496 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1497 yaffs_ObjectType type)
1500 yaffs_Object *theObject;
1503 number = yaffs_CreateNewObjectNumber(dev);
1506 theObject = yaffs_AllocateEmptyObject(dev);
1509 theObject->fake = 0;
1510 theObject->renameAllowed = 1;
1511 theObject->unlinkAllowed = 1;
1512 theObject->objectId = number;
1513 yaffs_HashObject(theObject);
1514 theObject->variantType = type;
1515 #ifdef CONFIG_YAFFS_WINCE
1516 yfsd_WinFileTimeNow(theObject->win_atime);
1517 theObject->win_ctime[0] = theObject->win_mtime[0] =
1518 theObject->win_atime[0];
1519 theObject->win_ctime[1] = theObject->win_mtime[1] =
1520 theObject->win_atime[1];
1524 theObject->yst_atime = theObject->yst_mtime =
1525 theObject->yst_ctime = Y_CURRENT_TIME;
1528 case YAFFS_OBJECT_TYPE_FILE:
1529 theObject->variant.fileVariant.fileSize = 0;
1530 theObject->variant.fileVariant.scannedFileSize = 0;
1531 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1532 theObject->variant.fileVariant.topLevel = 0;
1533 theObject->variant.fileVariant.top =
1534 yaffs_GetTnode(dev);
1536 case YAFFS_OBJECT_TYPE_DIRECTORY:
1537 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1540 case YAFFS_OBJECT_TYPE_SYMLINK:
1541 case YAFFS_OBJECT_TYPE_HARDLINK:
1542 case YAFFS_OBJECT_TYPE_SPECIAL:
1543 /* No action required */
1545 case YAFFS_OBJECT_TYPE_UNKNOWN:
1546 /* todo this should not happen */
1554 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1556 yaffs_ObjectType type)
1558 yaffs_Object *theObject = NULL;
1561 theObject = yaffs_FindObjectByNumber(dev, number);
1565 theObject = yaffs_CreateNewObject(dev, number, type);
1572 static YCHAR *yaffs_CloneString(const YCHAR * str)
1574 YCHAR *newStr = NULL;
1577 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1578 yaffs_strcpy(newStr, str);
1586 * Mknod (create) a new object.
1587 * equivalentObject only has meaning for a hard link;
1588 * aliasString only has meaning for a sumlink.
1589 * rdev only has meaning for devices (a subset of special objects)
1592 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1593 yaffs_Object * parent,
1598 yaffs_Object * equivalentObject,
1599 const YCHAR * aliasString, __u32 rdev)
1603 yaffs_Device *dev = parent->myDev;
1605 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1606 if (yaffs_FindObjectByName(parent, name)) {
1610 in = yaffs_CreateNewObject(dev, -1, type);
1615 in->variantType = type;
1617 in->yst_mode = mode;
1619 #ifdef CONFIG_YAFFS_WINCE
1620 yfsd_WinFileTimeNow(in->win_atime);
1621 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1622 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1625 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1627 in->yst_rdev = rdev;
1631 in->nDataChunks = 0;
1633 yaffs_SetObjectName(in, name);
1636 yaffs_AddObjectToDirectory(parent, in);
1638 in->myDev = parent->myDev;
1641 case YAFFS_OBJECT_TYPE_SYMLINK:
1642 in->variant.symLinkVariant.alias =
1643 yaffs_CloneString(aliasString);
1645 case YAFFS_OBJECT_TYPE_HARDLINK:
1646 in->variant.hardLinkVariant.equivalentObject =
1648 in->variant.hardLinkVariant.equivalentObjectId =
1649 equivalentObject->objectId;
1650 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1652 case YAFFS_OBJECT_TYPE_FILE:
1653 case YAFFS_OBJECT_TYPE_DIRECTORY:
1654 case YAFFS_OBJECT_TYPE_SPECIAL:
1655 case YAFFS_OBJECT_TYPE_UNKNOWN:
1660 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1661 /* Could not create the object header, fail the creation */
1662 yaffs_DestroyObject(in);
1671 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1672 __u32 mode, __u32 uid, __u32 gid)
1674 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1675 uid, gid, NULL, NULL, 0);
1678 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1679 __u32 mode, __u32 uid, __u32 gid)
1681 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1682 mode, uid, gid, NULL, NULL, 0);
1685 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1686 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1688 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1689 uid, gid, NULL, NULL, rdev);
1692 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1693 __u32 mode, __u32 uid, __u32 gid,
1694 const YCHAR * alias)
1696 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1697 uid, gid, NULL, alias, 0);
1700 /* yaffs_Link returns the object id of the equivalent object.*/
1701 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1702 yaffs_Object * equivalentObject)
1704 /* Get the real object in case we were fed a hard link as an equivalent object */
1705 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1707 if (yaffs_MknodObject
1708 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1709 equivalentObject, NULL, 0)) {
1710 return equivalentObject;
1717 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1718 const YCHAR * newName, int force, int shadows)
1723 yaffs_Object *existingTarget;
1725 if (newDir == NULL) {
1726 newDir = obj->parent; /* use the old directory */
1729 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1730 T(YAFFS_TRACE_ALWAYS,
1732 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1737 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1738 if (obj->myDev->isYaffs2) {
1739 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1741 unlinkOp = (newDir == obj->myDev->unlinkedDir
1742 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1745 deleteOp = (newDir == obj->myDev->deletedDir);
1747 existingTarget = yaffs_FindObjectByName(newDir, newName);
1749 /* If the object is a file going into the unlinked directory,
1750 * then it is OK to just stuff it in since duplicate names are allowed.
1751 * else only proceed if the new name does not exist and if we're putting
1752 * it into a directory.
1759 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1760 yaffs_SetObjectName(obj, newName);
1763 yaffs_AddObjectToDirectory(newDir, obj);
1768 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1769 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1776 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1777 yaffs_Object * newDir, const YCHAR * newName)
1780 yaffs_Object *existingTarget;
1783 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1784 /* Special case for case insemsitive systems (eg. WinCE).
1785 * While look-up is case insensitive, the name isn't.
1786 * Therefore we might want to change x.txt to X.txt
1788 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1793 obj = yaffs_FindObjectByName(oldDir, oldName);
1795 if (obj && obj->renameAllowed) {
1797 /* Now do the handling for an existing target, if there is one */
1799 existingTarget = yaffs_FindObjectByName(newDir, newName);
1800 if (existingTarget &&
1801 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1802 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1803 /* There is a target that is a non-empty directory, so we fail */
1804 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1805 } else if (existingTarget && existingTarget != obj) {
1806 /* Nuke the target first, using shadowing,
1807 * but only if it isn't the same object
1809 yaffs_ChangeObjectName(obj, newDir, newName, force,
1810 existingTarget->objectId);
1811 yaffs_UnlinkObject(existingTarget);
1814 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1819 /*------------------------- Block Management and Page Allocation ----------------*/
1821 static int yaffs_InitialiseBlocks(yaffs_Device * dev, int nBlocks)
1823 dev->allocationBlock = -1; /* force it to get a new one */
1825 /* Todo we're assuming the malloc will pass. */
1826 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1827 if(!dev->blockInfo){
1828 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1829 dev->blockInfoAlt = 1;
1832 dev->blockInfoAlt = 0;
1834 /* Set up dynamic blockinfo stuff. */
1835 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8;
1836 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1837 if(!dev->chunkBits){
1838 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1839 dev->chunkBitsAlt = 1;
1842 dev->chunkBitsAlt = 0;
1844 if (dev->blockInfo && dev->chunkBits) {
1845 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1846 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1854 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1856 if(dev->blockInfoAlt)
1857 YFREE_ALT(dev->blockInfo);
1859 YFREE(dev->blockInfo);
1860 dev->blockInfoAlt = 0;
1862 dev->blockInfo = NULL;
1864 if(dev->chunkBitsAlt)
1865 YFREE_ALT(dev->chunkBits);
1867 YFREE(dev->chunkBits);
1868 dev->chunkBitsAlt = 0;
1869 dev->chunkBits = NULL;
1872 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1873 yaffs_BlockInfo * bi)
1880 return 1; /* disqualification only applies to yaffs2. */
1882 if (!bi->hasShrinkHeader)
1883 return 1; /* can gc */
1885 /* Find the oldest dirty sequence number if we don't know it and save it
1886 * so we don't have to keep recomputing it.
1888 if (!dev->oldestDirtySequence) {
1889 seq = dev->sequenceNumber;
1891 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1893 b = yaffs_GetBlockInfo(dev, i);
1894 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1895 (b->pagesInUse - b->softDeletions) <
1896 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1897 seq = b->sequenceNumber;
1900 dev->oldestDirtySequence = seq;
1903 /* Can't do gc of this block if there are any blocks older than this one that have
1906 return (bi->sequenceNumber <= dev->oldestDirtySequence);
1912 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1913 * for garbage collection.
1916 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1920 int b = dev->currentDirtyChecker;
1926 yaffs_BlockInfo *bi;
1927 static int nonAggressiveSkip = 0;
1929 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1931 * else (we're doing a leasurely gc), then we only bother to do this if the
1932 * block has only a few pages in use.
1935 nonAggressiveSkip--;
1937 if (!aggressive && (nonAggressiveSkip > 0)) {
1942 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1946 dev->internalEndBlock - dev->internalStartBlock + 1;
1949 dev->internalEndBlock - dev->internalStartBlock + 1;
1950 iterations = iterations / 16;
1951 if (iterations > 200) {
1956 for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1958 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1959 b = dev->internalStartBlock;
1962 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1963 T(YAFFS_TRACE_ERROR,
1964 (TSTR("**>> Block %d is not valid" TENDSTR), b));
1968 bi = yaffs_GetBlockInfo(dev, b);
1970 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1971 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1972 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1974 pagesInUse = (bi->pagesInUse - bi->softDeletions);
1978 dev->currentDirtyChecker = b;
1982 (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1983 dev->nChunksPerBlock - pagesInUse));
1986 dev->oldestDirtySequence = 0;
1989 nonAggressiveSkip = 4;
1995 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1997 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2001 /* If the block is still healthy erase it and mark as clean.
2002 * If the block has had a data failure, then retire it.
2004 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2006 if (!bi->needsRetiring) {
2007 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2009 dev->nErasureFailures++;
2010 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2011 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2015 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2017 for (i = 0; i < dev->nChunksPerBlock; i++) {
2018 if (!yaffs_CheckChunkErased
2019 (dev, blockNo * dev->nChunksPerBlock + i)) {
2020 T(YAFFS_TRACE_ERROR,
2022 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2023 TENDSTR), blockNo, i));
2029 /* Clean it up... */
2030 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2031 dev->nErasedBlocks++;
2033 bi->softDeletions = 0;
2034 bi->hasShrinkHeader = 0;
2035 yaffs_ClearChunkBits(dev, blockNo);
2037 T(YAFFS_TRACE_ERASE,
2038 (TSTR("Erased block %d" TENDSTR), blockNo));
2040 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2042 yaffs_RetireBlock(dev, blockNo);
2043 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2044 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2048 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2052 yaffs_BlockInfo *bi;
2054 if (dev->nErasedBlocks < 1) {
2055 /* Hoosterman we've got a problem.
2056 * Can't get space to gc
2058 T(YAFFS_TRACE_ERROR,
2059 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2064 /* Find an empty block. */
2066 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2067 dev->allocationBlockFinder++;
2068 if (dev->allocationBlockFinder < dev->internalStartBlock
2069 || dev->allocationBlockFinder > dev->internalEndBlock) {
2070 dev->allocationBlockFinder = dev->internalStartBlock;
2073 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2075 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2076 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2077 dev->sequenceNumber++;
2078 bi->sequenceNumber = dev->sequenceNumber;
2079 dev->nErasedBlocks--;
2080 T(YAFFS_TRACE_ALLOCATE,
2081 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2082 dev->allocationBlockFinder, dev->sequenceNumber,
2083 dev->nErasedBlocks));
2084 return dev->allocationBlockFinder;
2088 T(YAFFS_TRACE_ALWAYS,
2090 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2091 TENDSTR), dev->nErasedBlocks));
2098 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2100 int reservedChunks = (dev->nReservedBlocks * dev->nChunksPerBlock);
2101 return (dev->nFreeChunks > reservedChunks);
2104 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2107 yaffs_BlockInfo *bi;
2109 if (dev->allocationBlock < 0) {
2110 /* Get next block to allocate off */
2111 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2112 dev->allocationPage = 0;
2115 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2116 /* Not enough space to allocate unless we're allowed to use the reserve. */
2120 if (dev->nErasedBlocks < dev->nReservedBlocks
2121 && dev->allocationPage == 0) {
2122 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2125 /* Next page please.... */
2126 if (dev->allocationBlock >= 0) {
2127 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2129 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2130 dev->allocationPage;
2132 yaffs_SetChunkBit(dev, dev->allocationBlock,
2133 dev->allocationPage);
2135 dev->allocationPage++;
2139 /* If the block is full set the state to full */
2140 if (dev->allocationPage >= dev->nChunksPerBlock) {
2141 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2142 dev->allocationBlock = -1;
2148 T(YAFFS_TRACE_ERROR,
2149 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2154 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2158 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2160 if (dev->allocationBlock > 0) {
2161 n += (dev->nChunksPerBlock - dev->allocationPage);
2168 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2174 int retVal = YAFFS_OK;
2178 int chunksBefore = yaffs_GetErasedChunks(dev);
2181 yaffs_ExtendedTags tags;
2183 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2185 yaffs_Object *object;
2187 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2189 T(YAFFS_TRACE_TRACING,
2190 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2191 bi->pagesInUse, bi->hasShrinkHeader));
2193 /*yaffs_VerifyFreeChunks(dev); */
2195 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2197 /* Take off the number of soft deleted entries because
2198 * they're going to get really deleted during GC.
2200 dev->nFreeChunks -= bi->softDeletions;
2204 if (!yaffs_StillSomeChunkBits(dev, block)) {
2205 T(YAFFS_TRACE_TRACING,
2207 ("Collecting block %d that has no chunks in use" TENDSTR),
2209 yaffs_BlockBecameDirty(dev, block);
2212 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2214 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2215 chunkInBlock < dev->nChunksPerBlock
2216 && yaffs_StillSomeChunkBits(dev, block);
2217 chunkInBlock++, oldChunk++) {
2218 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2220 /* This page is in use and might need to be copied off */
2224 yaffs_InitialiseTags(&tags);
2226 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2230 yaffs_FindObjectByNumber(dev,
2233 T(YAFFS_TRACE_GC_DETAIL,
2235 ("Collecting page %d, %d %d %d " TENDSTR),
2236 chunkInBlock, tags.objectId, tags.chunkId,
2240 T(YAFFS_TRACE_ERROR,
2242 ("page %d in gc has no object "
2243 TENDSTR), oldChunk));
2246 if (object && object->deleted
2247 && tags.chunkId != 0) {
2248 /* Data chunk in a deleted file, throw it away
2249 * It's a soft deleted data chunk,
2250 * No need to copy this, just forget about it and
2251 * fix up the object.
2254 object->nDataChunks--;
2256 if (object->nDataChunks <= 0) {
2257 /* remeber to clean up the object */
2258 dev->gcCleanupList[cleanups] =
2264 /* Todo object && object->deleted && object->nDataChunks == 0 */
2266 /* Deleted object header with no data chunks.
2267 * Can be discarded and the file deleted.
2269 object->chunkId = 0;
2270 yaffs_FreeTnode(object->myDev,
2273 object->variant.fileVariant.top = NULL;
2274 yaffs_DoGenericObjectDeletion(object);
2276 } else if (object) {
2277 /* It's either a data chunk in a live file or
2278 * an ObjectHeader, so we're interested in it.
2279 * NB Need to keep the ObjectHeaders of deleted files
2280 * until the whole file has been deleted off
2282 tags.serialNumber++;
2286 if (tags.chunkId == 0) {
2287 /* It is an object Id,
2288 * We need to nuke the shrinkheader flags first
2289 * We no longer want the shrinkHeader flag since its work is done
2290 * and if it is left in place it will mess up scanning.
2291 * Also, clear out any shadowing stuff
2294 yaffs_ObjectHeader *oh;
2295 oh = (yaffs_ObjectHeader *)buffer;
2297 oh->shadowsObject = -1;
2298 tags.extraShadows = 0;
2299 tags.extraIsShrinkHeader = 0;
2303 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2306 retVal = YAFFS_FAIL;
2309 /* Ok, now fix up the Tnodes etc. */
2311 if (tags.chunkId == 0) {
2313 object->chunkId = newChunk;
2314 object->serial = tags.serialNumber;
2316 /* It's a data chunk */
2317 yaffs_PutChunkIntoFile
2325 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2330 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2333 /* Do any required cleanups */
2334 for (i = 0; i < cleanups; i++) {
2335 /* Time to delete the file too */
2337 yaffs_FindObjectByNumber(dev,
2338 dev->gcCleanupList[i]);
2340 yaffs_FreeTnode(dev,
2341 object->variant.fileVariant.
2343 object->variant.fileVariant.top = NULL;
2346 ("yaffs: About to finally delete object %d"
2347 TENDSTR), object->objectId));
2348 yaffs_DoGenericObjectDeletion(object);
2355 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2358 ("gc did not increase free chunks before %d after %d"
2359 TENDSTR), chunksBefore, chunksAfter));
2367 /* New garbage collector
2368 * If we're very low on erased blocks then we do aggressive garbage collection
2369 * otherwise we do "leasurely" garbage collection.
2370 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2371 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2373 * The idea is to help clear out space in a more spread-out manner.
2374 * Dunno if it really does anything useful.
2376 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2380 int gcOk = YAFFS_OK;
2383 if (dev->isDoingGC) {
2384 /* Bail out so we don't get recursive gc */
2388 /* This loop should pass the first time.
2389 * We'll only see looping here if the erase of the collected block fails.
2394 if (dev->nErasedBlocks < dev->nReservedBlocks) {
2395 /* We need a block soon...*/
2398 /* We're in no hurry */
2402 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2405 dev->garbageCollections++;
2407 dev->passiveGarbageCollections++;
2412 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2413 dev->nErasedBlocks, aggressive));
2415 gcOk = yaffs_GarbageCollectBlock(dev, block);
2418 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2421 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2422 TENDSTR), dev->nErasedBlocks, maxTries, block));
2424 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2427 return aggressive ? gcOk : YAFFS_OK;
2430 /*------------------------- TAGS --------------------------------*/
2432 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2435 return (tags->chunkId == chunkInObject &&
2436 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2441 /*-------------------- Data file manipulation -----------------*/
2443 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2444 yaffs_ExtendedTags * tags)
2446 /*Get the Tnode, then get the level 0 offset chunk offset */
2449 yaffs_ExtendedTags localTags;
2452 yaffs_Device *dev = in->myDev;
2455 /* Passed a NULL, so use our own tags space */
2459 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2462 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2465 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2471 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2472 yaffs_ExtendedTags * tags)
2474 /* Get the Tnode, then get the level 0 offset chunk offset */
2477 yaffs_ExtendedTags localTags;
2479 yaffs_Device *dev = in->myDev;
2483 /* Passed a NULL, so use our own tags space */
2487 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2491 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2494 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2497 /* Delete the entry in the filestructure (if found) */
2499 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2502 /*T(("No level 0 found for %d\n", chunkInInode)); */
2506 /* T(("Could not find %d to delete\n",chunkInInode)); */
2511 #ifdef YAFFS_PARANOID
2513 static int yaffs_CheckFileSanity(yaffs_Object * in)
2521 yaffs_Tags localTags;
2522 yaffs_Tags *tags = &localTags;
2526 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2527 /* T(("Object not a file\n")); */
2531 objId = in->objectId;
2532 fSize = in->variant.fileVariant.fileSize;
2534 (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2536 for (chunk = 1; chunk <= nChunks; chunk++) {
2537 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2542 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2544 if (yaffs_CheckChunkBits
2545 (dev, theChunk / dev->nChunksPerBlock,
2546 theChunk % dev->nChunksPerBlock)) {
2548 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2552 (tags, in->objectId, chunk, chunkDeleted)) {
2562 /* T(("No level 0 found for %d\n", chunk)); */
2566 return failed ? YAFFS_FAIL : YAFFS_OK;
2571 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2572 int chunkInNAND, int inScan)
2574 /* NB inScan is zero unless scanning.
2575 * For forward scanning, inScan is > 0;
2576 * for backward scanning inScan is < 0
2580 yaffs_Device *dev = in->myDev;
2582 yaffs_ExtendedTags existingTags;
2583 yaffs_ExtendedTags newTags;
2584 unsigned existingSerial, newSerial;
2586 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2587 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2588 * If it is not during Scanning then something went wrong!
2591 T(YAFFS_TRACE_ERROR,
2593 ("yaffs tragedy:attempt to put data chunk into a non-file"
2598 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2602 tn = yaffs_AddOrFindLevel0Tnode(dev, &in->variant.fileVariant,
2608 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2611 /* If we're scanning then we need to test for duplicates
2612 * NB This does not need to be efficient since it should only ever
2613 * happen when the power fails during a write, then only one
2614 * chunk should ever be affected.
2616 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2617 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2620 if (existingChunk != 0) {
2621 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2622 * thus we have to do a FindChunkInFile to get the real chunk id.
2624 * We have a duplicate now we need to decide which one to use:
2626 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2627 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2628 * YAFFS1: Get both sets of tags and compare serial numbers.
2632 /* Only do this for forward scanning */
2633 yaffs_ReadChunkWithTagsFromNAND(dev,
2637 /* Do a proper find */
2639 yaffs_FindChunkInFile(in, chunkInInode,
2643 if (existingChunk <= 0) {
2644 /*Hoosterman - how did this happen? */
2646 T(YAFFS_TRACE_ERROR,
2648 ("yaffs tragedy: existing chunk < 0 in scan"
2653 /* NB The deleted flags should be false, otherwise the chunks will
2654 * not be loaded during a scan
2657 newSerial = newTags.serialNumber;
2658 existingSerial = existingTags.serialNumber;
2661 (in->myDev->isYaffs2 ||
2662 existingChunk <= 0 ||
2663 ((existingSerial + 1) & 3) == newSerial)) {
2664 /* Forward scanning.
2666 * Delete the old one and drop through to update the tnode
2668 yaffs_DeleteChunk(dev, existingChunk, 1,
2671 /* Backward scanning or we want to use the existing one
2673 * Delete the new one and return early so that the tnode isn't changed
2675 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2683 if (existingChunk == 0) {
2687 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2692 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2695 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2697 if (chunkInNAND >= 0) {
2698 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2701 T(YAFFS_TRACE_NANDACCESS,
2702 (TSTR("Chunk %d not found zero instead" TENDSTR),
2704 /* get sane (zero) data if you read a hole */
2705 memset(buffer, 0, in->myDev->nBytesPerChunk);
2711 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2715 yaffs_ExtendedTags tags;
2716 yaffs_BlockInfo *bi;
2722 block = chunkId / dev->nChunksPerBlock;
2723 page = chunkId % dev->nChunksPerBlock;
2725 bi = yaffs_GetBlockInfo(dev, block);
2727 T(YAFFS_TRACE_DELETION,
2728 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2731 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2733 yaffs_InitialiseTags(&tags);
2735 tags.chunkDeleted = 1;
2737 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2738 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2740 dev->nUnmarkedDeletions++;
2743 /* Pull out of the management area.
2744 * If the whole block became dirty, this will kick off an erasure.
2746 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2747 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2748 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2749 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2752 yaffs_ClearChunkBit(dev, block, page);
2756 if (bi->pagesInUse == 0 &&
2757 !bi->hasShrinkHeader &&
2758 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2759 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2760 yaffs_BlockBecameDirty(dev, block);
2764 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2769 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2770 const __u8 * buffer, int nBytes,
2773 /* Find old chunk Need to do this to get serial number
2774 * Write new one and patch into tree.
2775 * Invalidate old tags.
2779 yaffs_ExtendedTags prevTags;
2782 yaffs_ExtendedTags newTags;
2784 yaffs_Device *dev = in->myDev;
2786 yaffs_CheckGarbageCollection(dev);
2788 /* Get the previous chunk at this location in the file if it exists */
2789 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2791 /* Set up new tags */
2792 yaffs_InitialiseTags(&newTags);
2794 newTags.chunkId = chunkInInode;
2795 newTags.objectId = in->objectId;
2796 newTags.serialNumber =
2797 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2798 newTags.byteCount = nBytes;
2801 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2804 if (newChunkId >= 0) {
2805 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2807 if (prevChunkId >= 0) {
2808 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2812 yaffs_CheckFileSanity(in);
2818 /* UpdateObjectHeader updates the header on NAND for an object.
2819 * If name is not NULL, then that new name is used.
2821 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2822 int isShrink, int shadows)
2825 yaffs_BlockInfo *bi;
2827 yaffs_Device *dev = in->myDev;
2833 yaffs_ExtendedTags newTags;
2835 __u8 *buffer = NULL;
2836 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2838 yaffs_ObjectHeader *oh = NULL;
2840 if (!in->fake || force) {
2842 yaffs_CheckGarbageCollection(dev);
2844 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2845 oh = (yaffs_ObjectHeader *) buffer;
2847 prevChunkId = in->chunkId;
2849 if (prevChunkId >= 0) {
2850 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2852 memcpy(oldName, oh->name, sizeof(oh->name));
2855 memset(buffer, 0xFF, dev->nBytesPerChunk);
2857 oh->type = in->variantType;
2858 oh->yst_mode = in->yst_mode;
2859 oh->shadowsObject = shadows;
2861 #ifdef CONFIG_YAFFS_WINCE
2862 oh->win_atime[0] = in->win_atime[0];
2863 oh->win_ctime[0] = in->win_ctime[0];
2864 oh->win_mtime[0] = in->win_mtime[0];
2865 oh->win_atime[1] = in->win_atime[1];
2866 oh->win_ctime[1] = in->win_ctime[1];
2867 oh->win_mtime[1] = in->win_mtime[1];
2869 oh->yst_uid = in->yst_uid;
2870 oh->yst_gid = in->yst_gid;
2871 oh->yst_atime = in->yst_atime;
2872 oh->yst_mtime = in->yst_mtime;
2873 oh->yst_ctime = in->yst_ctime;
2874 oh->yst_rdev = in->yst_rdev;
2877 oh->parentObjectId = in->parent->objectId;
2879 oh->parentObjectId = 0;
2882 if (name && *name) {
2883 memset(oh->name, 0, sizeof(oh->name));
2884 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2885 } else if (prevChunkId) {
2886 memcpy(oh->name, oldName, sizeof(oh->name));
2888 memset(oh->name, 0, sizeof(oh->name));
2891 oh->isShrink = isShrink;
2893 switch (in->variantType) {
2894 case YAFFS_OBJECT_TYPE_UNKNOWN:
2895 /* Should not happen */
2897 case YAFFS_OBJECT_TYPE_FILE:
2899 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2900 || oh->parentObjectId ==
2901 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2902 fileVariant.fileSize;
2904 case YAFFS_OBJECT_TYPE_HARDLINK:
2905 oh->equivalentObjectId =
2906 in->variant.hardLinkVariant.equivalentObjectId;
2908 case YAFFS_OBJECT_TYPE_SPECIAL:
2911 case YAFFS_OBJECT_TYPE_DIRECTORY:
2914 case YAFFS_OBJECT_TYPE_SYMLINK:
2915 yaffs_strncpy(oh->alias,
2916 in->variant.symLinkVariant.alias,
2917 YAFFS_MAX_ALIAS_LENGTH);
2918 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2923 yaffs_InitialiseTags(&newTags);
2925 newTags.chunkId = 0;
2926 newTags.objectId = in->objectId;
2927 newTags.serialNumber = in->serial;
2929 /* Add extra info for file header */
2931 newTags.extraHeaderInfoAvailable = 1;
2932 newTags.extraParentObjectId = oh->parentObjectId;
2933 newTags.extraFileLength = oh->fileSize;
2934 newTags.extraIsShrinkHeader = oh->isShrink;
2935 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2936 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2937 newTags.extraObjectType = in->variantType;
2939 /* Create new chunk in NAND */
2941 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2942 (prevChunkId >= 0) ? 1 : 0);
2944 if (newChunkId >= 0) {
2946 in->chunkId = newChunkId;
2948 if (prevChunkId >= 0) {
2949 yaffs_DeleteChunk(dev, prevChunkId, 1,
2955 /* If this was a shrink, then mark the block that the chunk lives on */
2957 bi = yaffs_GetBlockInfo(in->myDev,
2958 newChunkId /in->myDev-> nChunksPerBlock);
2959 bi->hasShrinkHeader = 1;
2964 retVal = newChunkId;
2969 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2974 /*------------------------ Short Operations Cache ----------------------------------------
2975 * In many situations where there is no high level buffering (eg WinCE) a lot of
2976 * reads might be short sequential reads, and a lot of writes may be short
2977 * sequential writes. eg. scanning/writing a jpeg file.
2978 * In these cases, a short read/write cache can provide a huge perfomance benefit
2979 * with dumb-as-a-rock code.
2980 * In Linux, the page cache provides read buffering aand the short op cache provides write
2983 * There are a limited number (~10) of cache chunks per device so that we don't
2984 * need a very intelligent search.
2987 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2989 yaffs_Device *dev = obj->myDev;
2990 int lowest = -99; /* Stop compiler whining. */
2992 yaffs_ChunkCache *cache;
2993 int chunkWritten = 0;
2994 int nCaches = obj->myDev->nShortOpCaches;
3000 /* Find the dirty cache for this object with the lowest chunk id. */
3001 for (i = 0; i < nCaches; i++) {
3002 if (dev->srCache[i].object == obj &&
3003 dev->srCache[i].dirty) {
3005 || dev->srCache[i].chunkId <
3007 cache = &dev->srCache[i];
3008 lowest = cache->chunkId;
3013 if (cache && !cache->locked) {
3014 /* Write it out and free it up */
3017 yaffs_WriteChunkDataToObject(cache->object,
3023 cache->object = NULL;
3026 } while (cache && chunkWritten > 0);
3029 /* Hoosterman, disk full while writing cache out. */
3030 T(YAFFS_TRACE_ERROR,
3031 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3038 /* Grab us a cache chunk for use.
3039 * First look for an empty one.
3040 * Then look for the least recently used non-dirty one.
3041 * Then look for the least recently used dirty one...., flush and look again.
3043 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3049 if (dev->nShortOpCaches > 0) {
3050 for (i = 0; i < dev->nShortOpCaches; i++) {
3051 if (!dev->srCache[i].object)
3052 return &dev->srCache[i];
3058 usage = 0; /* just to stop the compiler grizzling */
3060 for (i = 0; i < dev->nShortOpCaches; i++) {
3061 if (!dev->srCache[i].dirty &&
3062 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3064 usage = dev->srCache[i].lastUse;
3070 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3077 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3079 yaffs_ChunkCache *cache;
3080 yaffs_Object *theObj;
3085 if (dev->nShortOpCaches > 0) {
3086 /* Try find a non-dirty one... */
3088 cache = yaffs_GrabChunkCacheWorker(dev);
3091 /* They were all dirty, find the last recently used object and flush
3092 * its cache, then find again.
3093 * NB what's here is not very accurate, we actually flush the object
3094 * the last recently used page.
3097 /* With locking we can't assume we can use entry zero */
3104 for (i = 0; i < dev->nShortOpCaches; i++) {
3105 if (dev->srCache[i].object &&
3106 !dev->srCache[i].locked &&
3107 (dev->srCache[i].lastUse < usage || !cache))
3109 usage = dev->srCache[i].lastUse;
3110 theObj = dev->srCache[i].object;
3111 cache = &dev->srCache[i];
3116 if (!cache || cache->dirty) {
3117 /* Flush and try again */
3118 yaffs_FlushFilesChunkCache(theObj);
3119 cache = yaffs_GrabChunkCacheWorker(dev);
3129 /* Find a cached chunk */
3130 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3133 yaffs_Device *dev = obj->myDev;
3135 if (dev->nShortOpCaches > 0) {
3136 for (i = 0; i < dev->nShortOpCaches; i++) {
3137 if (dev->srCache[i].object == obj &&
3138 dev->srCache[i].chunkId == chunkId) {
3141 return &dev->srCache[i];
3148 /* Mark the chunk for the least recently used algorithym */
3149 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3153 if (dev->nShortOpCaches > 0) {
3154 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3155 /* Reset the cache usages */
3157 for (i = 1; i < dev->nShortOpCaches; i++) {
3158 dev->srCache[i].lastUse = 0;
3165 cache->lastUse = dev->srLastUse;
3173 /* Invalidate a single cache page.
3174 * Do this when a whole page gets written,
3175 * ie the short cache for this page is no longer valid.
3177 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3179 if (object->myDev->nShortOpCaches > 0) {
3180 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3183 cache->object = NULL;
3188 /* Invalidate all the cache pages associated with this object
3189 * Do this whenever ther file is deleted or resized.
3191 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3194 yaffs_Device *dev = in->myDev;
3196 if (dev->nShortOpCaches > 0) {
3197 /* Invalidate it. */
3198 for (i = 0; i < dev->nShortOpCaches; i++) {
3199 if (dev->srCache[i].object == in) {
3200 dev->srCache[i].object = NULL;
3206 /*--------------------- File read/write ------------------------
3207 * Read and write have very similar structures.
3208 * In general the read/write has three parts to it
3209 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3210 * Some complete chunks
3211 * An incomplete chunk to end off with
3213 * Curve-balls: the first chunk might also be the last chunk.
3216 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3225 yaffs_ChunkCache *cache;
3232 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3233 start = offset % dev->nBytesPerChunk;
3235 /* OK now check for the curveball where the start and end are in
3238 if ((start + n) < dev->nBytesPerChunk) {
3241 nToCopy = dev->nBytesPerChunk - start;
3244 cache = yaffs_FindChunkCache(in, chunk);
3246 /* If the chunk is already in the cache or it is less than a whole chunk
3247 * then use the cache (if there is caching)
3248 * else bypass the cache.
3250 if (cache || nToCopy != dev->nBytesPerChunk) {
3251 if (dev->nShortOpCaches > 0) {
3253 /* If we can't find the data in the cache, then load it up. */
3256 cache = yaffs_GrabChunkCache(in->myDev);
3258 cache->chunkId = chunk;
3261 yaffs_ReadChunkDataFromObject(in, chunk,
3267 yaffs_UseChunkCache(dev, cache, 0);
3271 #ifdef CONFIG_YAFFS_WINCE
3272 yfsd_UnlockYAFFS(TRUE);
3274 memcpy(buffer, &cache->data[start], nToCopy);
3276 #ifdef CONFIG_YAFFS_WINCE
3277 yfsd_LockYAFFS(TRUE);
3281 /* Read into the local buffer then copy..*/
3284 yaffs_GetTempBuffer(dev, __LINE__);
3285 yaffs_ReadChunkDataFromObject(in, chunk,
3287 #ifdef CONFIG_YAFFS_WINCE
3288 yfsd_UnlockYAFFS(TRUE);
3290 memcpy(buffer, &localBuffer[start], nToCopy);
3292 #ifdef CONFIG_YAFFS_WINCE
3293 yfsd_LockYAFFS(TRUE);
3295 yaffs_ReleaseTempBuffer(dev, localBuffer,
3300 #ifdef CONFIG_YAFFS_WINCE
3301 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3303 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3304 * This is because we otherwise screw up WinCE's memory mapper
3306 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3308 #ifdef CONFIG_YAFFS_WINCE
3309 yfsd_UnlockYAFFS(TRUE);
3311 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3313 #ifdef CONFIG_YAFFS_WINCE
3314 yfsd_LockYAFFS(TRUE);
3315 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3319 /* A full chunk. Read directly into the supplied buffer. */
3320 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3334 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3335 int nBytes, int writeThrough)
3344 int startOfWrite = offset;
3345 int chunkWritten = 0;
3352 while (n > 0 && chunkWritten >= 0) {
3353 chunk = offset / dev->nBytesPerChunk + 1;
3354 start = offset % dev->nBytesPerChunk;
3356 /* OK now check for the curveball where the start and end are in
3360 if ((start + n) < dev->nBytesPerChunk) {
3363 /* Now folks, to calculate how many bytes to write back....
3364 * If we're overwriting and not writing to then end of file then
3365 * we need to write back as much as was there before.
3369 in->variant.fileVariant.fileSize -
3370 ((chunk - 1) * dev->nBytesPerChunk);
3372 if (nBytesRead > dev->nBytesPerChunk) {
3373 nBytesRead = dev->nBytesPerChunk;
3378 (start + n)) ? nBytesRead : (start + n);
3381 nToCopy = dev->nBytesPerChunk - start;
3382 nToWriteBack = dev->nBytesPerChunk;
3385 if (nToCopy != dev->nBytesPerChunk) {
3386 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3387 if (dev->nShortOpCaches > 0) {
3388 yaffs_ChunkCache *cache;
3389 /* If we can't find the data in the cache, then load the cache */
3390 cache = yaffs_FindChunkCache(in, chunk);
3392 && yaffs_CheckSpaceForAllocation(in->
3394 cache = yaffs_GrabChunkCache(in->myDev);
3396 cache->chunkId = chunk;
3399 yaffs_ReadChunkDataFromObject(in, chunk,
3405 yaffs_UseChunkCache(dev, cache, 1);
3407 #ifdef CONFIG_YAFFS_WINCE
3408 yfsd_UnlockYAFFS(TRUE);
3411 memcpy(&cache->data[start], buffer,
3414 #ifdef CONFIG_YAFFS_WINCE
3415 yfsd_LockYAFFS(TRUE);
3418 cache->nBytes = nToWriteBack;
3422 yaffs_WriteChunkDataToObject
3425 cache->data, cache->nBytes,
3431 chunkWritten = -1; /* fail the write */
3434 /* An incomplete start or end chunk (or maybe both start and end chunk)
3435 * Read into the local buffer then copy, then copy over and write back.
3439 yaffs_GetTempBuffer(dev, __LINE__);
3441 yaffs_ReadChunkDataFromObject(in, chunk,
3444 #ifdef CONFIG_YAFFS_WINCE
3445 yfsd_UnlockYAFFS(TRUE);
3448 memcpy(&localBuffer[start], buffer, nToCopy);
3450 #ifdef CONFIG_YAFFS_WINCE
3451 yfsd_LockYAFFS(TRUE);
3454 yaffs_WriteChunkDataToObject(in, chunk,
3459 yaffs_ReleaseTempBuffer(dev, localBuffer,
3466 #ifdef CONFIG_YAFFS_WINCE
3467 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3468 * This is because we otherwise screw up WinCE's memory mapper
3470 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3471 #ifdef CONFIG_YAFFS_WINCE
3472 yfsd_UnlockYAFFS(TRUE);
3474 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3475 #ifdef CONFIG_YAFFS_WINCE
3476 yfsd_LockYAFFS(TRUE);
3479 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3480 dev->nBytesPerChunk,
3482 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3484 /* A full chunk. Write directly from the supplied buffer. */
3486 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3487 dev->nBytesPerChunk,
3490 /* Since we've overwritten the cached data, we better invalidate it. */
3491 yaffs_InvalidateChunkCache(in, chunk);
3494 if (chunkWritten >= 0) {
3503 /* Update file object */
3505 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3506 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3515 /* ---------------------- File resizing stuff ------------------ */
3517 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
3520 yaffs_Device *dev = in->myDev;
3521 int oldFileSize = in->variant.fileVariant.fileSize;
3523 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
3525 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
3526 dev->nBytesPerChunk;
3530 /* Delete backwards so that we don't end up with holes if
3531 * power is lost part-way through the operation.
3533 for (i = lastDel; i >= startDel; i--) {
3534 /* NB this could be optimised somewhat,
3535 * eg. could retrieve the tags and write them without
3536 * using yaffs_DeleteChunk
3539 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3542 (dev->internalStartBlock * dev->nChunksPerBlock)
3544 ((dev->internalEndBlock +
3545 1) * dev->nChunksPerBlock)) {
3546 T(YAFFS_TRACE_ALWAYS,
3547 (TSTR("Found daft chunkId %d for %d" TENDSTR),
3551 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3558 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
3561 int oldFileSize = in->variant.fileVariant.fileSize;
3562 int sizeOfPartialChunk;
3563 yaffs_Device *dev = in->myDev;
3565 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
3567 yaffs_FlushFilesChunkCache(in);
3568 yaffs_InvalidateWholeChunkCache(in);
3570 yaffs_CheckGarbageCollection(dev);
3572 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3573 return yaffs_GetFileSize(in);
3576 if (newSize == oldFileSize) {
3580 if (newSize < oldFileSize) {
3582 yaffs_PruneResizedChunks(in, newSize);
3584 if (sizeOfPartialChunk != 0) {
3585 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
3586 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3588 /* Got to read and rewrite the last chunk with its new size and zero pad */
3589 yaffs_ReadChunkDataFromObject(in, lastChunk,
3592 memset(localBuffer + sizeOfPartialChunk, 0,
3593 dev->nBytesPerChunk - sizeOfPartialChunk);
3595 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
3596 sizeOfPartialChunk, 1);
3598 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3601 in->variant.fileVariant.fileSize = newSize;
3603 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
3605 /* Write a new object header.
3606 * show we've shrunk the file, if need be
3607 * Do this only if the file is not in the deleted directories.
3609 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3610 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
3611 yaffs_UpdateObjectHeader(in, NULL, 0,
3612 (newSize < oldFileSize) ? 1 : 0, 0);
3618 loff_t yaffs_GetFileSize(yaffs_Object * obj)
3620 obj = yaffs_GetEquivalentObject(obj);
3622 switch (obj->variantType) {
3623 case YAFFS_OBJECT_TYPE_FILE:
3624 return obj->variant.fileVariant.fileSize;
3625 case YAFFS_OBJECT_TYPE_SYMLINK:
3626 return yaffs_strlen(obj->variant.symLinkVariant.alias);
3634 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
3638 yaffs_FlushFilesChunkCache(in);
3640 #ifdef CONFIG_YAFFS_WINCE
3641 yfsd_WinFileTimeNow(in->win_mtime);
3644 in->yst_mtime = Y_CURRENT_TIME;
3650 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
3651 0) ? YAFFS_OK : YAFFS_FAIL;
3660 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
3663 /* First off, invalidate the file's data in the cache, without flushing. */
3664 yaffs_InvalidateWholeChunkCache(in);
3666 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3667 /* Move to the unlinked directory so we have a record that it was deleted. */
3668 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
3672 yaffs_RemoveObjectFromDirectory(in);
3673 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
3676 yaffs_FreeObject(in);
3681 /* yaffs_DeleteFile deletes the whole file data
3682 * and the inode associated with the file.
3683 * It does not delete the links associated with the file.
3685 static int yaffs_UnlinkFile(yaffs_Object * in)
3689 int immediateDeletion = 0;
3694 immediateDeletion = 1;
3698 if (in->inUse <= 0) {
3699 immediateDeletion = 1;
3703 if (immediateDeletion) {
3705 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3707 T(YAFFS_TRACE_TRACING,
3708 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3711 in->myDev->nDeletedFiles++;
3712 if (0 && in->myDev->isYaffs2) {
3713 yaffs_ResizeFile(in, 0);
3715 yaffs_SoftDeleteFile(in);
3718 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3726 int yaffs_DeleteFile(yaffs_Object * in)
3728 int retVal = YAFFS_OK;
3730 if (in->nDataChunks > 0) {
3731 /* Use soft deletion if there is data in the file */
3732 if (!in->unlinked) {
3733 retVal = yaffs_UnlinkFile(in);
3735 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3737 in->myDev->nDeletedFiles++;
3738 yaffs_SoftDeleteFile(in);
3740 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3742 /* The file has no data chunks so we toss it immediately */
3743 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3744 in->variant.fileVariant.top = NULL;
3745 yaffs_DoGenericObjectDeletion(in);
3751 static int yaffs_DeleteDirectory(yaffs_Object * in)
3753 /* First check that the directory is empty. */
3754 if (list_empty(&in->variant.directoryVariant.children)) {
3755 return yaffs_DoGenericObjectDeletion(in);
3762 static int yaffs_DeleteSymLink(yaffs_Object * in)
3764 YFREE(in->variant.symLinkVariant.alias);
3766 return yaffs_DoGenericObjectDeletion(in);
3769 static int yaffs_DeleteHardLink(yaffs_Object * in)
3771 /* remove this hardlink from the list assocaited with the equivalent
3774 list_del(&in->hardLinks);
3775 return yaffs_DoGenericObjectDeletion(in);
3778 static void yaffs_DestroyObject(yaffs_Object * obj)
3780 switch (obj->variantType) {
3781 case YAFFS_OBJECT_TYPE_FILE:
3782 yaffs_DeleteFile(obj);
3784 case YAFFS_OBJECT_TYPE_DIRECTORY:
3785 yaffs_DeleteDirectory(obj);
3787 case YAFFS_OBJECT_TYPE_SYMLINK:
3788 yaffs_DeleteSymLink(obj);
3790 case YAFFS_OBJECT_TYPE_HARDLINK:
3791 yaffs_DeleteHardLink(obj);
3793 case YAFFS_OBJECT_TYPE_SPECIAL:
3794 yaffs_DoGenericObjectDeletion(obj);
3796 case YAFFS_OBJECT_TYPE_UNKNOWN:
3797 break; /* should not happen. */
3801 static int yaffs_UnlinkWorker(yaffs_Object * obj)
3804 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3805 return yaffs_DeleteHardLink(obj);
3806 } else if (!list_empty(&obj->hardLinks)) {
3807 /* Curve ball: We're unlinking an object that has a hardlink.
3809 * This problem arises because we are not strictly following
3810 * The Linux link/inode model.
3812 * We can't really delete the object.
3813 * Instead, we do the following:
3814 * - Select a hardlink.
3815 * - Unhook it from the hard links
3816 * - Unhook it from its parent directory (so that the rename can work)
3817 * - Rename the object to the hardlink's name.
3818 * - Delete the hardlink
3823 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3825 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
3827 list_del_init(&hl->hardLinks);
3828 list_del_init(&hl->siblings);
3830 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3832 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
3834 if (retVal == YAFFS_OK) {
3835 retVal = yaffs_DoGenericObjectDeletion(hl);
3840 switch (obj->variantType) {
3841 case YAFFS_OBJECT_TYPE_FILE:
3842 return yaffs_UnlinkFile(obj);
3844 case YAFFS_OBJECT_TYPE_DIRECTORY:
3845 return yaffs_DeleteDirectory(obj);
3847 case YAFFS_OBJECT_TYPE_SYMLINK:
3848 return yaffs_DeleteSymLink(obj);
3850 case YAFFS_OBJECT_TYPE_SPECIAL:
3851 return yaffs_DoGenericObjectDeletion(obj);
3853 case YAFFS_OBJECT_TYPE_HARDLINK:
3854 case YAFFS_OBJECT_TYPE_UNKNOWN:
3862 static int yaffs_UnlinkObject( yaffs_Object *obj)
3865 if (obj && obj->unlinkAllowed) {
3866 return yaffs_UnlinkWorker(obj);
3872 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
3876 obj = yaffs_FindObjectByName(dir, name);
3877 return yaffs_UnlinkObject(obj);
3880 /*----------------------- Initialisation Scanning ---------------------- */
3882 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
3883 int backwardScanning)
3887 if (!backwardScanning) {
3888 /* Handle YAFFS1 forward scanning case
3889 * For YAFFS1 we always do the deletion
3893 /* Handle YAFFS2 case (backward scanning)
3894 * If the shadowed object exists then ignore.
3896 if (yaffs_FindObjectByNumber(dev, objId)) {
3901 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
3902 * We put it in unlinked dir to be cleaned up after the scanning
3905 yaffs_FindOrCreateObjectByNumber(dev, objId,
3906 YAFFS_OBJECT_TYPE_FILE);
3907 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
3908 obj->variant.fileVariant.shrinkSize = 0;
3909 obj->valid = 1; /* So that we don't read any other info for this file */
3918 static int yaffs_Scan(yaffs_Device * dev)
3920 yaffs_ExtendedTags tags;
3925 int nBlocksToScan = 0;
3930 yaffs_BlockState state;
3931 yaffs_Object *hardList = NULL;
3933 yaffs_BlockInfo *bi;
3935 yaffs_ObjectHeader *oh;
3937 yaffs_Object *parent;
3938 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3942 yaffs_BlockIndex *blockIndex = NULL;
3945 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
3946 dev->internalStartBlock, dev->internalEndBlock));
3948 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
3950 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
3952 if (dev->isYaffs2) {
3953 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
3956 /* Scan all the blocks to determine their state */
3957 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
3958 bi = yaffs_GetBlockInfo(dev, blk);
3959 yaffs_ClearChunkBits(dev, blk);
3961 bi->softDeletions = 0;
3963 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
3965 bi->blockState = state;
3966 bi->sequenceNumber = sequenceNumber;
3968 T(YAFFS_TRACE_SCAN_DEBUG,
3969 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
3970 state, sequenceNumber));
3972 if (state == YAFFS_BLOCK_STATE_DEAD) {
3973 T(YAFFS_TRACE_BAD_BLOCKS,
3974 (TSTR("block %d is bad" TENDSTR), blk));
3975 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
3976 T(YAFFS_TRACE_SCAN_DEBUG,
3977 (TSTR("Block empty " TENDSTR)));
3978 dev->nErasedBlocks++;
3979 dev->nFreeChunks += dev->nChunksPerBlock;
3980 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3982 /* Determine the highest sequence number */
3983 if (dev->isYaffs2 &&
3984 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
3985 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
3987 blockIndex[nBlocksToScan].seq = sequenceNumber;
3988 blockIndex[nBlocksToScan].block = blk;
3992 if (sequenceNumber >= dev->sequenceNumber) {
3993 dev->sequenceNumber = sequenceNumber;
3995 } else if (dev->isYaffs2) {
3996 /* TODO: Nasty sequence number! */
3999 ("Block scanning block %d has bad sequence number %d"
4000 TENDSTR), blk, sequenceNumber));
4007 * Dungy old bubble sort for now...
4009 if (dev->isYaffs2) {
4010 yaffs_BlockIndex temp;
4014 for (i = 0; i < nBlocksToScan; i++)
4015 for (j = i + 1; j < nBlocksToScan; j++)
4016 if (blockIndex[i].seq > blockIndex[j].seq) {
4017 temp = blockIndex[j];
4018 blockIndex[j] = blockIndex[i];
4019 blockIndex[i] = temp;
4023 /* Now scan the blocks looking at the data. */
4024 if (dev->isYaffs2) {
4026 endIterator = nBlocksToScan - 1;
4027 T(YAFFS_TRACE_SCAN_DEBUG,
4028 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4030 startIterator = dev->internalStartBlock;
4031 endIterator = dev->internalEndBlock;
4034 /* For each block.... */
4035 for (blockIterator = startIterator; blockIterator <= endIterator;
4038 if (dev->isYaffs2) {
4039 /* get the block to scan in the correct order */
4040 blk = blockIndex[blockIterator].block;
4042 blk = blockIterator;
4045 bi = yaffs_GetBlockInfo(dev, blk);
4046 state = bi->blockState;
4050 /* For each chunk in each block that needs scanning....*/
4051 for (c = 0; c < dev->nChunksPerBlock &&
4052 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4053 /* Read the tags and decide what to do */
4054 chunk = blk * dev->nChunksPerBlock + c;
4056 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4059 /* Let's have a good look at this chunk... */
4061 if (!dev->isYaffs2 && tags.chunkDeleted) {
4067 /*T((" %d %d deleted\n",blk,c)); */
4068 } else if (!tags.chunkUsed) {
4069 /* An unassigned chunk in the block
4070 * This means that either the block is empty or
4071 * this is the one being allocated from
4075 /* We're looking at the first chunk in the block so the block is unused */
4076 state = YAFFS_BLOCK_STATE_EMPTY;
4077 dev->nErasedBlocks++;
4079 /* this is the block being allocated from */
4082 (" Allocating from %d %d" TENDSTR),
4084 state = YAFFS_BLOCK_STATE_ALLOCATING;
4085 dev->allocationBlock = blk;
4086 dev->allocationPage = c;
4087 dev->allocationBlockFinder = blk;
4088 /* Set it to here to encourage the allocator to go forth from here. */
4090 /* Yaffs2 sanity check:
4091 * This should be the one with the highest sequence number
4094 && (dev->sequenceNumber !=
4095 bi->sequenceNumber)) {
4096 T(YAFFS_TRACE_ALWAYS,
4098 ("yaffs: Allocation block %d was not highest sequence id:"
4099 " block seq = %d, dev seq = %d"
4100 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4104 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4105 } else if (tags.chunkId > 0) {
4106 /* chunkId > 0 so it is a data chunk... */
4107 unsigned int endpos;
4109 yaffs_SetChunkBit(dev, blk, c);
4112 in = yaffs_FindOrCreateObjectByNumber(dev,
4115 YAFFS_OBJECT_TYPE_FILE);
4116 /* PutChunkIntoFile checks for a clash (two data chunks with
4117 * the same chunkId).
4119 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4122 (tags.chunkId - 1) * dev->nBytesPerChunk +
4124 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4125 && in->variant.fileVariant.scannedFileSize <
4127 in->variant.fileVariant.
4128 scannedFileSize = endpos;
4129 if (!dev->useHeaderFileSize) {
4130 in->variant.fileVariant.
4132 in->variant.fileVariant.
4137 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4139 /* chunkId == 0, so it is an ObjectHeader.
4140 * Thus, we read in the object header and make the object
4142 yaffs_SetChunkBit(dev, blk, c);
4145 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4149 oh = (yaffs_ObjectHeader *) chunkData;
4151 in = yaffs_FindObjectByNumber(dev,
4153 if (in && in->variantType != oh->type) {
4154 /* This should not happen, but somehow
4155 * Wev'e ended up with an objectId that has been reused but not yet
4156 * deleted, and worse still it has changed type. Delete the old object.
4159 yaffs_DestroyObject(in);
4164 in = yaffs_FindOrCreateObjectByNumber(dev,
4169 if (oh->shadowsObject > 0) {
4170 yaffs_HandleShadowedObject(dev,
4177 /* We have already filled this one. We have a duplicate and need to resolve it. */
4179 unsigned existingSerial = in->serial;
4180 unsigned newSerial = tags.serialNumber;
4182 if (dev->isYaffs2 ||
4183 ((existingSerial + 1) & 3) ==
4185 /* Use new one - destroy the exisiting one */
4186 yaffs_DeleteChunk(dev,
4191 /* Use existing - destroy this one. */
4192 yaffs_DeleteChunk(dev, chunk, 1,
4198 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4199 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4200 /* We only load some info, don't fiddle with directory structure */
4202 in->variantType = oh->type;
4204 in->yst_mode = oh->yst_mode;
4205 #ifdef CONFIG_YAFFS_WINCE
4206 in->win_atime[0] = oh->win_atime[0];
4207 in->win_ctime[0] = oh->win_ctime[0];
4208 in->win_mtime[0] = oh->win_mtime[0];
4209 in->win_atime[1] = oh->win_atime[1];
4210 in->win_ctime[1] = oh->win_ctime[1];
4211 in->win_mtime[1] = oh->win_mtime[1];
4213 in->yst_uid = oh->yst_uid;
4214 in->yst_gid = oh->yst_gid;
4215 in->yst_atime = oh->yst_atime;
4216 in->yst_mtime = oh->yst_mtime;
4217 in->yst_ctime = oh->yst_ctime;
4218 in->yst_rdev = oh->yst_rdev;
4220 in->chunkId = chunk;
4222 } else if (!in->valid) {
4223 /* we need to load this info */
4226 in->variantType = oh->type;
4228 in->yst_mode = oh->yst_mode;
4229 #ifdef CONFIG_YAFFS_WINCE
4230 in->win_atime[0] = oh->win_atime[0];
4231 in->win_ctime[0] = oh->win_ctime[0];
4232 in->win_mtime[0] = oh->win_mtime[0];
4233 in->win_atime[1] = oh->win_atime[1];
4234 in->win_ctime[1] = oh->win_ctime[1];
4235 in->win_mtime[1] = oh->win_mtime[1];
4237 in->yst_uid = oh->yst_uid;
4238 in->yst_gid = oh->yst_gid;
4239 in->yst_atime = oh->yst_atime;
4240 in->yst_mtime = oh->yst_mtime;
4241 in->yst_ctime = oh->yst_ctime;
4242 in->yst_rdev = oh->yst_rdev;
4244 in->chunkId = chunk;
4246 yaffs_SetObjectName(in, oh->name);
4249 /* directory stuff...
4254 yaffs_FindOrCreateObjectByNumber
4255 (dev, oh->parentObjectId,
4256 YAFFS_OBJECT_TYPE_DIRECTORY);
4257 if (parent->variantType ==
4258 YAFFS_OBJECT_TYPE_UNKNOWN) {
4259 /* Set up as a directory */
4260 parent->variantType =
4261 YAFFS_OBJECT_TYPE_DIRECTORY;
4262 INIT_LIST_HEAD(&parent->variant.
4265 } else if (parent->variantType !=
4266 YAFFS_OBJECT_TYPE_DIRECTORY)
4268 /* Hoosterman, another problem....
4269 * We're trying to use a non-directory as a directory
4272 T(YAFFS_TRACE_ERROR,
4274 ("yaffs tragedy: attempting to use non-directory as"
4275 " a directory in scan. Put in lost+found."
4277 parent = dev->lostNFoundDir;
4280 yaffs_AddObjectToDirectory(parent, in);
4282 if (0 && (parent == dev->deletedDir ||
4283 parent == dev->unlinkedDir)) {
4284 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
4285 dev->nDeletedFiles++;
4287 /* Note re hardlinks.
4288 * Since we might scan a hardlink before its equivalent object is scanned
4289 * we put them all in a list.
4290 * After scanning is complete, we should have all the objects, so we run through this
4291 * list and fix up all the chains.
4294 switch (in->variantType) {
4295 case YAFFS_OBJECT_TYPE_UNKNOWN:
4296 /* Todo got a problem */
4298 case YAFFS_OBJECT_TYPE_FILE:
4301 /* Prune back the shrunken chunks */
4302 yaffs_PruneResizedChunks
4304 /* Mark the block as having a shrinkHeader */
4305 bi->hasShrinkHeader = 1;
4308 if (dev->useHeaderFileSize)
4310 in->variant.fileVariant.
4315 case YAFFS_OBJECT_TYPE_HARDLINK:
4316 in->variant.hardLinkVariant.
4317 equivalentObjectId =
4318 oh->equivalentObjectId;
4319 in->hardLinks.next =
4320 (struct list_head *)
4324 case YAFFS_OBJECT_TYPE_DIRECTORY:
4327 case YAFFS_OBJECT_TYPE_SPECIAL:
4330 case YAFFS_OBJECT_TYPE_SYMLINK:
4331 in->variant.symLinkVariant.
4333 yaffs_CloneString(oh->alias);
4337 if (parent == dev->deletedDir) {
4338 yaffs_DestroyObject(in);
4339 bi->hasShrinkHeader = 1;
4345 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4346 /* If we got this far while scanning, then the block is fully allocated.*/
4347 state = YAFFS_BLOCK_STATE_FULL;
4350 bi->blockState = state;
4352 /* Now let's see if it was dirty */
4353 if (bi->pagesInUse == 0 &&
4354 !bi->hasShrinkHeader &&
4355 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4356 yaffs_BlockBecameDirty(dev, blk);
4365 /* Ok, we've done all the scanning.
4366 * Fix up the hard link chains.
4367 * We should now have scanned all the objects, now it's time to add these
4372 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4374 in = yaffs_FindObjectByNumber(dev,
4375 hl->variant.hardLinkVariant.
4376 equivalentObjectId);
4379 /* Add the hardlink pointers */
4380 hl->variant.hardLinkVariant.equivalentObject = in;
4381 list_add(&hl->hardLinks, &in->hardLinks);
4383 /* Todo Need to report/handle this better.
4384 * Got a problem... hardlink to a non-existant object
4386 hl->variant.hardLinkVariant.equivalentObject = NULL;
4387 INIT_LIST_HEAD(&hl->hardLinks);
4393 /* Handle the unlinked files. Since they were left in an unlinked state we should
4397 struct list_head *i;
4398 struct list_head *n;
4401 /* Soft delete all the unlinked files */
4402 list_for_each_safe(i, n,
4403 &dev->unlinkedDir->variant.directoryVariant.
4406 l = list_entry(i, yaffs_Object, siblings);
4407 yaffs_DestroyObject(l);
4412 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4414 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4419 static int yaffs_ScanBackwards(yaffs_Device * dev)
4421 yaffs_ExtendedTags tags;
4426 int nBlocksToScan = 0;
4431 yaffs_BlockState state;
4432 yaffs_Object *hardList = NULL;
4434 yaffs_BlockInfo *bi;
4436 yaffs_ObjectHeader *oh;
4438 yaffs_Object *parent;
4439 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4443 yaffs_BlockIndex *blockIndex = NULL;
4445 if (!dev->isYaffs2) {
4447 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
4453 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
4454 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
4456 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4458 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4460 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4462 /* Scan all the blocks to determine their state */
4463 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4464 bi = yaffs_GetBlockInfo(dev, blk);
4465 yaffs_ClearChunkBits(dev, blk);
4467 bi->softDeletions = 0;
4469 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4471 bi->blockState = state;
4472 bi->sequenceNumber = sequenceNumber;
4474 T(YAFFS_TRACE_SCAN_DEBUG,
4475 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4476 state, sequenceNumber));
4478 if (state == YAFFS_BLOCK_STATE_DEAD) {
4479 T(YAFFS_TRACE_BAD_BLOCKS,
4480 (TSTR("block %d is bad" TENDSTR), blk));
4481 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4482 T(YAFFS_TRACE_SCAN_DEBUG,
4483 (TSTR("Block empty " TENDSTR)));
4484 dev->nErasedBlocks++;
4485 dev->nFreeChunks += dev->nChunksPerBlock;
4486 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4488 /* Determine the highest sequence number */
4489 if (dev->isYaffs2 &&
4490 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4491 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4493 blockIndex[nBlocksToScan].seq = sequenceNumber;
4494 blockIndex[nBlocksToScan].block = blk;
4498 if (sequenceNumber >= dev->sequenceNumber) {
4499 dev->sequenceNumber = sequenceNumber;
4501 } else if (dev->isYaffs2) {
4502 /* TODO: Nasty sequence number! */
4505 ("Block scanning block %d has bad sequence number %d"
4506 TENDSTR), blk, sequenceNumber));
4514 * Dungy old bubble sort for now...
4517 yaffs_BlockIndex temp;
4521 for (i = 0; i < nBlocksToScan; i++)
4522 for (j = i + 1; j < nBlocksToScan; j++)
4523 if (blockIndex[i].seq > blockIndex[j].seq) {
4524 temp = blockIndex[j];
4525 blockIndex[j] = blockIndex[i];
4526 blockIndex[i] = temp;
4530 /* Now scan the blocks looking at the data. */
4532 endIterator = nBlocksToScan - 1;
4533 T(YAFFS_TRACE_SCAN_DEBUG,
4534 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4536 /* For each block.... backwards */
4537 for (blockIterator = endIterator; blockIterator >= startIterator;
4540 /* get the block to scan in the correct order */
4541 blk = blockIndex[blockIterator].block;
4543 bi = yaffs_GetBlockInfo(dev, blk);
4544 state = bi->blockState;
4548 /* For each chunk in each block that needs scanning.... */
4549 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
4550 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
4551 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
4552 /* Scan backwards...
4553 * Read the tags and decide what to do
4555 chunk = blk * dev->nChunksPerBlock + c;
4557 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4560 /* Let's have a good look at this chunk... */
4562 if (!tags.chunkUsed) {
4563 // An unassigned chunk in the block
4564 // This means that either the block is empty or
4565 // this is the one being allocated from
4568 /* We're looking at the first chunk in the block so the block is unused */
4569 state = YAFFS_BLOCK_STATE_EMPTY;
4570 dev->nErasedBlocks++;
4572 /* this is the block being allocated from */
4574 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4577 (" Allocating from %d %d"
4580 state = YAFFS_BLOCK_STATE_ALLOCATING;
4581 dev->allocationBlock = blk;
4582 dev->allocationPage = c;
4583 dev->allocationBlockFinder = blk;
4584 /* Set it to here to encourage the allocator to
4585 * go forth from here.
4588 /* Yaffs2 sanity check:
4589 * This should be the one with the highest sequence number
4592 && (dev->sequenceNumber !=
4593 bi->sequenceNumber)) {
4594 T(YAFFS_TRACE_ALWAYS,
4596 ("yaffs: Allocation block %d was not highest sequence "
4597 "id: block seq = %d, dev seq = %d"
4600 dev->sequenceNumber));
4605 } else if (tags.chunkId > 0) {
4606 /* chunkId > 0 so it is a data chunk... */
4607 unsigned int endpos;
4610 (tags.chunkId - 1) * dev->nBytesPerChunk;
4612 yaffs_SetChunkBit(dev, blk, c);
4615 in = yaffs_FindOrCreateObjectByNumber(dev,
4618 YAFFS_OBJECT_TYPE_FILE);
4619 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4621 in->variant.fileVariant.shrinkSize) {
4622 /* This has not been invalidated by a resize */
4623 yaffs_PutChunkIntoFile(in, tags.chunkId,
4626 /* File size is calculated by looking at the data chunks if we have not
4627 * seen an object header yet. Stop this practice once we find an object header.
4631 1) * dev->nBytesPerChunk +
4634 if (!in->valid && /* have not got an object header yet */
4635 in->variant.fileVariant.
4636 scannedFileSize < endpos) {
4637 in->variant.fileVariant.
4638 scannedFileSize = endpos;
4639 in->variant.fileVariant.
4641 in->variant.fileVariant.
4646 /* This chunk has been invalidated by a resize, so delete */
4647 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4651 /* chunkId == 0, so it is an ObjectHeader.
4652 * Thus, we read in the object header and make the object
4654 yaffs_SetChunkBit(dev, blk, c);
4660 if (tags.extraHeaderInfoAvailable) {
4661 in = yaffs_FindOrCreateObjectByNumber
4662 (dev, tags.objectId,
4663 tags.extraObjectType);
4666 if (!in || !in->valid) {
4668 /* If we don't have valid info then we need to read the chunk
4669 * TODO In future we can probably defer reading the chunk and
4670 * living with invalid data until needed.
4673 yaffs_ReadChunkWithTagsFromNAND(dev,
4678 oh = (yaffs_ObjectHeader *) chunkData;
4681 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
4686 /* TODO Hoosterman we have a problem! */
4687 T(YAFFS_TRACE_ERROR,
4689 ("yaffs tragedy: Could not make object for object %d "
4690 "at chunk %d during scan"
4691 TENDSTR), tags.objectId, chunk));
4696 /* We have already filled this one.
4697 * We have a duplicate that will be discarded, but
4698 * we first have to suck out resize info if it is a file.
4701 if ((in->variantType ==
4702 YAFFS_OBJECT_TYPE_FILE) && ((oh
4707 YAFFS_OBJECT_TYPE_FILE)
4710 extraHeaderInfoAvailable
4715 YAFFS_OBJECT_TYPE_FILE))
4718 (oh) ? oh->fileSize : tags.
4720 __u32 parentObjectId =
4722 parentObjectId : tags.
4723 extraParentObjectId;
4725 (oh) ? oh->isShrink : tags.
4726 extraIsShrinkHeader;
4728 /* If it is deleted (unlinked at start also means deleted)
4729 * we treat the file size as being zeroed at this point.
4731 if (parentObjectId ==
4732 YAFFS_OBJECTID_DELETED
4733 || parentObjectId ==
4734 YAFFS_OBJECTID_UNLINKED) {
4740 in->variant.fileVariant.
4741 shrinkSize > thisSize) {
4742 in->variant.fileVariant.
4748 bi->hasShrinkHeader = 1;
4752 /* Use existing - destroy this one. */
4753 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4758 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4760 YAFFS_OBJECTID_LOSTNFOUND)) {
4761 /* We only load some info, don't fiddle with directory structure */
4763 in->variantType = oh->type;
4765 in->yst_mode = oh->yst_mode;
4766 #ifdef CONFIG_YAFFS_WINCE
4767 in->win_atime[0] = oh->win_atime[0];
4768 in->win_ctime[0] = oh->win_ctime[0];
4769 in->win_mtime[0] = oh->win_mtime[0];
4770 in->win_atime[1] = oh->win_atime[1];
4771 in->win_ctime[1] = oh->win_ctime[1];
4772 in->win_mtime[1] = oh->win_mtime[1];
4774 in->yst_uid = oh->yst_uid;
4775 in->yst_gid = oh->yst_gid;
4776 in->yst_atime = oh->yst_atime;
4777 in->yst_mtime = oh->yst_mtime;
4778 in->yst_ctime = oh->yst_ctime;
4779 in->yst_rdev = oh->yst_rdev;
4781 in->chunkId = chunk;
4783 } else if (!in->valid) {
4784 /* we need to load this info */
4787 in->variantType = oh->type;
4789 in->yst_mode = oh->yst_mode;
4790 #ifdef CONFIG_YAFFS_WINCE
4791 in->win_atime[0] = oh->win_atime[0];
4792 in->win_ctime[0] = oh->win_ctime[0];
4793 in->win_mtime[0] = oh->win_mtime[0];
4794 in->win_atime[1] = oh->win_atime[1];
4795 in->win_ctime[1] = oh->win_ctime[1];
4796 in->win_mtime[1] = oh->win_mtime[1];
4798 in->yst_uid = oh->yst_uid;
4799 in->yst_gid = oh->yst_gid;
4800 in->yst_atime = oh->yst_atime;
4801 in->yst_mtime = oh->yst_mtime;
4802 in->yst_ctime = oh->yst_ctime;
4803 in->yst_rdev = oh->yst_rdev;
4805 in->chunkId = chunk;
4807 if (oh->shadowsObject > 0) {
4808 yaffs_HandleShadowedObject(dev,
4814 yaffs_SetObjectName(in, oh->name);
4817 /* directory stuff...
4822 yaffs_FindOrCreateObjectByNumber
4823 (dev, oh->parentObjectId,
4824 YAFFS_OBJECT_TYPE_DIRECTORY);
4825 if (parent->variantType ==
4826 YAFFS_OBJECT_TYPE_UNKNOWN) {
4827 /* Set up as a directory */
4828 parent->variantType =
4829 YAFFS_OBJECT_TYPE_DIRECTORY;
4830 INIT_LIST_HEAD(&parent->variant.
4833 } else if (parent->variantType !=
4834 YAFFS_OBJECT_TYPE_DIRECTORY)
4836 /* Hoosterman, another problem....
4837 * We're trying to use a non-directory as a directory
4840 T(YAFFS_TRACE_ERROR,
4842 ("yaffs tragedy: attempting to use non-directory as"
4843 " a directory in scan. Put in lost+found."
4845 parent = dev->lostNFoundDir;
4848 yaffs_AddObjectToDirectory(parent, in);
4850 if ((parent == dev->deletedDir ||
4851 parent == dev->unlinkedDir)) {
4852 /* If it is unlinked at start up then it wants deleting */
4857 /* Mark the block as having a shrinkHeader */
4858 bi->hasShrinkHeader = 1;
4861 /* Note re hardlinks.
4862 * Since we might scan a hardlink before its equivalent object is scanned
4863 * we put them all in a list.
4864 * After scanning is complete, we should have all the objects, so we run
4865 * through this list and fix up all the chains.
4868 switch (in->variantType) {
4869 case YAFFS_OBJECT_TYPE_UNKNOWN:
4870 /* Todo got a problem */
4872 case YAFFS_OBJECT_TYPE_FILE:
4874 if (in->variant.fileVariant.
4877 /* This covers the case where the file size is greater
4878 * than where the data is
4879 * This will happen if the file is resized to be larger
4880 * than its current data extents.
4882 in->variant.fileVariant.fileSize =
4884 in->variant.fileVariant.scannedFileSize =
4885 in->variant.fileVariant.fileSize;
4889 in->variant.fileVariant.shrinkSize >
4891 in->variant.fileVariant.shrinkSize =
4896 case YAFFS_OBJECT_TYPE_HARDLINK:
4898 in->variant.hardLinkVariant.equivalentObjectId =
4899 oh->equivalentObjectId;
4900 in->hardLinks.next =
4901 (struct list_head *) hardList;
4905 case YAFFS_OBJECT_TYPE_DIRECTORY:
4908 case YAFFS_OBJECT_TYPE_SPECIAL:
4911 case YAFFS_OBJECT_TYPE_SYMLINK:
4912 in->variant.symLinkVariant.
4914 yaffs_CloneString(oh->
4923 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4924 /* If we got this far while scanning, then the block is fully allocated. */
4925 state = YAFFS_BLOCK_STATE_FULL;
4928 bi->blockState = state;
4930 /* Now let's see if it was dirty */
4931 if (bi->pagesInUse == 0 &&
4932 !bi->hasShrinkHeader &&
4933 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4934 yaffs_BlockBecameDirty(dev, blk);
4942 /* Ok, we've done all the scanning.
4943 * Fix up the hard link chains.
4944 * We should now have scanned all the objects, now it's time to add these
4949 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4951 in = yaffs_FindObjectByNumber(dev,
4952 hl->variant.hardLinkVariant.
4953 equivalentObjectId);
4956 /* Add the hardlink pointers */
4957 hl->variant.hardLinkVariant.equivalentObject = in;
4958 list_add(&hl->hardLinks, &in->hardLinks);
4960 /* Todo Need to report/handle this better.
4961 * Got a problem... hardlink to a non-existant object
4963 hl->variant.hardLinkVariant.equivalentObject = NULL;
4964 INIT_LIST_HEAD(&hl->hardLinks);
4971 struct list_head *i;
4972 struct list_head *n;
4976 /* Soft delete all the unlinked files */
4977 list_for_each_safe(i, n,
4978 &dev->unlinkedDir->variant.directoryVariant.
4981 l = list_entry(i, yaffs_Object, siblings);
4982 yaffs_DestroyObject(l);
4986 /* Soft delete all the deletedDir files */
4987 list_for_each_safe(i, n,
4988 &dev->deletedDir->variant.directoryVariant.
4991 l = list_entry(i, yaffs_Object, siblings);
4992 yaffs_DestroyObject(l);
4998 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5000 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5005 /*------------------------------ Directory Functions ----------------------------- */
5007 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5009 yaffs_Device *dev = obj->myDev;
5011 if(dev && dev->removeObjectCallback)
5012 dev->removeObjectCallback(obj);
5014 list_del_init(&obj->siblings);
5019 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5024 T(YAFFS_TRACE_ALWAYS,
5026 ("tragedy: Trying to add an object to a null pointer directory"
5030 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5031 T(YAFFS_TRACE_ALWAYS,
5033 ("tragedy: Trying to add an object to a non-directory"
5038 if (obj->siblings.prev == NULL) {
5039 /* Not initialised */
5040 INIT_LIST_HEAD(&obj->siblings);
5042 } else if (!list_empty(&obj->siblings)) {
5043 /* If it is holed up somewhere else, un hook it */
5044 yaffs_RemoveObjectFromDirectory(obj);
5047 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5048 obj->parent = directory;
5050 if (directory == obj->myDev->unlinkedDir
5051 || directory == obj->myDev->deletedDir) {
5053 obj->myDev->nUnlinkedFiles++;
5054 obj->renameAllowed = 0;
5058 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5063 struct list_head *i;
5064 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5073 T(YAFFS_TRACE_ALWAYS,
5075 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5079 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5080 T(YAFFS_TRACE_ALWAYS,
5082 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5086 sum = yaffs_CalcNameSum(name);
5088 list_for_each(i, &directory->variant.directoryVariant.children) {
5090 l = list_entry(i, yaffs_Object, siblings);
5092 /* Special case for lost-n-found */
5093 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5094 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5097 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5099 /* LostnFound cunk called Objxxx
5102 yaffs_GetObjectName(l, buffer,
5103 YAFFS_MAX_NAME_LENGTH);
5104 if (yaffs_strcmp(name, buffer) == 0) {
5117 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5118 int (*fn) (yaffs_Object *))
5120 struct list_head *i;
5124 T(YAFFS_TRACE_ALWAYS,
5126 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5130 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5131 T(YAFFS_TRACE_ALWAYS,
5133 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5137 list_for_each(i, &theDir->variant.directoryVariant.children) {
5139 l = list_entry(i, yaffs_Object, siblings);
5151 /* GetEquivalentObject dereferences any hard links to get to the
5155 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5157 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5158 /* We want the object id of the equivalent object, not this one */
5159 obj = obj->variant.hardLinkVariant.equivalentObject;
5165 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5167 memset(name, 0, buffSize * sizeof(YCHAR));
5169 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5170 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5171 } else if (obj->chunkId <= 0) {
5173 /* make up a name */
5174 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5176 yaffs_strncpy(name, locName, buffSize - 1);
5179 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5180 else if (obj->shortName[0]) {
5181 yaffs_strcpy(name, obj->shortName);
5185 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5187 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5189 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5191 if (obj->chunkId >= 0) {
5192 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5193 obj->chunkId, buffer,
5196 yaffs_strncpy(name, oh->name, buffSize - 1);
5198 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5201 return yaffs_strlen(name);
5204 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5207 /* Dereference any hard linking */
5208 obj = yaffs_GetEquivalentObject(obj);
5210 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5211 return obj->variant.fileVariant.fileSize;
5213 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5214 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5216 /* Only a directory should drop through to here */
5217 return obj->myDev->nBytesPerChunk;
5221 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5224 struct list_head *i;
5226 if (!obj->unlinked) {
5227 count++; /* the object itself */
5229 list_for_each(i, &obj->hardLinks) {
5230 count++; /* add the hard links; */
5236 int yaffs_GetObjectInode(yaffs_Object * obj)
5238 obj = yaffs_GetEquivalentObject(obj);
5240 return obj->objectId;
5243 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5245 obj = yaffs_GetEquivalentObject(obj);
5247 switch (obj->variantType) {
5248 case YAFFS_OBJECT_TYPE_FILE:
5251 case YAFFS_OBJECT_TYPE_DIRECTORY:
5254 case YAFFS_OBJECT_TYPE_SYMLINK:
5257 case YAFFS_OBJECT_TYPE_HARDLINK:
5260 case YAFFS_OBJECT_TYPE_SPECIAL:
5261 if (S_ISFIFO(obj->yst_mode))
5263 if (S_ISCHR(obj->yst_mode))
5265 if (S_ISBLK(obj->yst_mode))
5267 if (S_ISSOCK(obj->yst_mode))
5275 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5277 obj = yaffs_GetEquivalentObject(obj);
5278 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5279 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5281 return yaffs_CloneString(_Y(""));
5285 #ifndef CONFIG_YAFFS_WINCE
5287 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5289 unsigned int valid = attr->ia_valid;
5291 if (valid & ATTR_MODE)
5292 obj->yst_mode = attr->ia_mode;
5293 if (valid & ATTR_UID)
5294 obj->yst_uid = attr->ia_uid;
5295 if (valid & ATTR_GID)
5296 obj->yst_gid = attr->ia_gid;
5298 if (valid & ATTR_ATIME)
5299 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5300 if (valid & ATTR_CTIME)
5301 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5302 if (valid & ATTR_MTIME)
5303 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5305 if (valid & ATTR_SIZE)
5306 yaffs_ResizeFile(obj, attr->ia_size);
5308 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5313 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5315 unsigned int valid = 0;
5317 attr->ia_mode = obj->yst_mode;
5319 attr->ia_uid = obj->yst_uid;
5321 attr->ia_gid = obj->yst_gid;
5324 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5325 valid |= ATTR_ATIME;
5326 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5327 valid |= ATTR_CTIME;
5328 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5329 valid |= ATTR_MTIME;
5331 attr->ia_size = yaffs_GetFileSize(obj);
5334 attr->ia_valid = valid;
5343 int yaffs_DumpObject(yaffs_Object * obj)
5347 yaffs_GetObjectName(obj, name, 256);
5349 T(YAFFS_TRACE_ALWAYS,
5351 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5352 " chunk %d type %d size %d\n"
5353 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5354 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5355 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5361 /*---------------------------- Initialisation code -------------------------------------- */
5363 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5366 /* Common functions, gotta have */
5367 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5370 #ifdef CONFIG_YAFFS_YAFFS2
5372 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5373 if (dev->writeChunkWithTagsToNAND &&
5374 dev->readChunkWithTagsFromNAND &&
5375 !dev->writeChunkToNAND &&
5376 !dev->readChunkFromNAND &&
5377 dev->markNANDBlockBad && dev->queryNANDBlock)
5381 /* Can use the "spare" style interface for yaffs1 */
5382 if (!dev->isYaffs2 &&
5383 !dev->writeChunkWithTagsToNAND &&
5384 !dev->readChunkWithTagsFromNAND &&
5385 dev->writeChunkToNAND &&
5386 dev->readChunkFromNAND &&
5387 !dev->markNANDBlockBad && !dev->queryNANDBlock)
5393 int yaffs_GutsInitialise(yaffs_Device * dev)
5400 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5402 /* Check stuff that must be set */
5405 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5409 dev->internalStartBlock = dev->startBlock;
5410 dev->internalEndBlock = dev->endBlock;
5411 dev->blockOffset = 0;
5412 dev->chunkOffset = 0;
5413 dev->nFreeChunks = 0;
5415 if (dev->startBlock == 0) {
5416 dev->internalStartBlock = dev->startBlock + 1;
5417 dev->internalEndBlock = dev->endBlock + 1;
5418 dev->blockOffset = 1;
5419 dev->chunkOffset = dev->nChunksPerBlock;
5422 /* Check geometry parameters. */
5424 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
5426 T(YAFFS_TRACE_ALWAYS,
5428 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
5429 TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
5433 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5434 T(YAFFS_TRACE_ALWAYS,
5435 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5439 /* Got the right mix of functions? */
5440 if (!yaffs_CheckDevFunctions(dev)) {
5441 /* Function missing */
5442 T(YAFFS_TRACE_ALWAYS,
5444 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5449 /* This is really a compilation check. */
5450 if (!yaffs_CheckStructures()) {
5451 T(YAFFS_TRACE_ALWAYS,
5452 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5456 if (dev->isMounted) {
5457 T(YAFFS_TRACE_ALWAYS,
5458 (TSTR("yaffs: device already mounted\n" TENDSTR)));
5462 /* Finished with most checks. One or two more checks happen later on too. */
5466 nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5468 /* OK now calculate a few things for the device
5469 * Calculate chunkGroupBits.
5470 * We need to find the next power of 2 > than internalEndBlock
5473 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
5475 for (bits = extraBits = 0; x > 1; bits++) {
5484 /* Set up tnode width if wide tnodes are enabled. */
5485 if(!dev->wideTnodesDisabled){
5486 /* bits must be even so that we end up with 32-bit words */
5490 dev->tnodeWidth = 16;
5492 dev->tnodeWidth = bits;
5495 dev->tnodeWidth = 16;
5497 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5499 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5500 * so if the bitwidth of the
5501 * chunk range we're using is greater than 16 we need
5502 * to figure out chunk shift and chunkGroupSize
5505 if (bits <= dev->tnodeWidth)
5506 dev->chunkGroupBits = 0;
5508 dev->chunkGroupBits = bits - dev->tnodeWidth;
5511 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5513 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
5514 /* We have a problem because the soft delete won't work if
5515 * the chunk group size > chunks per block.
5516 * This can be remedied by using larger "virtual blocks".
5518 T(YAFFS_TRACE_ALWAYS,
5519 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5524 /* OK, we've finished verifying the device, lets continue with initialisation */
5526 /* More device initialisation */
5527 dev->garbageCollections = 0;
5528 dev->passiveGarbageCollections = 0;
5529 dev->currentDirtyChecker = 0;
5530 dev->bufferedBlock = -1;
5531 dev->doingBufferedBlockRewrite = 0;
5532 dev->nDeletedFiles = 0;
5533 dev->nBackgroundDeletions = 0;
5534 dev->nUnlinkedFiles = 0;
5536 dev->eccUnfixed = 0;
5537 dev->tagsEccFixed = 0;
5538 dev->tagsEccUnfixed = 0;
5539 dev->nErasureFailures = 0;
5540 dev->nErasedBlocks = 0;
5543 /* Initialise temporary buffers */
5546 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5547 dev->tempBuffer[i].line = 0; /* not in use */
5548 dev->tempBuffer[i].buffer =
5549 YMALLOC(dev->nBytesPerChunk);
5553 yaffs_InitialiseBlocks(dev, nBlocks);
5555 yaffs_InitialiseTnodes(dev);
5557 yaffs_InitialiseObjects(dev);
5559 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
5561 if (dev->nShortOpCaches > 0) {
5564 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
5565 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5569 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
5571 for (i = 0; i < dev->nShortOpCaches; i++) {
5572 dev->srCache[i].object = NULL;
5573 dev->srCache[i].lastUse = 0;
5574 dev->srCache[i].dirty = 0;
5575 dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
5582 /* Initialise the unlinked, root and lost and found directories */
5583 dev->lostNFoundDir = dev->rootDir = NULL;
5584 dev->unlinkedDir = dev->deletedDir = NULL;
5587 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5589 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5592 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5593 YAFFS_ROOT_MODE | S_IFDIR);
5594 dev->lostNFoundDir =
5595 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5596 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5597 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5599 if (dev->isYaffs2) {
5600 dev->useHeaderFileSize = 1;
5603 /* Now scan the flash. */
5605 yaffs_ScanBackwards(dev);
5609 /* Zero out stats */
5610 dev->nPageReads = 0;
5611 dev->nPageWrites = 0;
5612 dev->nBlockErasures = 0;
5614 dev->nRetriedWrites = 0;
5616 dev->nRetiredBlocks = 0;
5618 yaffs_VerifyFreeChunks(dev);
5620 T(YAFFS_TRACE_TRACING,
5621 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5626 void yaffs_Deinitialise(yaffs_Device * dev)
5628 if (dev->isMounted) {
5631 yaffs_DeinitialiseBlocks(dev);
5632 yaffs_DeinitialiseTnodes(dev);
5633 yaffs_DeinitialiseObjects(dev);
5634 if (dev->nShortOpCaches > 0) {
5636 for (i = 0; i < dev->nShortOpCaches; i++) {
5637 YFREE(dev->srCache[i].data);
5640 YFREE(dev->srCache);
5643 YFREE(dev->gcCleanupList);
5645 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5646 YFREE(dev->tempBuffer[i].buffer);
5654 static int yaffs_CountFreeChunks(yaffs_Device * dev)
5659 yaffs_BlockInfo *blk;
5661 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
5663 blk = yaffs_GetBlockInfo(dev, b);
5665 switch (blk->blockState) {
5666 case YAFFS_BLOCK_STATE_EMPTY:
5667 case YAFFS_BLOCK_STATE_ALLOCATING:
5668 case YAFFS_BLOCK_STATE_COLLECTING:
5669 case YAFFS_BLOCK_STATE_FULL:
5671 (dev->nChunksPerBlock - blk->pagesInUse +
5672 blk->softDeletions);
5683 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
5685 /* This is what we report to the outside world */
5688 int nDirtyCacheChunks;
5691 nFree = dev->nFreeChunks;
5693 nFree = yaffs_CountFreeChunks(dev);
5696 /* Now count the number of dirty chunks in the cache and subtract those */
5700 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
5701 if (dev->srCache[i].dirty)
5702 nDirtyCacheChunks++;
5706 nFree -= nDirtyCacheChunks;
5708 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
5717 static int yaffs_freeVerificationFailures;
5719 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
5721 int counted = yaffs_CountFreeChunks(dev);
5723 int difference = dev->nFreeChunks - counted;
5726 T(YAFFS_TRACE_ALWAYS,
5727 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
5728 dev->nFreeChunks, counted, difference));
5729 yaffs_freeVerificationFailures++;
5733 /*---------------------------------------- YAFFS test code ----------------------*/
5735 #define yaffs_CheckStruct(structure,syze, name) \
5736 if(sizeof(structure) != syze) \
5738 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
5739 name,syze,sizeof(structure))); \
5740 return YAFFS_FAIL; \
5743 static int yaffs_CheckStructures(void)
5745 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
5746 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
5747 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
5748 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5749 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
5751 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")