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.27 2005-12-20 04:02:18 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
26 #ifdef CONFIG_YAFFS_WINCE
27 void yfsd_LockYAFFS(BOOL fsLockOnly);
28 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
31 #define YAFFS_PASSIVE_GC_CHUNKS 2
33 #include "yaffs_ecc.h"
37 static Y_INLINE int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev,
40 yaffs_ExtendedTags * tags);
41 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
44 yaffs_ExtendedTags * tags);
45 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo);
46 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
48 yaffs_BlockState * state,
49 unsigned *sequenceNumber);
50 /* Robustification (if it ever comes about...) */
51 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
52 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND);
53 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
55 const yaffs_ExtendedTags * tags);
56 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
57 const yaffs_ExtendedTags * tags);
59 /* Other local prototypes */
60 static int yaffs_UnlinkObject( yaffs_Object *obj);
62 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
64 yaffs_ExtendedTags * tags,
66 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
67 int chunkInNAND, int inScan);
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
70 yaffs_ObjectType type);
71 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
73 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
74 int force, int isShrink, int shadows);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
78 int chunkOffset, int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
83 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
84 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
87 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
90 static int yaffs_UnlinkWorker(yaffs_Object * obj);
91 static void yaffs_DestroyObject(yaffs_Object * obj);
93 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
96 loff_t yaffs_GetFileSize(yaffs_Object * obj);
98 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
100 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
113 * Start of real code.
122 static int yaffs_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND,
124 yaffs_ExtendedTags * tags)
126 chunkInNAND -= dev->chunkOffset;
128 if (dev->readChunkWithTagsFromNAND)
129 return dev->readChunkWithTagsFromNAND(dev, chunkInNAND, buffer,
132 return yaffs_TagsCompatabilityReadChunkWithTagsFromNAND(dev,
138 static Y_INLINE int yaffs_WriteChunkWithTagsToNAND(yaffs_Device * dev,
141 yaffs_ExtendedTags * tags)
143 chunkInNAND -= dev->chunkOffset;
146 tags->sequenceNumber = dev->sequenceNumber;
148 if (!yaffs_ValidateTags(tags)) {
150 (TSTR("Writing uninitialised tags" TENDSTR)));
154 (TSTR("Writing chunk %d tags %d %d" TENDSTR), chunkInNAND,
155 tags->objectId, tags->chunkId));
157 T(YAFFS_TRACE_ERROR, (TSTR("Writing with no tags" TENDSTR)));
161 if (dev->writeChunkWithTagsToNAND)
162 return dev->writeChunkWithTagsToNAND(dev, chunkInNAND, buffer,
165 return yaffs_TagsCompatabilityWriteChunkWithTagsToNAND(dev,
171 static Y_INLINE int yaffs_MarkBlockBad(yaffs_Device * dev, int blockNo)
173 blockNo -= dev->blockOffset;
175 if (dev->markNANDBlockBad)
176 return dev->markNANDBlockBad(dev, blockNo);
178 return yaffs_TagsCompatabilityMarkNANDBlockBad(dev, blockNo);
180 static Y_INLINE int yaffs_QueryInitialBlockState(yaffs_Device * dev,
182 yaffs_BlockState * state,
183 unsigned *sequenceNumber)
185 blockNo -= dev->blockOffset;
187 if (dev->queryNANDBlock)
188 return dev->queryNANDBlock(dev, blockNo, state, sequenceNumber);
190 return yaffs_TagsCompatabilityQueryNANDBlock(dev, blockNo,
195 static int yaffs_EraseBlockInNAND(struct yaffs_DeviceStruct *dev,
200 blockInNAND -= dev->blockOffset;
202 dev->nBlockErasures++;
203 result = dev->eraseBlockInNAND(dev, blockInNAND);
205 /* If at first we don't succeed, try again *once*.*/
207 result = dev->eraseBlockInNAND(dev, blockInNAND);
211 static int yaffs_InitialiseNAND(struct yaffs_DeviceStruct *dev)
213 return dev->initialiseNAND(dev);
217 * Temporary buffer manipulations.
220 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
223 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
224 if (dev->tempBuffer[i].line == 0) {
225 dev->tempBuffer[i].line = lineNo;
226 if ((i + 1) > dev->maxTemp) {
227 dev->maxTemp = i + 1;
228 for (j = 0; j <= i; j++)
229 dev->tempBuffer[j].maxLine =
230 dev->tempBuffer[j].line;
233 return dev->tempBuffer[i].buffer;
237 T(YAFFS_TRACE_BUFFERS,
238 (TSTR("Out of temp buffers at line %d, other held by lines:"),
240 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
243 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
246 * If we got here then we have to allocate an unmanaged one
250 dev->unmanagedTempAllocations++;
251 return YMALLOC(dev->nBytesPerChunk);
255 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
259 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
260 if (dev->tempBuffer[i].buffer == buffer) {
261 dev->tempBuffer[i].line = 0;
267 /* assume it is an unmanaged one. */
268 T(YAFFS_TRACE_BUFFERS,
269 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
272 dev->unmanagedTempDeallocations++;
278 * Chunk bitmap manipulations
281 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
283 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
285 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
289 return dev->chunkBits +
290 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
293 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
295 __u8 *blkBits = yaffs_BlockBits(dev, blk);
297 memset(blkBits, 0, dev->chunkBitmapStride);
300 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
302 __u8 *blkBits = yaffs_BlockBits(dev, blk);
304 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
307 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
309 __u8 *blkBits = yaffs_BlockBits(dev, blk);
311 blkBits[chunk / 8] |= (1 << (chunk & 7));
314 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
316 __u8 *blkBits = yaffs_BlockBits(dev, blk);
317 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
320 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
322 __u8 *blkBits = yaffs_BlockBits(dev, blk);
324 for (i = 0; i < dev->chunkBitmapStride; i++) {
333 * Simple hash function. Needs to have a reasonable spread
336 static Y_INLINE int yaffs_HashFunction(int n)
338 return (n % YAFFS_NOBJECT_BUCKETS);
342 * Access functions to useful fake objects
345 yaffs_Object *yaffs_Root(yaffs_Device * dev)
350 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
352 return dev->lostNFoundDir;
357 * Erased NAND checking functions
360 int yaffs_CheckFF(__u8 * buffer, int nBytes)
362 /* Horrible, slow implementation */
371 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
375 int retval = YAFFS_OK;
376 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
377 yaffs_ExtendedTags tags;
379 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
381 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
382 T(YAFFS_TRACE_NANDACCESS,
383 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
387 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
393 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
395 yaffs_ExtendedTags * tags,
404 chunk = yaffs_AllocateChunk(dev, useReserve);
408 /* First check this chunk is erased... */
409 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
410 writeOk = yaffs_CheckChunkErased(dev, chunk);
415 ("**>> yaffs chunk %d was not erased"
419 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
426 * Copy the data into the robustification buffer.
427 * NB We do this at the end to prevent duplicates in the case of a write error.
430 yaffs_HandleWriteChunkOk(dev, chunk, data,
433 yaffs_HandleWriteChunkError(dev, chunk);
437 } while (chunk >= 0 && !writeOk);
441 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
443 dev->nRetriedWrites += (attempts - 1);
450 * Block retiring for handling a broken block.
453 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
456 yaffs_MarkBlockBad(dev, blockInNAND);
458 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
459 YAFFS_BLOCK_STATE_DEAD;
461 dev->nRetiredBlocks++;
465 * Functions for robustisizing TODO
469 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
471 const yaffs_ExtendedTags * tags)
475 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
476 const yaffs_ExtendedTags * tags)
480 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
482 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
484 /* Mark the block for retirement */
485 yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
486 /* Delete the chunk */
487 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
491 /*---------------- Name handling functions ------------*/
493 static __u16 yaffs_CalcNameSum(const YCHAR * name)
498 YUCHAR *bname = (YUCHAR *) name;
500 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
502 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
503 sum += yaffs_toupper(*bname) * i;
514 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
516 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
517 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
518 yaffs_strcpy(obj->shortName, name);
520 obj->shortName[0] = _Y('\0');
523 obj->sum = yaffs_CalcNameSum(name);
526 /*-------------------- TNODES -------------------
528 * List of spare tnodes
529 * The list is hooked together using the first pointer
533 /* yaffs_CreateTnodes creates a bunch more tnodes and
534 * adds them to the tnode free list.
535 * Don't use this function directly
538 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
542 yaffs_Tnode *newTnodes;
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