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.35 2006-06-05 04:10:49 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
35 #ifdef CONFIG_YAFFS_WINCE
36 void yfsd_LockYAFFS(BOOL fsLockOnly);
37 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
40 #define YAFFS_PASSIVE_GC_CHUNKS 2
42 #include "yaffs_ecc.h"
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND);
48 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
50 const yaffs_ExtendedTags * tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
52 const yaffs_ExtendedTags * tags);
54 /* Other local prototypes */
55 static int yaffs_UnlinkObject( yaffs_Object *obj);
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
61 yaffs_ExtendedTags * tags,
63 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
64 int chunkInNAND, int inScan);
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
67 yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
70 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
71 int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
75 int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
80 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
81 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
84 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
87 static int yaffs_UnlinkWorker(yaffs_Object * obj);
88 static void yaffs_DestroyObject(yaffs_Object * obj);
90 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
93 loff_t yaffs_GetFileSize(yaffs_Object * obj);
95 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
97 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
100 static int yaffs_CheckFileSanity(yaffs_Object * in);
102 #define yaffs_CheckFileSanity(in)
105 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
106 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
108 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
111 * Temporary buffer manipulations.
114 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
117 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
118 if (dev->tempBuffer[i].line == 0) {
119 dev->tempBuffer[i].line = lineNo;
120 if ((i + 1) > dev->maxTemp) {
121 dev->maxTemp = i + 1;
122 for (j = 0; j <= i; j++)
123 dev->tempBuffer[j].maxLine =
124 dev->tempBuffer[j].line;
127 return dev->tempBuffer[i].buffer;
131 T(YAFFS_TRACE_BUFFERS,
132 (TSTR("Out of temp buffers at line %d, other held by lines:"),
134 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
135 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
137 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
140 * If we got here then we have to allocate an unmanaged one
144 dev->unmanagedTempAllocations++;
145 return YMALLOC(dev->nBytesPerChunk);
149 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
153 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
154 if (dev->tempBuffer[i].buffer == buffer) {
155 dev->tempBuffer[i].line = 0;
161 /* assume it is an unmanaged one. */
162 T(YAFFS_TRACE_BUFFERS,
163 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
166 dev->unmanagedTempDeallocations++;
172 * Determine if we have a managed buffer.
174 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
177 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
178 if (dev->tempBuffer[i].buffer == buffer)
183 for (i = 0; i < dev->nShortOpCaches; i++) {
184 if( dev->srCache[i].data == buffer )
189 if (buffer == dev->checkpointBuffer)
192 T(YAFFS_TRACE_ALWAYS,
193 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
198 * Chunk bitmap manipulations
201 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
203 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
205 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
209 return dev->chunkBits +
210 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
213 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
215 __u8 *blkBits = yaffs_BlockBits(dev, blk);
217 memset(blkBits, 0, dev->chunkBitmapStride);
220 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
222 __u8 *blkBits = yaffs_BlockBits(dev, blk);
224 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
227 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
229 __u8 *blkBits = yaffs_BlockBits(dev, blk);
231 blkBits[chunk / 8] |= (1 << (chunk & 7));
234 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
236 __u8 *blkBits = yaffs_BlockBits(dev, blk);
237 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
240 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
242 __u8 *blkBits = yaffs_BlockBits(dev, blk);
244 for (i = 0; i < dev->chunkBitmapStride; i++) {
253 * Simple hash function. Needs to have a reasonable spread
256 static Y_INLINE int yaffs_HashFunction(int n)
259 return (n % YAFFS_NOBJECT_BUCKETS);
263 * Access functions to useful fake objects
266 yaffs_Object *yaffs_Root(yaffs_Device * dev)
271 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
273 return dev->lostNFoundDir;
278 * Erased NAND checking functions
281 int yaffs_CheckFF(__u8 * buffer, int nBytes)
283 /* Horrible, slow implementation */
292 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
296 int retval = YAFFS_OK;
297 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
298 yaffs_ExtendedTags tags;
300 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
302 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
303 T(YAFFS_TRACE_NANDACCESS,
304 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
308 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
314 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
316 yaffs_ExtendedTags * tags,
324 yaffs_InvalidateCheckpoint(dev);
327 chunk = yaffs_AllocateChunk(dev, useReserve);
331 /* First check this chunk is erased... */
332 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
333 writeOk = yaffs_CheckChunkErased(dev, chunk);
338 ("**>> yaffs chunk %d was not erased"
342 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
349 * Copy the data into the robustification buffer.
350 * NB We do this at the end to prevent duplicates in the case of a write error.
353 yaffs_HandleWriteChunkOk(dev, chunk, data,
356 yaffs_HandleWriteChunkError(dev, chunk);
360 } while (chunk >= 0 && !writeOk);
364 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
366 dev->nRetriedWrites += (attempts - 1);
373 * Block retiring for handling a broken block.
376 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
379 yaffs_InvalidateCheckpoint(dev);
381 yaffs_MarkBlockBad(dev, blockInNAND);
383 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
384 YAFFS_BLOCK_STATE_DEAD;
386 dev->nRetiredBlocks++;
390 * Functions for robustisizing TODO
394 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
396 const yaffs_ExtendedTags * tags)
400 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
401 const yaffs_ExtendedTags * tags)
405 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
407 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
409 /* Mark the block for retirement */
410 yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
411 /* Delete the chunk */
412 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
416 /*---------------- Name handling functions ------------*/
418 static __u16 yaffs_CalcNameSum(const YCHAR * name)
423 YUCHAR *bname = (YUCHAR *) name;
425 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
427 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
428 sum += yaffs_toupper(*bname) * i;
439 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
441 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
442 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
443 yaffs_strcpy(obj->shortName, name);
445 obj->shortName[0] = _Y('\0');
448 obj->sum = yaffs_CalcNameSum(name);
451 /*-------------------- TNODES -------------------
453 * List of spare tnodes
454 * The list is hooked together using the first pointer
458 /* yaffs_CreateTnodes creates a bunch more tnodes and
459 * adds them to the tnode free list.
460 * Don't use this function directly
463 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
467 yaffs_Tnode *newTnodes;
471 yaffs_TnodeList *tnl;
476 /* Calculate the tnode size in bytes for variable width tnode support.
477 * Must be a multiple of 32-bits */
478 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
480 /* make these things */
482 newTnodes = YMALLOC(nTnodes * tnodeSize);
483 mem = (__u8 *)newTnodes;
487 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
491 /* Hook them into the free list */
493 for (i = 0; i < nTnodes - 1; i++) {
494 newTnodes[i].internal[0] = &newTnodes[i + 1];
495 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
496 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
500 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
501 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
502 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
504 dev->freeTnodes = newTnodes;
506 /* New hookup for wide tnodes */
507 for(i = 0; i < nTnodes -1; i++) {
508 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
509 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
510 curr->internal[0] = next;
513 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
514 curr->internal[0] = dev->freeTnodes;
515 dev->freeTnodes = (yaffs_Tnode *)mem;
520 dev->nFreeTnodes += nTnodes;
521 dev->nTnodesCreated += nTnodes;
523 /* Now add this bunch of tnodes to a list for freeing up.
524 * NB If we can't add this to the management list it isn't fatal
525 * but it just means we can't free this bunch of tnodes later.
528 tnl = YMALLOC(sizeof(yaffs_TnodeList));
532 ("yaffs: Could not add tnodes to management list" TENDSTR)));
535 tnl->tnodes = newTnodes;
536 tnl->next = dev->allocatedTnodeList;
537 dev->allocatedTnodeList = tnl;
540 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
545 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
547 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
549 yaffs_Tnode *tn = NULL;
551 /* If there are none left make more */
552 if (!dev->freeTnodes) {
553 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
556 if (dev->freeTnodes) {
557 tn = dev->freeTnodes;
558 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
559 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
560 /* Hoosterman, this thing looks like it isn't in the list */
561 T(YAFFS_TRACE_ALWAYS,
562 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
565 dev->freeTnodes = dev->freeTnodes->internal[0];
572 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
574 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
577 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
582 /* FreeTnode frees up a tnode and puts it back on the free list */
583 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
586 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
587 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
588 /* Hoosterman, this thing looks like it is already in the list */
589 T(YAFFS_TRACE_ALWAYS,
590 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
592 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
594 tn->internal[0] = dev->freeTnodes;
595 dev->freeTnodes = tn;
600 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
602 /* Free the list of allocated tnodes */
603 yaffs_TnodeList *tmp;
605 while (dev->allocatedTnodeList) {
606 tmp = dev->allocatedTnodeList->next;
608 YFREE(dev->allocatedTnodeList->tnodes);
609 YFREE(dev->allocatedTnodeList);
610 dev->allocatedTnodeList = tmp;
614 dev->freeTnodes = NULL;
615 dev->nFreeTnodes = 0;
618 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
620 dev->allocatedTnodeList = NULL;
621 dev->freeTnodes = NULL;
622 dev->nFreeTnodes = 0;
623 dev->nTnodesCreated = 0;
628 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
630 __u32 *map = (__u32 *)tn;
636 pos &= YAFFS_TNODES_LEVEL0_MASK;
637 val >>= dev->chunkGroupBits;
639 bitInMap = pos * dev->tnodeWidth;
640 wordInMap = bitInMap /32;
641 bitInWord = bitInMap & (32 -1);
643 mask = dev->tnodeMask << bitInWord;
645 map[wordInMap] &= ~mask;
646 map[wordInMap] |= (mask & (val << bitInWord));
648 if(dev->tnodeWidth > (32-bitInWord)) {
649 bitInWord = (32 - bitInWord);
651 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
652 map[wordInMap] &= ~mask;
653 map[wordInMap] |= (mask & (val >> bitInWord));
657 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
659 __u32 *map = (__u32 *)tn;
665 pos &= YAFFS_TNODES_LEVEL0_MASK;
667 bitInMap = pos * dev->tnodeWidth;
668 wordInMap = bitInMap /32;
669 bitInWord = bitInMap & (32 -1);
671 val = map[wordInMap] >> bitInWord;
673 if(dev->tnodeWidth > (32-bitInWord)) {
674 bitInWord = (32 - bitInWord);
676 val |= (map[wordInMap] << bitInWord);
679 val &= dev->tnodeMask;
680 val <<= dev->chunkGroupBits;
685 /* ------------------- End of individual tnode manipulation -----------------*/
687 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
688 * The look up tree is represented by the top tnode and the number of topLevel
689 * in the tree. 0 means only the level 0 tnode is in the tree.
692 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
693 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
694 yaffs_FileStructure * fStruct,
698 yaffs_Tnode *tn = fStruct->top;
700 int requiredTallness;
701 int level = fStruct->topLevel;
703 /* Check sane level and chunk Id */
704 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
708 if (chunkId > YAFFS_MAX_CHUNK_ID) {
712 /* First check we're tall enough (ie enough topLevel) */
714 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
715 requiredTallness = 0;
717 i >>= YAFFS_TNODES_INTERNAL_BITS;
721 if (requiredTallness > fStruct->topLevel) {
722 /* Not tall enough, so we can't find it, return NULL. */
726 /* Traverse down to level 0 */
727 while (level > 0 && tn) {
730 ( YAFFS_TNODES_LEVEL0_BITS +
732 YAFFS_TNODES_INTERNAL_BITS)
734 YAFFS_TNODES_INTERNAL_MASK];
742 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
743 * This happens in two steps:
744 * 1. If the tree isn't tall enough, then make it taller.
745 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
747 * Used when modifying the tree.
749 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
750 * be plugged into the ttree.
753 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
754 yaffs_FileStructure * fStruct,
756 yaffs_Tnode *passedTn)
759 int requiredTallness;
767 /* Check sane level and page Id */
768 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
772 if (chunkId > YAFFS_MAX_CHUNK_ID) {
776 /* First check we're tall enough (ie enough topLevel) */
778 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
779 requiredTallness = 0;
781 x >>= YAFFS_TNODES_INTERNAL_BITS;
786 if (requiredTallness > fStruct->topLevel) {
787 /* Not tall enough,gotta make the tree taller */
788 for (i = fStruct->topLevel; i < requiredTallness; i++) {
790 tn = yaffs_GetTnode(dev);
793 tn->internal[0] = fStruct->top;
797 (TSTR("yaffs: no more tnodes" TENDSTR)));
801 fStruct->topLevel = requiredTallness;
804 /* Traverse down to level 0, adding anything we need */
806 l = fStruct->topLevel;
810 while (l > 0 && tn) {
812 ( YAFFS_TNODES_LEVEL0_BITS +
813 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
814 YAFFS_TNODES_INTERNAL_MASK;
817 if((l>1) && !tn->internal[x]){
818 /* Add missing non-level-zero tnode */
819 tn->internal[x] = yaffs_GetTnode(dev);
822 /* Looking from level 1 at level 0 */
824 /* If we already have one, then release it.*/
826 yaffs_FreeTnode(dev,tn->internal[x]);
827 tn->internal[x] = passedTn;
829 } else if(!tn->internal[x]) {
830 /* Don't have one, none passed in */
831 tn->internal[x] = yaffs_GetTnode(dev);
835 tn = tn->internal[x];
841 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
842 yaffs_FreeTnode(dev,passedTn);
849 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
850 yaffs_ExtendedTags * tags, int objectId,
855 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
856 if (yaffs_CheckChunkBit
857 (dev, theChunk / dev->nChunksPerBlock,
858 theChunk % dev->nChunksPerBlock)) {
859 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
861 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
873 /* DeleteWorker scans backwards through the tnode tree and deletes all the
874 * chunks and tnodes in the file
875 * Returns 1 if the tree was deleted.
876 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
879 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
880 int chunkOffset, int *limit)
885 yaffs_ExtendedTags tags;
887 yaffs_Device *dev = in->myDev;
894 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
896 if (tn->internal[i]) {
897 if (limit && (*limit) < 0) {
901 yaffs_DeleteWorker(in,
909 YAFFS_TNODES_INTERNAL_BITS)
917 tn->internal[i] = NULL;
922 return (allDone) ? 1 : 0;
923 } else if (level == 0) {
926 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
928 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
933 YAFFS_TNODES_LEVEL0_BITS) + i;
936 yaffs_FindChunkInGroup(dev,
942 if (foundChunk > 0) {
943 yaffs_DeleteChunk(dev,
956 yaffs_PutLevel0Tnode(dev,tn,i,0);
960 return (i < 0) ? 1 : 0;
970 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
973 yaffs_BlockInfo *theBlock;
975 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
977 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
979 theBlock->softDeletions++;
984 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
985 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
987 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
990 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
991 __u32 level, int chunkOffset)
996 yaffs_Device *dev = in->myDev;
1001 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1003 if (tn->internal[i]) {
1005 yaffs_SoftDeleteWorker(in,
1011 YAFFS_TNODES_INTERNAL_BITS)
1014 yaffs_FreeTnode(dev,
1017 tn->internal[i] = NULL;
1019 /* Hoosterman... how could this happen? */
1023 return (allDone) ? 1 : 0;
1024 } else if (level == 0) {
1026 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1027 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1029 /* Note this does not find the real chunk, only the chunk group.
1030 * We make an assumption that a chunk group is not larger than
1033 yaffs_SoftDeleteChunk(dev, theChunk);
1034 yaffs_PutLevel0Tnode(dev,tn,i,0);
1048 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1051 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1052 if (obj->nDataChunks <= 0) {
1053 /* Empty file with no duplicate object headers, just delete it immediately */
1054 yaffs_FreeTnode(obj->myDev,
1055 obj->variant.fileVariant.top);
1056 obj->variant.fileVariant.top = NULL;
1057 T(YAFFS_TRACE_TRACING,
1058 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1060 yaffs_DoGenericObjectDeletion(obj);
1062 yaffs_SoftDeleteWorker(obj,
1063 obj->variant.fileVariant.top,
1064 obj->variant.fileVariant.
1066 obj->softDeleted = 1;
1071 /* Pruning removes any part of the file structure tree that is beyond the
1072 * bounds of the file (ie that does not point to chunks).
1074 * A file should only get pruned when its size is reduced.
1076 * Before pruning, the chunks must be pulled from the tree and the
1077 * level 0 tnode entries must be zeroed out.
1078 * Could also use this for file deletion, but that's probably better handled
1079 * by a special case.
1082 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1083 __u32 level, int del0)
1091 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1092 if (tn->internal[i] && level > 0) {
1094 yaffs_PruneWorker(dev, tn->internal[i],
1096 (i == 0) ? del0 : 1);
1099 if (tn->internal[i]) {
1104 if (hasData == 0 && del0) {
1105 /* Free and return NULL */
1107 yaffs_FreeTnode(dev, tn);
1117 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1118 yaffs_FileStructure * fStruct)
1125 if (fStruct->topLevel > 0) {
1127 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1129 /* Now we have a tree with all the non-zero branches NULL but the height
1130 * is the same as it was.
1131 * Let's see if we can trim internal tnodes to shorten the tree.
1132 * We can do this if only the 0th element in the tnode is in use
1133 * (ie all the non-zero are NULL)
1136 while (fStruct->topLevel && !done) {
1140 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1141 if (tn->internal[i]) {
1147 fStruct->top = tn->internal[0];
1148 fStruct->topLevel--;
1149 yaffs_FreeTnode(dev, tn);
1159 /*-------------------- End of File Structure functions.-------------------*/
1161 /* yaffs_CreateFreeObjects creates a bunch more objects and
1162 * adds them to the object free list.
1164 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1167 yaffs_Object *newObjects;
1168 yaffs_ObjectList *list;
1173 /* make these things */
1174 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1177 T(YAFFS_TRACE_ALLOCATE,
1178 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1182 /* Hook them into the free list */
1183 for (i = 0; i < nObjects - 1; i++) {
1184 newObjects[i].siblings.next =
1185 (struct list_head *)(&newObjects[i + 1]);
1188 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1189 dev->freeObjects = newObjects;
1190 dev->nFreeObjects += nObjects;
1191 dev->nObjectsCreated += nObjects;
1193 /* Now add this bunch of Objects to a list for freeing up. */
1195 list = YMALLOC(sizeof(yaffs_ObjectList));
1197 T(YAFFS_TRACE_ALLOCATE,
1198 (TSTR("Could not add objects to management list" TENDSTR)));
1200 list->objects = newObjects;
1201 list->next = dev->allocatedObjectList;
1202 dev->allocatedObjectList = list;
1209 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1210 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1212 yaffs_Object *tn = NULL;
1214 /* If there are none left make more */
1215 if (!dev->freeObjects) {
1216 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1219 if (dev->freeObjects) {
1220 tn = dev->freeObjects;
1222 (yaffs_Object *) (dev->freeObjects->siblings.next);
1223 dev->nFreeObjects--;
1225 /* Now sweeten it up... */
1227 memset(tn, 0, sizeof(yaffs_Object));
1230 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1231 INIT_LIST_HEAD(&(tn->hardLinks));
1232 INIT_LIST_HEAD(&(tn->hashLink));
1233 INIT_LIST_HEAD(&tn->siblings);
1235 /* Add it to the lost and found directory.
1236 * NB Can't put root or lostNFound in lostNFound so
1237 * check if lostNFound exists first
1239 if (dev->lostNFoundDir) {
1240 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1247 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1252 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1254 obj->fake = 1; /* it is fake so it has no NAND presence... */
1255 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1256 obj->unlinkAllowed = 0; /* ... or unlink it */
1259 obj->yst_mode = mode;
1261 obj->chunkId = 0; /* Not a valid chunk. */
1268 static void yaffs_UnhashObject(yaffs_Object * tn)
1271 yaffs_Device *dev = tn->myDev;
1273 /* If it is still linked into the bucket list, free from the list */
1274 if (!list_empty(&tn->hashLink)) {
1275 list_del_init(&tn->hashLink);
1276 bucket = yaffs_HashFunction(tn->objectId);
1277 dev->objectBucket[bucket].count--;
1282 /* FreeObject frees up a Object and puts it back on the free list */
1283 static void yaffs_FreeObject(yaffs_Object * tn)
1286 yaffs_Device *dev = tn->myDev;
1290 /* We're still hooked up to a cached inode.
1291 * Don't delete now, but mark for later deletion
1293 tn->deferedFree = 1;
1298 yaffs_UnhashObject(tn);
1300 /* Link into the free list. */
1301 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1302 dev->freeObjects = tn;
1303 dev->nFreeObjects++;
1308 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1310 if (obj->deferedFree) {
1311 yaffs_FreeObject(obj);
1317 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1319 /* Free the list of allocated Objects */
1321 yaffs_ObjectList *tmp;
1323 while (dev->allocatedObjectList) {
1324 tmp = dev->allocatedObjectList->next;
1325 YFREE(dev->allocatedObjectList->objects);
1326 YFREE(dev->allocatedObjectList);
1328 dev->allocatedObjectList = tmp;
1331 dev->freeObjects = NULL;
1332 dev->nFreeObjects = 0;
1335 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1339 dev->allocatedObjectList = NULL;
1340 dev->freeObjects = NULL;
1341 dev->nFreeObjects = 0;
1343 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1344 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1345 dev->objectBucket[i].count = 0;
1350 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1355 int lowest = 999999;
1357 /* First let's see if we can find one that's empty. */
1359 for (i = 0; i < 10 && lowest > 0; i++) {
1361 x %= YAFFS_NOBJECT_BUCKETS;
1362 if (dev->objectBucket[x].count < lowest) {
1363 lowest = dev->objectBucket[x].count;
1369 /* If we didn't find an empty list, then try
1370 * looking a bit further for a short one
1373 for (i = 0; i < 10 && lowest > 3; i++) {
1375 x %= YAFFS_NOBJECT_BUCKETS;
1376 if (dev->objectBucket[x].count < lowest) {
1377 lowest = dev->objectBucket[x].count;
1386 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1388 int bucket = yaffs_FindNiceObjectBucket(dev);
1390 /* Now find an object value that has not already been taken
1391 * by scanning the list.
1395 struct list_head *i;
1397 __u32 n = (__u32) bucket;
1399 /* yaffs_CheckObjectHashSanity(); */
1403 n += YAFFS_NOBJECT_BUCKETS;
1404 if (1 || dev->objectBucket[bucket].count > 0) {
1405 list_for_each(i, &dev->objectBucket[bucket].list) {
1406 /* If there is already one in the list */
1408 && list_entry(i, yaffs_Object,
1409 hashLink)->objectId == n) {
1420 static void yaffs_HashObject(yaffs_Object * in)
1422 int bucket = yaffs_HashFunction(in->objectId);
1423 yaffs_Device *dev = in->myDev;
1425 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1426 dev->objectBucket[bucket].count++;
1430 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1432 int bucket = yaffs_HashFunction(number);
1433 struct list_head *i;
1436 list_for_each(i, &dev->objectBucket[bucket].list) {
1437 /* Look if it is in the list */
1439 in = list_entry(i, yaffs_Object, hashLink);
1440 if (in->objectId == number) {
1442 /* Don't tell the VFS about this one if it is defered free */
1443 if (in->deferedFree)
1455 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1456 yaffs_ObjectType type)
1459 yaffs_Object *theObject;
1462 number = yaffs_CreateNewObjectNumber(dev);
1465 theObject = yaffs_AllocateEmptyObject(dev);
1468 theObject->fake = 0;
1469 theObject->renameAllowed = 1;
1470 theObject->unlinkAllowed = 1;
1471 theObject->objectId = number;
1472 yaffs_HashObject(theObject);
1473 theObject->variantType = type;
1474 #ifdef CONFIG_YAFFS_WINCE
1475 yfsd_WinFileTimeNow(theObject->win_atime);
1476 theObject->win_ctime[0] = theObject->win_mtime[0] =
1477 theObject->win_atime[0];
1478 theObject->win_ctime[1] = theObject->win_mtime[1] =
1479 theObject->win_atime[1];
1483 theObject->yst_atime = theObject->yst_mtime =
1484 theObject->yst_ctime = Y_CURRENT_TIME;
1487 case YAFFS_OBJECT_TYPE_FILE:
1488 theObject->variant.fileVariant.fileSize = 0;
1489 theObject->variant.fileVariant.scannedFileSize = 0;
1490 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1491 theObject->variant.fileVariant.topLevel = 0;
1492 theObject->variant.fileVariant.top =
1493 yaffs_GetTnode(dev);
1495 case YAFFS_OBJECT_TYPE_DIRECTORY:
1496 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1499 case YAFFS_OBJECT_TYPE_SYMLINK:
1500 case YAFFS_OBJECT_TYPE_HARDLINK:
1501 case YAFFS_OBJECT_TYPE_SPECIAL:
1502 /* No action required */
1504 case YAFFS_OBJECT_TYPE_UNKNOWN:
1505 /* todo this should not happen */
1513 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1515 yaffs_ObjectType type)
1517 yaffs_Object *theObject = NULL;
1520 theObject = yaffs_FindObjectByNumber(dev, number);
1524 theObject = yaffs_CreateNewObject(dev, number, type);
1532 static YCHAR *yaffs_CloneString(const YCHAR * str)
1534 YCHAR *newStr = NULL;
1537 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1538 yaffs_strcpy(newStr, str);
1546 * Mknod (create) a new object.
1547 * equivalentObject only has meaning for a hard link;
1548 * aliasString only has meaning for a sumlink.
1549 * rdev only has meaning for devices (a subset of special objects)
1552 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1553 yaffs_Object * parent,
1558 yaffs_Object * equivalentObject,
1559 const YCHAR * aliasString, __u32 rdev)
1563 yaffs_Device *dev = parent->myDev;
1565 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1566 if (yaffs_FindObjectByName(parent, name)) {
1570 in = yaffs_CreateNewObject(dev, -1, type);
1575 in->variantType = type;
1577 in->yst_mode = mode;
1579 #ifdef CONFIG_YAFFS_WINCE
1580 yfsd_WinFileTimeNow(in->win_atime);
1581 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1582 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1585 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1587 in->yst_rdev = rdev;
1591 in->nDataChunks = 0;
1593 yaffs_SetObjectName(in, name);
1596 yaffs_AddObjectToDirectory(parent, in);
1598 in->myDev = parent->myDev;
1601 case YAFFS_OBJECT_TYPE_SYMLINK:
1602 in->variant.symLinkVariant.alias =
1603 yaffs_CloneString(aliasString);
1605 case YAFFS_OBJECT_TYPE_HARDLINK:
1606 in->variant.hardLinkVariant.equivalentObject =
1608 in->variant.hardLinkVariant.equivalentObjectId =
1609 equivalentObject->objectId;
1610 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1612 case YAFFS_OBJECT_TYPE_FILE:
1613 case YAFFS_OBJECT_TYPE_DIRECTORY:
1614 case YAFFS_OBJECT_TYPE_SPECIAL:
1615 case YAFFS_OBJECT_TYPE_UNKNOWN:
1620 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1621 /* Could not create the object header, fail the creation */
1622 yaffs_DestroyObject(in);
1631 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1632 __u32 mode, __u32 uid, __u32 gid)
1634 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1635 uid, gid, NULL, NULL, 0);
1638 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1639 __u32 mode, __u32 uid, __u32 gid)
1641 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1642 mode, uid, gid, NULL, NULL, 0);
1645 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1646 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1648 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1649 uid, gid, NULL, NULL, rdev);
1652 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1653 __u32 mode, __u32 uid, __u32 gid,
1654 const YCHAR * alias)
1656 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1657 uid, gid, NULL, alias, 0);
1660 /* yaffs_Link returns the object id of the equivalent object.*/
1661 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1662 yaffs_Object * equivalentObject)
1664 /* Get the real object in case we were fed a hard link as an equivalent object */
1665 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1667 if (yaffs_MknodObject
1668 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1669 equivalentObject, NULL, 0)) {
1670 return equivalentObject;
1677 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1678 const YCHAR * newName, int force, int shadows)
1683 yaffs_Object *existingTarget;
1685 if (newDir == NULL) {
1686 newDir = obj->parent; /* use the old directory */
1689 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1690 T(YAFFS_TRACE_ALWAYS,
1692 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1697 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1698 if (obj->myDev->isYaffs2) {
1699 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1701 unlinkOp = (newDir == obj->myDev->unlinkedDir
1702 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1705 deleteOp = (newDir == obj->myDev->deletedDir);
1707 existingTarget = yaffs_FindObjectByName(newDir, newName);
1709 /* If the object is a file going into the unlinked directory,
1710 * then it is OK to just stuff it in since duplicate names are allowed.
1711 * else only proceed if the new name does not exist and if we're putting
1712 * it into a directory.
1719 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1720 yaffs_SetObjectName(obj, newName);
1723 yaffs_AddObjectToDirectory(newDir, obj);
1728 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1729 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1736 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1737 yaffs_Object * newDir, const YCHAR * newName)
1740 yaffs_Object *existingTarget;
1743 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1744 /* Special case for case insemsitive systems (eg. WinCE).
1745 * While look-up is case insensitive, the name isn't.
1746 * Therefore we might want to change x.txt to X.txt
1748 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1753 obj = yaffs_FindObjectByName(oldDir, oldName);
1754 /* Check new name to long. */
1755 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1756 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1759 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1760 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1764 if (obj && obj->renameAllowed) {
1766 /* Now do the handling for an existing target, if there is one */
1768 existingTarget = yaffs_FindObjectByName(newDir, newName);
1769 if (existingTarget &&
1770 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1771 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1772 /* There is a target that is a non-empty directory, so we fail */
1773 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1774 } else if (existingTarget && existingTarget != obj) {
1775 /* Nuke the target first, using shadowing,
1776 * but only if it isn't the same object
1778 yaffs_ChangeObjectName(obj, newDir, newName, force,
1779 existingTarget->objectId);
1780 yaffs_UnlinkObject(existingTarget);
1783 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1788 /*------------------------- Block Management and Page Allocation ----------------*/
1790 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1792 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1794 dev->allocationBlock = -1; /* force it to get a new one */
1796 /* Todo we're assuming the malloc will pass. */
1797 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1798 if(!dev->blockInfo){
1799 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1800 dev->blockInfoAlt = 1;
1803 dev->blockInfoAlt = 0;
1805 /* Set up dynamic blockinfo stuff. */
1806 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; // round up bytes
1807 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1808 if(!dev->chunkBits){
1809 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1810 dev->chunkBitsAlt = 1;
1813 dev->chunkBitsAlt = 0;
1815 if (dev->blockInfo && dev->chunkBits) {
1816 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1817 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1825 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1827 if(dev->blockInfoAlt)
1828 YFREE_ALT(dev->blockInfo);
1830 YFREE(dev->blockInfo);
1831 dev->blockInfoAlt = 0;
1833 dev->blockInfo = NULL;
1835 if(dev->chunkBitsAlt)
1836 YFREE_ALT(dev->chunkBits);
1838 YFREE(dev->chunkBits);
1839 dev->chunkBitsAlt = 0;
1840 dev->chunkBits = NULL;
1843 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1844 yaffs_BlockInfo * bi)
1851 return 1; /* disqualification only applies to yaffs2. */
1853 if (!bi->hasShrinkHeader)
1854 return 1; /* can gc */
1856 /* Find the oldest dirty sequence number if we don't know it and save it
1857 * so we don't have to keep recomputing it.
1859 if (!dev->oldestDirtySequence) {
1860 seq = dev->sequenceNumber;
1862 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1864 b = yaffs_GetBlockInfo(dev, i);
1865 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1866 (b->pagesInUse - b->softDeletions) <
1867 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1868 seq = b->sequenceNumber;
1871 dev->oldestDirtySequence = seq;
1874 /* Can't do gc of this block if there are any blocks older than this one that have
1877 return (bi->sequenceNumber <= dev->oldestDirtySequence);
1883 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1884 * for garbage collection.
1887 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1891 int b = dev->currentDirtyChecker;
1897 yaffs_BlockInfo *bi;
1898 static int nonAggressiveSkip = 0;
1900 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1902 * else (we're doing a leasurely gc), then we only bother to do this if the
1903 * block has only a few pages in use.
1906 nonAggressiveSkip--;
1908 if (!aggressive && (nonAggressiveSkip > 0)) {
1913 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1917 dev->internalEndBlock - dev->internalStartBlock + 1;
1920 dev->internalEndBlock - dev->internalStartBlock + 1;
1921 iterations = iterations / 16;
1922 if (iterations > 200) {
1927 for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1929 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1930 b = dev->internalStartBlock;
1933 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1934 T(YAFFS_TRACE_ERROR,
1935 (TSTR("**>> Block %d is not valid" TENDSTR), b));
1939 bi = yaffs_GetBlockInfo(dev, b);
1942 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
1949 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1950 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1951 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1953 pagesInUse = (bi->pagesInUse - bi->softDeletions);
1957 dev->currentDirtyChecker = b;
1961 (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1962 dev->nChunksPerBlock - pagesInUse));
1965 dev->oldestDirtySequence = 0;
1968 nonAggressiveSkip = 4;
1974 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1976 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1980 /* If the block is still healthy erase it and mark as clean.
1981 * If the block has had a data failure, then retire it.
1983 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1985 if (!bi->needsRetiring) {
1986 yaffs_InvalidateCheckpoint(dev);
1987 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1989 dev->nErasureFailures++;
1990 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1991 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1995 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
1997 for (i = 0; i < dev->nChunksPerBlock; i++) {
1998 if (!yaffs_CheckChunkErased
1999 (dev, blockNo * dev->nChunksPerBlock + i)) {
2000 T(YAFFS_TRACE_ERROR,
2002 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2003 TENDSTR), blockNo, i));
2009 /* Clean it up... */
2010 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2011 dev->nErasedBlocks++;
2013 bi->softDeletions = 0;
2014 bi->hasShrinkHeader = 0;
2015 yaffs_ClearChunkBits(dev, blockNo);
2017 T(YAFFS_TRACE_ERASE,
2018 (TSTR("Erased block %d" TENDSTR), blockNo));
2020 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2022 yaffs_RetireBlock(dev, blockNo);
2023 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2024 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2028 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2032 yaffs_BlockInfo *bi;
2034 if (dev->nErasedBlocks < 1) {
2035 /* Hoosterman we've got a problem.
2036 * Can't get space to gc
2038 T(YAFFS_TRACE_ERROR,
2039 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2044 /* Find an empty block. */
2046 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2047 dev->allocationBlockFinder++;
2048 if (dev->allocationBlockFinder < dev->internalStartBlock
2049 || dev->allocationBlockFinder > dev->internalEndBlock) {
2050 dev->allocationBlockFinder = dev->internalStartBlock;
2053 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2055 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2056 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2057 dev->sequenceNumber++;
2058 bi->sequenceNumber = dev->sequenceNumber;
2059 dev->nErasedBlocks--;
2060 T(YAFFS_TRACE_ALLOCATE,
2061 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2062 dev->allocationBlockFinder, dev->sequenceNumber,
2063 dev->nErasedBlocks));
2064 return dev->allocationBlockFinder;
2068 T(YAFFS_TRACE_ALWAYS,
2070 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2071 TENDSTR), dev->nErasedBlocks));
2077 // Check if there's space to allocate...
2078 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2079 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2082 int reservedBlocks = dev->nReservedBlocks;
2083 int checkpointBlocks;
2085 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2086 if(checkpointBlocks < 0)
2087 checkpointBlocks = 0;
2089 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2091 return (dev->nFreeChunks > reservedChunks);
2094 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2097 yaffs_BlockInfo *bi;
2099 if (dev->allocationBlock < 0) {
2100 /* Get next block to allocate off */
2101 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2102 dev->allocationPage = 0;
2105 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2106 /* Not enough space to allocate unless we're allowed to use the reserve. */
2110 if (dev->nErasedBlocks < dev->nReservedBlocks
2111 && dev->allocationPage == 0) {
2112 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2115 /* Next page please.... */
2116 if (dev->allocationBlock >= 0) {
2117 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2119 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2120 dev->allocationPage;
2122 yaffs_SetChunkBit(dev, dev->allocationBlock,
2123 dev->allocationPage);
2125 dev->allocationPage++;
2129 /* If the block is full set the state to full */
2130 if (dev->allocationPage >= dev->nChunksPerBlock) {
2131 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2132 dev->allocationBlock = -1;
2138 T(YAFFS_TRACE_ERROR,
2139 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2144 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2148 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2150 if (dev->allocationBlock > 0) {
2151 n += (dev->nChunksPerBlock - dev->allocationPage);
2158 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2164 int retVal = YAFFS_OK;
2167 int isCheckpointBlock;
2169 int chunksBefore = yaffs_GetErasedChunks(dev);
2172 yaffs_ExtendedTags tags;
2174 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2176 yaffs_Object *object;
2178 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2180 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2182 T(YAFFS_TRACE_TRACING,
2183 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2184 bi->pagesInUse, bi->hasShrinkHeader));
2186 /*yaffs_VerifyFreeChunks(dev); */
2188 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2190 /* Take off the number of soft deleted entries because
2191 * they're going to get really deleted during GC.
2193 dev->nFreeChunks -= bi->softDeletions;
2197 if (isCheckpointBlock ||
2198 !yaffs_StillSomeChunkBits(dev, block)) {
2199 T(YAFFS_TRACE_TRACING,
2201 ("Collecting block %d that has no chunks in use" TENDSTR),
2203 yaffs_BlockBecameDirty(dev, block);
2206 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2208 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2209 chunkInBlock < dev->nChunksPerBlock
2210 && yaffs_StillSomeChunkBits(dev, block);
2211 chunkInBlock++, oldChunk++) {
2212 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2214 /* This page is in use and might need to be copied off */
2218 yaffs_InitialiseTags(&tags);
2220 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2224 yaffs_FindObjectByNumber(dev,
2227 T(YAFFS_TRACE_GC_DETAIL,
2229 ("Collecting page %d, %d %d %d " TENDSTR),
2230 chunkInBlock, tags.objectId, tags.chunkId,
2234 T(YAFFS_TRACE_ERROR,
2236 ("page %d in gc has no object "
2237 TENDSTR), oldChunk));
2240 if (object && object->deleted
2241 && tags.chunkId != 0) {
2242 /* Data chunk in a deleted file, throw it away
2243 * It's a soft deleted data chunk,
2244 * No need to copy this, just forget about it and
2245 * fix up the object.
2248 object->nDataChunks--;
2250 if (object->nDataChunks <= 0) {
2251 /* remeber to clean up the object */
2252 dev->gcCleanupList[cleanups] =
2258 /* Todo object && object->deleted && object->nDataChunks == 0 */
2260 /* Deleted object header with no data chunks.
2261 * Can be discarded and the file deleted.
2263 object->chunkId = 0;
2264 yaffs_FreeTnode(object->myDev,
2267 object->variant.fileVariant.top = NULL;
2268 yaffs_DoGenericObjectDeletion(object);
2270 } else if (object) {
2271 /* It's either a data chunk in a live file or
2272 * an ObjectHeader, so we're interested in it.
2273 * NB Need to keep the ObjectHeaders of deleted files
2274 * until the whole file has been deleted off
2276 tags.serialNumber++;
2280 if (tags.chunkId == 0) {
2281 /* It is an object Id,
2282 * We need to nuke the shrinkheader flags first
2283 * We no longer want the shrinkHeader flag since its work is done
2284 * and if it is left in place it will mess up scanning.
2285 * Also, clear out any shadowing stuff
2288 yaffs_ObjectHeader *oh;
2289 oh = (yaffs_ObjectHeader *)buffer;
2291 oh->shadowsObject = -1;
2292 tags.extraShadows = 0;
2293 tags.extraIsShrinkHeader = 0;
2297 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2300 retVal = YAFFS_FAIL;
2303 /* Ok, now fix up the Tnodes etc. */
2305 if (tags.chunkId == 0) {
2307 object->chunkId = newChunk;
2308 object->serial = tags.serialNumber;
2310 /* It's a data chunk */
2311 yaffs_PutChunkIntoFile
2319 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2324 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2327 /* Do any required cleanups */
2328 for (i = 0; i < cleanups; i++) {
2329 /* Time to delete the file too */
2331 yaffs_FindObjectByNumber(dev,
2332 dev->gcCleanupList[i]);
2334 yaffs_FreeTnode(dev,
2335 object->variant.fileVariant.
2337 object->variant.fileVariant.top = NULL;
2340 ("yaffs: About to finally delete object %d"
2341 TENDSTR), object->objectId));
2342 yaffs_DoGenericObjectDeletion(object);
2343 object->myDev->nDeletedFiles--;
2350 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2353 ("gc did not increase free chunks before %d after %d"
2354 TENDSTR), chunksBefore, chunksAfter));
2362 /* New garbage collector
2363 * If we're very low on erased blocks then we do aggressive garbage collection
2364 * otherwise we do "leasurely" garbage collection.
2365 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2366 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2368 * The idea is to help clear out space in a more spread-out manner.
2369 * Dunno if it really does anything useful.
2371 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2375 int gcOk = YAFFS_OK;
2378 int checkpointBlockAdjust;
2380 if (dev->isDoingGC) {
2381 /* Bail out so we don't get recursive gc */
2385 /* This loop should pass the first time.
2386 * We'll only see looping here if the erase of the collected block fails.
2392 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2393 if(checkpointBlockAdjust < 0)
2394 checkpointBlockAdjust = 0;
2396 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2397 /* We need a block soon...*/
2400 /* We're in no hurry */
2404 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2407 dev->garbageCollections++;
2409 dev->passiveGarbageCollections++;
2414 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2415 dev->nErasedBlocks, aggressive));
2417 gcOk = yaffs_GarbageCollectBlock(dev, block);
2420 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2423 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2424 TENDSTR), dev->nErasedBlocks, maxTries, block));
2426 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2429 return aggressive ? gcOk : YAFFS_OK;
2432 /*------------------------- TAGS --------------------------------*/
2434 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2437 return (tags->chunkId == chunkInObject &&
2438 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2443 /*-------------------- Data file manipulation -----------------*/
2445 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2446 yaffs_ExtendedTags * tags)
2448 /*Get the Tnode, then get the level 0 offset chunk offset */
2451 yaffs_ExtendedTags localTags;
2454 yaffs_Device *dev = in->myDev;
2457 /* Passed a NULL, so use our own tags space */
2461 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2464 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2467 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2473 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2474 yaffs_ExtendedTags * tags)
2476 /* Get the Tnode, then get the level 0 offset chunk offset */
2479 yaffs_ExtendedTags localTags;
2481 yaffs_Device *dev = in->myDev;
2485 /* Passed a NULL, so use our own tags space */
2489 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2493 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2496 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2499 /* Delete the entry in the filestructure (if found) */
2501 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2504 /*T(("No level 0 found for %d\n", chunkInInode)); */
2508 /* T(("Could not find %d to delete\n",chunkInInode)); */
2513 #ifdef YAFFS_PARANOID
2515 static int yaffs_CheckFileSanity(yaffs_Object * in)
2523 yaffs_Tags localTags;
2524 yaffs_Tags *tags = &localTags;
2528 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2529 /* T(("Object not a file\n")); */
2533 objId = in->objectId;
2534 fSize = in->variant.fileVariant.fileSize;
2536 (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2538 for (chunk = 1; chunk <= nChunks; chunk++) {
2539 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2544 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2546 if (yaffs_CheckChunkBits
2547 (dev, theChunk / dev->nChunksPerBlock,
2548 theChunk % dev->nChunksPerBlock)) {
2550 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2554 (tags, in->objectId, chunk, chunkDeleted)) {
2564 /* T(("No level 0 found for %d\n", chunk)); */
2568 return failed ? YAFFS_FAIL : YAFFS_OK;
2573 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2574 int chunkInNAND, int inScan)
2576 /* NB inScan is zero unless scanning.
2577 * For forward scanning, inScan is > 0;
2578 * for backward scanning inScan is < 0
2582 yaffs_Device *dev = in->myDev;
2584 yaffs_ExtendedTags existingTags;
2585 yaffs_ExtendedTags newTags;
2586 unsigned existingSerial, newSerial;
2588 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2589 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2590 * If it is not during Scanning then something went wrong!
2593 T(YAFFS_TRACE_ERROR,
2595 ("yaffs tragedy:attempt to put data chunk into a non-file"
2600 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2604 tn = yaffs_AddOrFindLevel0Tnode(dev,
2605 &in->variant.fileVariant,
2612 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2615 /* If we're scanning then we need to test for duplicates
2616 * NB This does not need to be efficient since it should only ever
2617 * happen when the power fails during a write, then only one
2618 * chunk should ever be affected.
2620 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2621 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2624 if (existingChunk != 0) {
2625 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2626 * thus we have to do a FindChunkInFile to get the real chunk id.
2628 * We have a duplicate now we need to decide which one to use:
2630 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2631 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2632 * YAFFS1: Get both sets of tags and compare serial numbers.
2636 /* Only do this for forward scanning */
2637 yaffs_ReadChunkWithTagsFromNAND(dev,
2641 /* Do a proper find */
2643 yaffs_FindChunkInFile(in, chunkInInode,
2647 if (existingChunk <= 0) {
2648 /*Hoosterman - how did this happen? */
2650 T(YAFFS_TRACE_ERROR,
2652 ("yaffs tragedy: existing chunk < 0 in scan"
2657 /* NB The deleted flags should be false, otherwise the chunks will
2658 * not be loaded during a scan
2661 newSerial = newTags.serialNumber;
2662 existingSerial = existingTags.serialNumber;
2665 (in->myDev->isYaffs2 ||
2666 existingChunk <= 0 ||
2667 ((existingSerial + 1) & 3) == newSerial)) {
2668 /* Forward scanning.
2670 * Delete the old one and drop through to update the tnode
2672 yaffs_DeleteChunk(dev, existingChunk, 1,
2675 /* Backward scanning or we want to use the existing one
2677 * Delete the new one and return early so that the tnode isn't changed
2679 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2687 if (existingChunk == 0) {
2691 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2696 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2699 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2701 if (chunkInNAND >= 0) {
2702 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2705 T(YAFFS_TRACE_NANDACCESS,
2706 (TSTR("Chunk %d not found zero instead" TENDSTR),
2708 /* get sane (zero) data if you read a hole */
2709 memset(buffer, 0, in->myDev->nBytesPerChunk);
2715 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2719 yaffs_ExtendedTags tags;
2720 yaffs_BlockInfo *bi;
2726 block = chunkId / dev->nChunksPerBlock;
2727 page = chunkId % dev->nChunksPerBlock;
2729 bi = yaffs_GetBlockInfo(dev, block);
2731 T(YAFFS_TRACE_DELETION,
2732 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2735 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2737 yaffs_InitialiseTags(&tags);
2739 tags.chunkDeleted = 1;
2741 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2742 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2744 dev->nUnmarkedDeletions++;
2747 /* Pull out of the management area.
2748 * If the whole block became dirty, this will kick off an erasure.
2750 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2751 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2752 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2753 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2756 yaffs_ClearChunkBit(dev, block, page);
2760 if (bi->pagesInUse == 0 &&
2761 !bi->hasShrinkHeader &&
2762 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2763 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2764 yaffs_BlockBecameDirty(dev, block);
2768 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2773 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2774 const __u8 * buffer, int nBytes,
2777 /* Find old chunk Need to do this to get serial number
2778 * Write new one and patch into tree.
2779 * Invalidate old tags.
2783 yaffs_ExtendedTags prevTags;
2786 yaffs_ExtendedTags newTags;
2788 yaffs_Device *dev = in->myDev;
2790 yaffs_CheckGarbageCollection(dev);
2792 /* Get the previous chunk at this location in the file if it exists */
2793 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2795 /* Set up new tags */
2796 yaffs_InitialiseTags(&newTags);
2798 newTags.chunkId = chunkInInode;
2799 newTags.objectId = in->objectId;
2800 newTags.serialNumber =
2801 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2802 newTags.byteCount = nBytes;
2805 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2808 if (newChunkId >= 0) {
2809 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2811 if (prevChunkId >= 0) {
2812 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2816 yaffs_CheckFileSanity(in);
2822 /* UpdateObjectHeader updates the header on NAND for an object.
2823 * If name is not NULL, then that new name is used.
2825 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2826 int isShrink, int shadows)
2829 yaffs_BlockInfo *bi;
2831 yaffs_Device *dev = in->myDev;
2837 yaffs_ExtendedTags newTags;
2839 __u8 *buffer = NULL;
2840 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2842 yaffs_ObjectHeader *oh = NULL;
2844 if (!in->fake || force) {
2846 yaffs_CheckGarbageCollection(dev);
2848 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2849 oh = (yaffs_ObjectHeader *) buffer;
2851 prevChunkId = in->chunkId;
2853 if (prevChunkId >= 0) {
2854 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2856 memcpy(oldName, oh->name, sizeof(oh->name));
2859 memset(buffer, 0xFF, dev->nBytesPerChunk);
2861 oh->type = in->variantType;
2862 oh->yst_mode = in->yst_mode;
2863 oh->shadowsObject = shadows;
2865 #ifdef CONFIG_YAFFS_WINCE
2866 oh->win_atime[0] = in->win_atime[0];
2867 oh->win_ctime[0] = in->win_ctime[0];
2868 oh->win_mtime[0] = in->win_mtime[0];
2869 oh->win_atime[1] = in->win_atime[1];
2870 oh->win_ctime[1] = in->win_ctime[1];
2871 oh->win_mtime[1] = in->win_mtime[1];
2873 oh->yst_uid = in->yst_uid;
2874 oh->yst_gid = in->yst_gid;
2875 oh->yst_atime = in->yst_atime;
2876 oh->yst_mtime = in->yst_mtime;
2877 oh->yst_ctime = in->yst_ctime;
2878 oh->yst_rdev = in->yst_rdev;
2881 oh->parentObjectId = in->parent->objectId;
2883 oh->parentObjectId = 0;
2886 if (name && *name) {
2887 memset(oh->name, 0, sizeof(oh->name));
2888 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2889 } else if (prevChunkId) {
2890 memcpy(oh->name, oldName, sizeof(oh->name));
2892 memset(oh->name, 0, sizeof(oh->name));
2895 oh->isShrink = isShrink;
2897 switch (in->variantType) {
2898 case YAFFS_OBJECT_TYPE_UNKNOWN:
2899 /* Should not happen */
2901 case YAFFS_OBJECT_TYPE_FILE:
2903 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2904 || oh->parentObjectId ==
2905 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2906 fileVariant.fileSize;
2908 case YAFFS_OBJECT_TYPE_HARDLINK:
2909 oh->equivalentObjectId =
2910 in->variant.hardLinkVariant.equivalentObjectId;
2912 case YAFFS_OBJECT_TYPE_SPECIAL:
2915 case YAFFS_OBJECT_TYPE_DIRECTORY:
2918 case YAFFS_OBJECT_TYPE_SYMLINK:
2919 yaffs_strncpy(oh->alias,
2920 in->variant.symLinkVariant.alias,
2921 YAFFS_MAX_ALIAS_LENGTH);
2922 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2927 yaffs_InitialiseTags(&newTags);
2929 newTags.chunkId = 0;
2930 newTags.objectId = in->objectId;
2931 newTags.serialNumber = in->serial;
2933 /* Add extra info for file header */
2935 newTags.extraHeaderInfoAvailable = 1;
2936 newTags.extraParentObjectId = oh->parentObjectId;
2937 newTags.extraFileLength = oh->fileSize;
2938 newTags.extraIsShrinkHeader = oh->isShrink;
2939 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2940 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2941 newTags.extraObjectType = in->variantType;
2943 /* Create new chunk in NAND */
2945 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2946 (prevChunkId >= 0) ? 1 : 0);
2948 if (newChunkId >= 0) {
2950 in->chunkId = newChunkId;
2952 if (prevChunkId >= 0) {
2953 yaffs_DeleteChunk(dev, prevChunkId, 1,
2959 /* If this was a shrink, then mark the block that the chunk lives on */
2961 bi = yaffs_GetBlockInfo(in->myDev,
2962 newChunkId /in->myDev-> nChunksPerBlock);
2963 bi->hasShrinkHeader = 1;
2968 retVal = newChunkId;
2973 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2978 /*------------------------ Short Operations Cache ----------------------------------------
2979 * In many situations where there is no high level buffering (eg WinCE) a lot of
2980 * reads might be short sequential reads, and a lot of writes may be short
2981 * sequential writes. eg. scanning/writing a jpeg file.
2982 * In these cases, a short read/write cache can provide a huge perfomance benefit
2983 * with dumb-as-a-rock code.
2984 * In Linux, the page cache provides read buffering aand the short op cache provides write
2987 * There are a limited number (~10) of cache chunks per device so that we don't
2988 * need a very intelligent search.
2991 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2993 yaffs_Device *dev = obj->myDev;
2994 int lowest = -99; /* Stop compiler whining. */
2996 yaffs_ChunkCache *cache;
2997 int chunkWritten = 0;
2998 int nCaches = obj->myDev->nShortOpCaches;
3004 /* Find the dirty cache for this object with the lowest chunk id. */
3005 for (i = 0; i < nCaches; i++) {
3006 if (dev->srCache[i].object == obj &&
3007 dev->srCache[i].dirty) {
3009 || dev->srCache[i].chunkId <
3011 cache = &dev->srCache[i];
3012 lowest = cache->chunkId;
3017 if (cache && !cache->locked) {
3018 /* Write it out and free it up */
3021 yaffs_WriteChunkDataToObject(cache->object,
3027 cache->object = NULL;
3030 } while (cache && chunkWritten > 0);
3033 /* Hoosterman, disk full while writing cache out. */
3034 T(YAFFS_TRACE_ERROR,
3035 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3042 /*yaffs_FlushEntireDeviceCache(dev)
3047 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3050 int nCaches = dev->nShortOpCaches;
3053 /* Find a dirty object in the cache and flush it...
3054 * until there are no further dirty objects.
3058 for( i = 0; i < nCaches && !obj; i++) {
3059 if (dev->srCache[i].object &&
3060 dev->srCache[i].dirty)
3061 obj = dev->srCache[i].object;
3065 yaffs_FlushFilesChunkCache(obj);
3072 /* Grab us a cache chunk for use.
3073 * First look for an empty one.
3074 * Then look for the least recently used non-dirty one.
3075 * Then look for the least recently used dirty one...., flush and look again.
3077 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3083 if (dev->nShortOpCaches > 0) {
3084 for (i = 0; i < dev->nShortOpCaches; i++) {
3085 if (!dev->srCache[i].object)
3086 return &dev->srCache[i];
3092 usage = 0; /* just to stop the compiler grizzling */
3094 for (i = 0; i < dev->nShortOpCaches; i++) {
3095 if (!dev->srCache[i].dirty &&
3096 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3098 usage = dev->srCache[i].lastUse;
3104 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3111 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3113 yaffs_ChunkCache *cache;
3114 yaffs_Object *theObj;
3119 if (dev->nShortOpCaches > 0) {
3120 /* Try find a non-dirty one... */
3122 cache = yaffs_GrabChunkCacheWorker(dev);
3125 /* They were all dirty, find the last recently used object and flush
3126 * its cache, then find again.
3127 * NB what's here is not very accurate, we actually flush the object
3128 * the last recently used page.
3131 /* With locking we can't assume we can use entry zero */
3138 for (i = 0; i < dev->nShortOpCaches; i++) {
3139 if (dev->srCache[i].object &&
3140 !dev->srCache[i].locked &&
3141 (dev->srCache[i].lastUse < usage || !cache))
3143 usage = dev->srCache[i].lastUse;
3144 theObj = dev->srCache[i].object;
3145 cache = &dev->srCache[i];
3150 if (!cache || cache->dirty) {
3151 /* Flush and try again */
3152 yaffs_FlushFilesChunkCache(theObj);
3153 cache = yaffs_GrabChunkCacheWorker(dev);
3163 /* Find a cached chunk */
3164 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3167 yaffs_Device *dev = obj->myDev;
3169 if (dev->nShortOpCaches > 0) {
3170 for (i = 0; i < dev->nShortOpCaches; i++) {
3171 if (dev->srCache[i].object == obj &&
3172 dev->srCache[i].chunkId == chunkId) {
3175 return &dev->srCache[i];
3182 /* Mark the chunk for the least recently used algorithym */
3183 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3187 if (dev->nShortOpCaches > 0) {
3188 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3189 /* Reset the cache usages */
3191 for (i = 1; i < dev->nShortOpCaches; i++) {
3192 dev->srCache[i].lastUse = 0;
3199 cache->lastUse = dev->srLastUse;
3207 /* Invalidate a single cache page.
3208 * Do this when a whole page gets written,
3209 * ie the short cache for this page is no longer valid.
3211 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3213 if (object->myDev->nShortOpCaches > 0) {
3214 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3217 cache->object = NULL;
3222 /* Invalidate all the cache pages associated with this object
3223 * Do this whenever ther file is deleted or resized.
3225 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3228 yaffs_Device *dev = in->myDev;
3230 if (dev->nShortOpCaches > 0) {
3231 /* Invalidate it. */
3232 for (i = 0; i < dev->nShortOpCaches; i++) {
3233 if (dev->srCache[i].object == in) {
3234 dev->srCache[i].object = NULL;
3240 /*--------------------- Checkpointing --------------------*/
3243 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3245 yaffs_CheckpointValidity cp;
3246 cp.structType = sizeof(cp);
3247 cp.magic = YAFFS_MAGIC;
3249 cp.head = (head) ? 1 : 0;
3251 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3255 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3257 yaffs_CheckpointValidity cp;
3260 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3263 ok = (cp.structType == sizeof(cp)) &&
3264 (cp.magic == YAFFS_MAGIC) &&
3265 (cp.version == 1) &&
3266 (cp.head == ((head) ? 1 : 0));
3270 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3273 cp->nErasedBlocks = dev->nErasedBlocks;
3274 cp->allocationBlock = dev->allocationBlock;
3275 cp->allocationPage = dev->allocationPage;
3276 cp->nFreeChunks = dev->nFreeChunks;
3278 cp->nDeletedFiles = dev->nDeletedFiles;
3279 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3280 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3281 cp->sequenceNumber = dev->sequenceNumber;
3282 cp->oldestDirtySequence = dev->oldestDirtySequence;
3286 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3287 yaffs_CheckpointDevice *cp)
3289 dev->nErasedBlocks = cp->nErasedBlocks;
3290 dev->allocationBlock = cp->allocationBlock;
3291 dev->allocationPage = cp->allocationPage;
3292 dev->nFreeChunks = cp->nFreeChunks;
3294 dev->nDeletedFiles = cp->nDeletedFiles;
3295 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3296 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3297 dev->sequenceNumber = cp->sequenceNumber;
3298 dev->oldestDirtySequence = cp->oldestDirtySequence;
3302 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3304 yaffs_CheckpointDevice cp;
3306 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3310 /* Write device runtime values*/
3311 yaffs_DeviceToCheckpointDevice(&cp,dev);
3312 cp.structType = sizeof(cp);
3314 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3316 /* Write block info */
3318 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3319 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3322 /* Write chunk bits */
3324 nBytes = nBlocks * dev->chunkBitmapStride;
3325 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3331 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3333 yaffs_CheckpointDevice cp;
3335 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3339 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3343 if(cp.structType != sizeof(cp))
3347 yaffs_CheckpointDeviceToDevice(dev,&cp);
3349 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3351 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3355 nBytes = nBlocks * dev->chunkBitmapStride;
3357 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3362 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3366 cp->objectId = obj->objectId;
3367 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3368 cp->chunkId = obj->chunkId;
3369 cp->variantType = obj->variantType;
3370 cp->deleted = obj->deleted;
3371 cp->softDeleted = obj->softDeleted;
3372 cp->unlinked = obj->unlinked;
3373 cp->fake = obj->fake;
3374 cp->renameAllowed = obj->renameAllowed;
3375 cp->unlinkAllowed = obj->unlinkAllowed;
3376 cp->serial = obj->serial;
3377 cp->nDataChunks = obj->nDataChunks;
3379 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3380 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3381 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3382 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3385 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3388 yaffs_Object *parent;
3390 obj->objectId = cp->objectId;
3393 parent = yaffs_FindOrCreateObjectByNumber(
3396 YAFFS_OBJECT_TYPE_DIRECTORY);
3401 yaffs_AddObjectToDirectory(parent, obj);
3403 obj->chunkId = cp->chunkId;
3404 obj->variantType = cp->variantType;
3405 obj->deleted = cp->deleted;
3406 obj->softDeleted = cp->softDeleted;
3407 obj->unlinked = cp->unlinked;
3408 obj->fake = cp->fake;
3409 obj->renameAllowed = cp->renameAllowed;
3410 obj->unlinkAllowed = cp->unlinkAllowed;
3411 obj->serial = cp->serial;
3412 obj->nDataChunks = cp->nDataChunks;
3414 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3415 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3416 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3417 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3419 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3420 obj->lazyLoaded = 1;
3425 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3426 __u32 level, int chunkOffset)
3429 yaffs_Device *dev = in->myDev;
3431 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3436 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3437 if (tn->internal[i]) {
3438 ok = yaffs_CheckpointTnodeWorker(in,
3441 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3444 } else if (level == 0) {
3445 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3446 /* printf("write tnode at %d\n",baseOffset); */
3447 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3449 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3457 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3459 __u32 endMarker = ~0;
3462 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3463 ok = yaffs_CheckpointTnodeWorker(obj,
3464 obj->variant.fileVariant.top,
3465 obj->variant.fileVariant.topLevel,
3468 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3475 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3479 yaffs_Device *dev = obj->myDev;
3480 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3483 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3485 while(ok && (~baseChunk)){
3486 /* Read level 0 tnode */
3488 /* printf("read tnode at %d\n",baseChunk); */
3489 tn = yaffs_GetTnodeRaw(dev);
3491 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3492 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3497 ok = yaffs_AddOrFindLevel0Tnode(dev,
3504 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3512 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3515 yaffs_CheckpointObject cp;
3518 struct list_head *lh;
3521 /* Iterate through the objects in each hash entry,
3522 * dumping them to the checkpointing stream.
3525 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3526 list_for_each(lh, &dev->objectBucket[i].list) {
3528 obj = list_entry(lh, yaffs_Object, hashLink);
3529 if (!obj->deferedFree) {
3530 yaffs_ObjectToCheckpointObject(&cp,obj);
3531 cp.structType = sizeof(cp);
3532 /* printf("Write out object %d type %d\n",obj->objectId,obj->variantType); */
3533 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3535 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3536 ok = yaffs_WriteCheckpointTnodes(obj);
3543 /* Dump end of list */
3544 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3545 cp.structType = sizeof(cp);
3548 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3553 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3556 yaffs_CheckpointObject cp;
3559 yaffs_Object *hardList = NULL;
3561 while(ok && !done) {
3562 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3563 if(cp.structType != sizeof(cp)) {
3564 /* printf("structure parsing failed\n"); */
3568 if(ok && cp.objectId == ~0)
3571 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Read object %d parent %d type %d" TENDSTR),
3572 cp.objectId,cp.parentId,cp.variantType));
3573 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3575 yaffs_CheckpointObjectToObject(obj,&cp);
3576 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3577 ok = yaffs_ReadCheckpointTnodes(obj);
3578 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3579 obj->hardLinks.next =
3580 (struct list_head *)
3590 yaffs_HardlinkFixup(dev,hardList);
3595 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3600 ok = yaffs_CheckpointOpen(dev,1);
3603 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3605 ok = yaffs_WriteCheckpointDevice(dev);
3607 ok = yaffs_WriteCheckpointObjects(dev);
3609 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3611 if(!yaffs_CheckpointClose(dev))
3615 dev->isCheckpointed = 1;
3617 dev->isCheckpointed = 0;
3619 return dev->isCheckpointed;
3622 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3626 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3629 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3631 ok = yaffs_ReadCheckpointDevice(dev);
3633 ok = yaffs_ReadCheckpointObjects(dev);
3635 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3639 if(!yaffs_CheckpointClose(dev))
3643 dev->isCheckpointed = 1;
3645 dev->isCheckpointed = 0;
3651 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3653 if(dev->isCheckpointed ||
3654 dev->blocksInCheckpoint > 0){
3655 dev->isCheckpointed = 0;
3656 yaffs_CheckpointInvalidateStream(dev);
3657 if(dev->superBlock && dev->markSuperBlockDirty)
3658 dev->markSuperBlockDirty(dev->superBlock);
3663 int yaffs_CheckpointSave(yaffs_Device *dev)
3665 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3667 if(!dev->isCheckpointed)
3668 yaffs_WriteCheckpointData(dev);
3670 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3672 return dev->isCheckpointed;
3675 int yaffs_CheckpointRestore(yaffs_Device *dev)
3678 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3680 retval = yaffs_ReadCheckpointData(dev);
3682 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3687 /*--------------------- File read/write ------------------------
3688 * Read and write have very similar structures.
3689 * In general the read/write has three parts to it
3690 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3691 * Some complete chunks
3692 * An incomplete chunk to end off with
3694 * Curve-balls: the first chunk might also be the last chunk.
3697 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3706 yaffs_ChunkCache *cache;
3713 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3714 start = offset % dev->nBytesPerChunk;
3716 /* OK now check for the curveball where the start and end are in
3719 if ((start + n) < dev->nBytesPerChunk) {
3722 nToCopy = dev->nBytesPerChunk - start;
3725 cache = yaffs_FindChunkCache(in, chunk);
3727 /* If the chunk is already in the cache or it is less than a whole chunk
3728 * then use the cache (if there is caching)
3729 * else bypass the cache.
3731 if (cache || nToCopy != dev->nBytesPerChunk) {
3732 if (dev->nShortOpCaches > 0) {
3734 /* If we can't find the data in the cache, then load it up. */
3737 cache = yaffs_GrabChunkCache(in->myDev);
3739 cache->chunkId = chunk;
3742 yaffs_ReadChunkDataFromObject(in, chunk,
3748 yaffs_UseChunkCache(dev, cache, 0);
3752 #ifdef CONFIG_YAFFS_WINCE
3753 yfsd_UnlockYAFFS(TRUE);
3755 memcpy(buffer, &cache->data[start], nToCopy);
3757 #ifdef CONFIG_YAFFS_WINCE
3758 yfsd_LockYAFFS(TRUE);
3762 /* Read into the local buffer then copy..*/
3765 yaffs_GetTempBuffer(dev, __LINE__);
3766 yaffs_ReadChunkDataFromObject(in, chunk,
3768 #ifdef CONFIG_YAFFS_WINCE
3769 yfsd_UnlockYAFFS(TRUE);
3771 memcpy(buffer, &localBuffer[start], nToCopy);
3773 #ifdef CONFIG_YAFFS_WINCE
3774 yfsd_LockYAFFS(TRUE);
3776 yaffs_ReleaseTempBuffer(dev, localBuffer,
3781 #ifdef CONFIG_YAFFS_WINCE
3782 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3784 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3785 * This is because we otherwise screw up WinCE's memory mapper
3787 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3789 #ifdef CONFIG_YAFFS_WINCE
3790 yfsd_UnlockYAFFS(TRUE);
3792 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3794 #ifdef CONFIG_YAFFS_WINCE
3795 yfsd_LockYAFFS(TRUE);
3796 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3800 /* A full chunk. Read directly into the supplied buffer. */
3801 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3815 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3816 int nBytes, int writeThrough)
3825 int startOfWrite = offset;
3826 int chunkWritten = 0;
3833 while (n > 0 && chunkWritten >= 0) {
3834 chunk = offset / dev->nBytesPerChunk + 1;
3835 start = offset % dev->nBytesPerChunk;
3837 /* OK now check for the curveball where the start and end are in
3841 if ((start + n) < dev->nBytesPerChunk) {
3844 /* Now folks, to calculate how many bytes to write back....
3845 * If we're overwriting and not writing to then end of file then
3846 * we need to write back as much as was there before.
3850 in->variant.fileVariant.fileSize -
3851 ((chunk - 1) * dev->nBytesPerChunk);
3853 if (nBytesRead > dev->nBytesPerChunk) {
3854 nBytesRead = dev->nBytesPerChunk;
3859 (start + n)) ? nBytesRead : (start + n);
3862 nToCopy = dev->nBytesPerChunk - start;
3863 nToWriteBack = dev->nBytesPerChunk;
3866 if (nToCopy != dev->nBytesPerChunk) {
3867 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3868 if (dev->nShortOpCaches > 0) {
3869 yaffs_ChunkCache *cache;
3870 /* If we can't find the data in the cache, then load the cache */
3871 cache = yaffs_FindChunkCache(in, chunk);
3874 && yaffs_CheckSpaceForAllocation(in->
3876 cache = yaffs_GrabChunkCache(in->myDev);
3878 cache->chunkId = chunk;
3881 yaffs_ReadChunkDataFromObject(in, chunk,
3887 !yaffs_CheckSpaceForAllocation(in->myDev)){
3888 /* Drop the cache if it was a read cache item and
3889 * no space check has been made for it.
3895 yaffs_UseChunkCache(dev, cache, 1);
3897 #ifdef CONFIG_YAFFS_WINCE
3898 yfsd_UnlockYAFFS(TRUE);
3901 memcpy(&cache->data[start], buffer,
3904 #ifdef CONFIG_YAFFS_WINCE
3905 yfsd_LockYAFFS(TRUE);
3908 cache->nBytes = nToWriteBack;
3912 yaffs_WriteChunkDataToObject
3915 cache->data, cache->nBytes,
3921 chunkWritten = -1; /* fail the write */
3924 /* An incomplete start or end chunk (or maybe both start and end chunk)
3925 * Read into the local buffer then copy, then copy over and write back.
3929 yaffs_GetTempBuffer(dev, __LINE__);
3931 yaffs_ReadChunkDataFromObject(in, chunk,
3934 #ifdef CONFIG_YAFFS_WINCE
3935 yfsd_UnlockYAFFS(TRUE);
3938 memcpy(&localBuffer[start], buffer, nToCopy);
3940 #ifdef CONFIG_YAFFS_WINCE
3941 yfsd_LockYAFFS(TRUE);
3944 yaffs_WriteChunkDataToObject(in, chunk,
3949 yaffs_ReleaseTempBuffer(dev, localBuffer,
3956 #ifdef CONFIG_YAFFS_WINCE
3957 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3958 * This is because we otherwise screw up WinCE's memory mapper
3960 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3961 #ifdef CONFIG_YAFFS_WINCE
3962 yfsd_UnlockYAFFS(TRUE);
3964 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3965 #ifdef CONFIG_YAFFS_WINCE
3966 yfsd_LockYAFFS(TRUE);
3969 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3970 dev->nBytesPerChunk,
3972 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3974 /* A full chunk. Write directly from the supplied buffer. */
3976 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3977 dev->nBytesPerChunk,
3980 /* Since we've overwritten the cached data, we better invalidate it. */
3981 yaffs_InvalidateChunkCache(in, chunk);
3984 if (chunkWritten >= 0) {
3993 /* Update file object */
3995 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3996 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4005 /* ---------------------- File resizing stuff ------------------ */
4007 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4010 yaffs_Device *dev = in->myDev;
4011 int oldFileSize = in->variant.fileVariant.fileSize;
4013 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
4015 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
4016 dev->nBytesPerChunk;
4020 /* Delete backwards so that we don't end up with holes if
4021 * power is lost part-way through the operation.
4023 for (i = lastDel; i >= startDel; i--) {
4024 /* NB this could be optimised somewhat,
4025 * eg. could retrieve the tags and write them without
4026 * using yaffs_DeleteChunk
4029 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4032 (dev->internalStartBlock * dev->nChunksPerBlock)
4034 ((dev->internalEndBlock +
4035 1) * dev->nChunksPerBlock)) {
4036 T(YAFFS_TRACE_ALWAYS,
4037 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4041 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4048 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
4051 int oldFileSize = in->variant.fileVariant.fileSize;
4052 int sizeOfPartialChunk;
4053 yaffs_Device *dev = in->myDev;
4055 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
4057 yaffs_FlushFilesChunkCache(in);
4058 yaffs_InvalidateWholeChunkCache(in);
4060 yaffs_CheckGarbageCollection(dev);
4062 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4063 return yaffs_GetFileSize(in);
4066 if (newSize == oldFileSize) {
4070 if (newSize < oldFileSize) {
4072 yaffs_PruneResizedChunks(in, newSize);
4074 if (sizeOfPartialChunk != 0) {
4075 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
4076 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4078 /* Got to read and rewrite the last chunk with its new size and zero pad */
4079 yaffs_ReadChunkDataFromObject(in, lastChunk,
4082 memset(localBuffer + sizeOfPartialChunk, 0,
4083 dev->nBytesPerChunk - sizeOfPartialChunk);
4085 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4086 sizeOfPartialChunk, 1);
4088 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4091 in->variant.fileVariant.fileSize = newSize;
4093 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4095 /* Write a new object header.
4096 * show we've shrunk the file, if need be
4097 * Do this only if the file is not in the deleted directories.
4099 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4100 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4101 yaffs_UpdateObjectHeader(in, NULL, 0,
4102 (newSize < oldFileSize) ? 1 : 0, 0);
4108 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4110 obj = yaffs_GetEquivalentObject(obj);
4112 switch (obj->variantType) {
4113 case YAFFS_OBJECT_TYPE_FILE:
4114 return obj->variant.fileVariant.fileSize;
4115 case YAFFS_OBJECT_TYPE_SYMLINK:
4116 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4124 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4128 yaffs_FlushFilesChunkCache(in);
4130 #ifdef CONFIG_YAFFS_WINCE
4131 yfsd_WinFileTimeNow(in->win_mtime);
4134 in->yst_mtime = Y_CURRENT_TIME;
4140 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4141 0) ? YAFFS_OK : YAFFS_FAIL;
4150 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4153 /* First off, invalidate the file's data in the cache, without flushing. */
4154 yaffs_InvalidateWholeChunkCache(in);
4156 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4157 /* Move to the unlinked directory so we have a record that it was deleted. */
4158 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4162 yaffs_RemoveObjectFromDirectory(in);
4163 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4166 yaffs_FreeObject(in);
4171 /* yaffs_DeleteFile deletes the whole file data
4172 * and the inode associated with the file.
4173 * It does not delete the links associated with the file.
4175 static int yaffs_UnlinkFile(yaffs_Object * in)
4179 int immediateDeletion = 0;
4184 immediateDeletion = 1;
4188 if (in->inUse <= 0) {
4189 immediateDeletion = 1;
4193 if (immediateDeletion) {
4195 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4197 T(YAFFS_TRACE_TRACING,
4198 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4201 in->myDev->nDeletedFiles++;
4202 if (0 && in->myDev->isYaffs2) {
4203 yaffs_ResizeFile(in, 0);
4205 yaffs_SoftDeleteFile(in);
4208 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4216 int yaffs_DeleteFile(yaffs_Object * in)
4218 int retVal = YAFFS_OK;
4220 if (in->nDataChunks > 0) {
4221 /* Use soft deletion if there is data in the file */
4222 if (!in->unlinked) {
4223 retVal = yaffs_UnlinkFile(in);
4225 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4227 in->myDev->nDeletedFiles++;
4228 yaffs_SoftDeleteFile(in);
4230 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4232 /* The file has no data chunks so we toss it immediately */
4233 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4234 in->variant.fileVariant.top = NULL;
4235 yaffs_DoGenericObjectDeletion(in);
4241 static int yaffs_DeleteDirectory(yaffs_Object * in)
4243 /* First check that the directory is empty. */
4244 if (list_empty(&in->variant.directoryVariant.children)) {
4245 return yaffs_DoGenericObjectDeletion(in);
4252 static int yaffs_DeleteSymLink(yaffs_Object * in)
4254 YFREE(in->variant.symLinkVariant.alias);
4256 return yaffs_DoGenericObjectDeletion(in);
4259 static int yaffs_DeleteHardLink(yaffs_Object * in)
4261 /* remove this hardlink from the list assocaited with the equivalent
4264 list_del(&in->hardLinks);
4265 return yaffs_DoGenericObjectDeletion(in);
4268 static void yaffs_DestroyObject(yaffs_Object * obj)
4270 switch (obj->variantType) {
4271 case YAFFS_OBJECT_TYPE_FILE:
4272 yaffs_DeleteFile(obj);
4274 case YAFFS_OBJECT_TYPE_DIRECTORY:
4275 yaffs_DeleteDirectory(obj);
4277 case YAFFS_OBJECT_TYPE_SYMLINK:
4278 yaffs_DeleteSymLink(obj);
4280 case YAFFS_OBJECT_TYPE_HARDLINK:
4281 yaffs_DeleteHardLink(obj);
4283 case YAFFS_OBJECT_TYPE_SPECIAL:
4284 yaffs_DoGenericObjectDeletion(obj);
4286 case YAFFS_OBJECT_TYPE_UNKNOWN:
4287 break; /* should not happen. */
4291 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4294 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4295 return yaffs_DeleteHardLink(obj);
4296 } else if (!list_empty(&obj->hardLinks)) {
4297 /* Curve ball: We're unlinking an object that has a hardlink.
4299 * This problem arises because we are not strictly following
4300 * The Linux link/inode model.
4302 * We can't really delete the object.
4303 * Instead, we do the following:
4304 * - Select a hardlink.
4305 * - Unhook it from the hard links
4306 * - Unhook it from its parent directory (so that the rename can work)
4307 * - Rename the object to the hardlink's name.
4308 * - Delete the hardlink
4313 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4315 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4317 list_del_init(&hl->hardLinks);
4318 list_del_init(&hl->siblings);
4320 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4322 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4324 if (retVal == YAFFS_OK) {
4325 retVal = yaffs_DoGenericObjectDeletion(hl);
4330 switch (obj->variantType) {
4331 case YAFFS_OBJECT_TYPE_FILE:
4332 return yaffs_UnlinkFile(obj);
4334 case YAFFS_OBJECT_TYPE_DIRECTORY:
4335 return yaffs_DeleteDirectory(obj);
4337 case YAFFS_OBJECT_TYPE_SYMLINK:
4338 return yaffs_DeleteSymLink(obj);
4340 case YAFFS_OBJECT_TYPE_SPECIAL:
4341 return yaffs_DoGenericObjectDeletion(obj);
4343 case YAFFS_OBJECT_TYPE_HARDLINK:
4344 case YAFFS_OBJECT_TYPE_UNKNOWN:
4352 static int yaffs_UnlinkObject( yaffs_Object *obj)
4355 if (obj && obj->unlinkAllowed) {
4356 return yaffs_UnlinkWorker(obj);
4362 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4366 obj = yaffs_FindObjectByName(dir, name);
4367 return yaffs_UnlinkObject(obj);
4370 /*----------------------- Initialisation Scanning ---------------------- */
4372 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4373 int backwardScanning)
4377 if (!backwardScanning) {
4378 /* Handle YAFFS1 forward scanning case
4379 * For YAFFS1 we always do the deletion
4383 /* Handle YAFFS2 case (backward scanning)
4384 * If the shadowed object exists then ignore.
4386 if (yaffs_FindObjectByNumber(dev, objId)) {
4391 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4392 * We put it in unlinked dir to be cleaned up after the scanning
4395 yaffs_FindOrCreateObjectByNumber(dev, objId,
4396 YAFFS_OBJECT_TYPE_FILE);
4397 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4398 obj->variant.fileVariant.shrinkSize = 0;
4399 obj->valid = 1; /* So that we don't read any other info for this file */
4409 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4416 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4418 in = yaffs_FindObjectByNumber(dev,
4419 hl->variant.hardLinkVariant.
4420 equivalentObjectId);
4423 /* Add the hardlink pointers */
4424 hl->variant.hardLinkVariant.equivalentObject = in;
4425 list_add(&hl->hardLinks, &in->hardLinks);
4427 /* Todo Need to report/handle this better.
4428 * Got a problem... hardlink to a non-existant object
4430 hl->variant.hardLinkVariant.equivalentObject = NULL;
4431 INIT_LIST_HEAD(&hl->hardLinks);
4443 static int ybicmp(const void *a, const void *b){
4444 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4445 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4446 register int ablock = ((yaffs_BlockIndex *)a)->block;
4447 register int bblock = ((yaffs_BlockIndex *)b)->block;
4449 return ablock - bblock;
4455 static int yaffs_Scan(yaffs_Device * dev)
4457 yaffs_ExtendedTags tags;
4462 int nBlocksToScan = 0;
4467 yaffs_BlockState state;
4468 yaffs_Object *hardList = NULL;
4470 yaffs_BlockInfo *bi;
4472 yaffs_ObjectHeader *oh;
4474 yaffs_Object *parent;
4475 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4479 yaffs_BlockIndex *blockIndex = NULL;
4481 if (dev->isYaffs2) {
4483 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4487 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4490 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4491 dev->internalStartBlock, dev->internalEndBlock));
4493 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4495 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4497 if (dev->isYaffs2) {
4498 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4501 /* Scan all the blocks to determine their state */
4502 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4503 bi = yaffs_GetBlockInfo(dev, blk);
4504 yaffs_ClearChunkBits(dev, blk);
4506 bi->softDeletions = 0;
4508 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4510 bi->blockState = state;
4511 bi->sequenceNumber = sequenceNumber;
4513 T(YAFFS_TRACE_SCAN_DEBUG,
4514 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4515 state, sequenceNumber));
4517 if (state == YAFFS_BLOCK_STATE_DEAD) {
4518 T(YAFFS_TRACE_BAD_BLOCKS,
4519 (TSTR("block %d is bad" TENDSTR), blk));
4520 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4521 T(YAFFS_TRACE_SCAN_DEBUG,
4522 (TSTR("Block empty " TENDSTR)));
4523 dev->nErasedBlocks++;
4524 dev->nFreeChunks += dev->nChunksPerBlock;
4525 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4527 /* Determine the highest sequence number */
4528 if (dev->isYaffs2 &&
4529 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4530 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4532 blockIndex[nBlocksToScan].seq = sequenceNumber;
4533 blockIndex[nBlocksToScan].block = blk;
4537 if (sequenceNumber >= dev->sequenceNumber) {
4538 dev->sequenceNumber = sequenceNumber;
4540 } else if (dev->isYaffs2) {
4541 /* TODO: Nasty sequence number! */
4544 ("Block scanning block %d has bad sequence number %d"
4545 TENDSTR), blk, sequenceNumber));
4552 * Dungy old bubble sort for now...
4554 if (dev->isYaffs2) {
4555 yaffs_BlockIndex temp;
4559 for (i = 0; i < nBlocksToScan; i++)
4560 for (j = i + 1; j < nBlocksToScan; j++)
4561 if (blockIndex[i].seq > blockIndex[j].seq) {
4562 temp = blockIndex[j];
4563 blockIndex[j] = blockIndex[i];
4564 blockIndex[i] = temp;
4568 /* Now scan the blocks looking at the data. */
4569 if (dev->isYaffs2) {
4571 endIterator = nBlocksToScan - 1;
4572 T(YAFFS_TRACE_SCAN_DEBUG,
4573 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4575 startIterator = dev->internalStartBlock;
4576 endIterator = dev->internalEndBlock;
4579 /* For each block.... */
4580 for (blockIterator = startIterator; blockIterator <= endIterator;
4583 if (dev->isYaffs2) {
4584 /* get the block to scan in the correct order */
4585 blk = blockIndex[blockIterator].block;
4587 blk = blockIterator;
4590 bi = yaffs_GetBlockInfo(dev, blk);
4591 state = bi->blockState;
4595 /* For each chunk in each block that needs scanning....*/
4596 for (c = 0; c < dev->nChunksPerBlock &&
4597 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4598 /* Read the tags and decide what to do */
4599 chunk = blk * dev->nChunksPerBlock + c;
4601 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4604 /* Let's have a good look at this chunk... */
4606 if (!dev->isYaffs2 && tags.chunkDeleted) {
4612 /*T((" %d %d deleted\n",blk,c)); */
4613 } else if (!tags.chunkUsed) {
4614 /* An unassigned chunk in the block
4615 * This means that either the block is empty or
4616 * this is the one being allocated from
4620 /* We're looking at the first chunk in the block so the block is unused */
4621 state = YAFFS_BLOCK_STATE_EMPTY;
4622 dev->nErasedBlocks++;
4624 /* this is the block being allocated from */
4627 (" Allocating from %d %d" TENDSTR),
4629 state = YAFFS_BLOCK_STATE_ALLOCATING;
4630 dev->allocationBlock = blk;
4631 dev->allocationPage = c;
4632 dev->allocationBlockFinder = blk;
4633 /* Set it to here to encourage the allocator to go forth from here. */
4635 /* Yaffs2 sanity check:
4636 * This should be the one with the highest sequence number
4639 && (dev->sequenceNumber !=
4640 bi->sequenceNumber)) {
4641 T(YAFFS_TRACE_ALWAYS,
4643 ("yaffs: Allocation block %d was not highest sequence id:"
4644 " block seq = %d, dev seq = %d"
4645 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4649 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4650 } else if (tags.chunkId > 0) {
4651 /* chunkId > 0 so it is a data chunk... */
4652 unsigned int endpos;
4654 yaffs_SetChunkBit(dev, blk, c);
4657 in = yaffs_FindOrCreateObjectByNumber(dev,
4660 YAFFS_OBJECT_TYPE_FILE);
4661 /* PutChunkIntoFile checks for a clash (two data chunks with
4662 * the same chunkId).
4664 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4667 (tags.chunkId - 1) * dev->nBytesPerChunk +
4669 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4670 && in->variant.fileVariant.scannedFileSize <
4672 in->variant.fileVariant.
4673 scannedFileSize = endpos;
4674 if (!dev->useHeaderFileSize) {
4675 in->variant.fileVariant.
4677 in->variant.fileVariant.
4682 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4684 /* chunkId == 0, so it is an ObjectHeader.
4685 * Thus, we read in the object header and make the object
4687 yaffs_SetChunkBit(dev, blk, c);
4690 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4694 oh = (yaffs_ObjectHeader *) chunkData;
4696 in = yaffs_FindObjectByNumber(dev,
4698 if (in && in->variantType != oh->type) {
4699 /* This should not happen, but somehow
4700 * Wev'e ended up with an objectId that has been reused but not yet
4701 * deleted, and worse still it has changed type. Delete the old object.
4704 yaffs_DestroyObject(in);
4709 in = yaffs_FindOrCreateObjectByNumber(dev,
4714 if (oh->shadowsObject > 0) {
4715 yaffs_HandleShadowedObject(dev,
4722 /* We have already filled this one. We have a duplicate and need to resolve it. */
4724 unsigned existingSerial = in->serial;
4725 unsigned newSerial = tags.serialNumber;
4727 if (dev->isYaffs2 ||
4728 ((existingSerial + 1) & 3) ==
4730 /* Use new one - destroy the exisiting one */
4731 yaffs_DeleteChunk(dev,
4736 /* Use existing - destroy this one. */
4737 yaffs_DeleteChunk(dev, chunk, 1,
4743 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4744 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4745 /* We only load some info, don't fiddle with directory structure */
4747 in->variantType = oh->type;
4749 in->yst_mode = oh->yst_mode;
4750 #ifdef CONFIG_YAFFS_WINCE
4751 in->win_atime[0] = oh->win_atime[0];
4752 in->win_ctime[0] = oh->win_ctime[0];
4753 in->win_mtime[0] = oh->win_mtime[0];
4754 in->win_atime[1] = oh->win_atime[1];
4755 in->win_ctime[1] = oh->win_ctime[1];
4756 in->win_mtime[1] = oh->win_mtime[1];
4758 in->yst_uid = oh->yst_uid;
4759 in->yst_gid = oh->yst_gid;
4760 in->yst_atime = oh->yst_atime;
4761 in->yst_mtime = oh->yst_mtime;
4762 in->yst_ctime = oh->yst_ctime;
4763 in->yst_rdev = oh->yst_rdev;
4765 in->chunkId = chunk;
4767 } else if (!in->valid) {
4768 /* we need to load this info */
4771 in->variantType = oh->type;
4773 in->yst_mode = oh->yst_mode;
4774 #ifdef CONFIG_YAFFS_WINCE
4775 in->win_atime[0] = oh->win_atime[0];
4776 in->win_ctime[0] = oh->win_ctime[0];
4777 in->win_mtime[0] = oh->win_mtime[0];
4778 in->win_atime[1] = oh->win_atime[1];
4779 in->win_ctime[1] = oh->win_ctime[1];
4780 in->win_mtime[1] = oh->win_mtime[1];
4782 in->yst_uid = oh->yst_uid;
4783 in->yst_gid = oh->yst_gid;
4784 in->yst_atime = oh->yst_atime;
4785 in->yst_mtime = oh->yst_mtime;
4786 in->yst_ctime = oh->yst_ctime;
4787 in->yst_rdev = oh->yst_rdev;
4789 in->chunkId = chunk;
4791 yaffs_SetObjectName(in, oh->name);
4794 /* directory stuff...
4799 yaffs_FindOrCreateObjectByNumber
4800 (dev, oh->parentObjectId,
4801 YAFFS_OBJECT_TYPE_DIRECTORY);
4802 if (parent->variantType ==
4803 YAFFS_OBJECT_TYPE_UNKNOWN) {
4804 /* Set up as a directory */
4805 parent->variantType =
4806 YAFFS_OBJECT_TYPE_DIRECTORY;
4807 INIT_LIST_HEAD(&parent->variant.
4810 } else if (parent->variantType !=
4811 YAFFS_OBJECT_TYPE_DIRECTORY)
4813 /* Hoosterman, another problem....
4814 * We're trying to use a non-directory as a directory
4817 T(YAFFS_TRACE_ERROR,
4819 ("yaffs tragedy: attempting to use non-directory as"
4820 " a directory in scan. Put in lost+found."
4822 parent = dev->lostNFoundDir;
4825 yaffs_AddObjectToDirectory(parent, in);
4827 if (0 && (parent == dev->deletedDir ||
4828 parent == dev->unlinkedDir)) {
4829 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
4830 dev->nDeletedFiles++;
4832 /* Note re hardlinks.
4833 * Since we might scan a hardlink before its equivalent object is scanned
4834 * we put them all in a list.
4835 * After scanning is complete, we should have all the objects, so we run through this
4836 * list and fix up all the chains.
4839 switch (in->variantType) {
4840 case YAFFS_OBJECT_TYPE_UNKNOWN:
4841 /* Todo got a problem */
4843 case YAFFS_OBJECT_TYPE_FILE:
4846 /* Prune back the shrunken chunks */
4847 yaffs_PruneResizedChunks
4849 /* Mark the block as having a shrinkHeader */
4850 bi->hasShrinkHeader = 1;
4853 if (dev->useHeaderFileSize)
4855 in->variant.fileVariant.
4860 case YAFFS_OBJECT_TYPE_HARDLINK:
4861 in->variant.hardLinkVariant.
4862 equivalentObjectId =
4863 oh->equivalentObjectId;
4864 in->hardLinks.next =
4865 (struct list_head *)
4869 case YAFFS_OBJECT_TYPE_DIRECTORY:
4872 case YAFFS_OBJECT_TYPE_SPECIAL:
4875 case YAFFS_OBJECT_TYPE_SYMLINK:
4876 in->variant.symLinkVariant.
4878 yaffs_CloneString(oh->alias);
4882 if (parent == dev->deletedDir) {
4883 yaffs_DestroyObject(in);
4884 bi->hasShrinkHeader = 1;
4890 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4891 /* If we got this far while scanning, then the block is fully allocated.*/
4892 state = YAFFS_BLOCK_STATE_FULL;
4895 bi->blockState = state;
4897 /* Now let's see if it was dirty */
4898 if (bi->pagesInUse == 0 &&
4899 !bi->hasShrinkHeader &&
4900 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4901 yaffs_BlockBecameDirty(dev, blk);
4911 /* Ok, we've done all the scanning.
4912 * Fix up the hard link chains.
4913 * We should now have scanned all the objects, now it's time to add these
4917 yaffs_HardlinkFixup(dev,hardList);
4919 /* Handle the unlinked files. Since they were left in an unlinked state we should
4923 struct list_head *i;
4924 struct list_head *n;
4927 /* Soft delete all the unlinked files */
4928 list_for_each_safe(i, n,
4929 &dev->unlinkedDir->variant.directoryVariant.
4932 l = list_entry(i, yaffs_Object, siblings);
4933 yaffs_DestroyObject(l);
4938 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4940 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4945 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4948 yaffs_ObjectHeader *oh;
4949 yaffs_Device *dev = in->myDev;
4953 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4955 yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,NULL);
4956 oh = (yaffs_ObjectHeader *) chunkData;
4958 in->yst_mode = oh->yst_mode;
4959 #ifdef CONFIG_YAFFS_WINCE
4960 in->win_atime[0] = oh->win_atime[0];
4961 in->win_ctime[0] = oh->win_ctime[0];
4962 in->win_mtime[0] = oh->win_mtime[0];
4963 in->win_atime[1] = oh->win_atime[1];
4964 in->win_ctime[1] = oh->win_ctime[1];
4965 in->win_mtime[1] = oh->win_mtime[1];
4967 in->yst_uid = oh->yst_uid;
4968 in->yst_gid = oh->yst_gid;
4969 in->yst_atime = oh->yst_atime;
4970 in->yst_mtime = oh->yst_mtime;
4971 in->yst_ctime = oh->yst_ctime;
4972 in->yst_rdev = oh->yst_rdev;
4975 yaffs_SetObjectName(in, oh->name);
4977 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4978 in->variant.symLinkVariant.alias =
4979 yaffs_CloneString(oh->alias);
4981 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
4985 static int yaffs_ScanBackwards(yaffs_Device * dev)
4987 yaffs_ExtendedTags tags;
4992 int nBlocksToScan = 0;
4997 yaffs_BlockState state;
4998 yaffs_Object *hardList = NULL;
4999 yaffs_BlockInfo *bi;
5001 yaffs_ObjectHeader *oh;
5003 yaffs_Object *parent;
5004 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5010 int equivalentObjectId;
5013 yaffs_BlockIndex *blockIndex = NULL;
5014 int altBlockIndex = 0;
5016 if (!dev->isYaffs2) {
5018 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5024 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5025 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5028 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5030 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5033 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5039 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5043 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5045 /* Scan all the blocks to determine their state */
5046 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5047 bi = yaffs_GetBlockInfo(dev, blk);
5048 yaffs_ClearChunkBits(dev, blk);
5050 bi->softDeletions = 0;
5052 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5054 bi->blockState = state;
5055 bi->sequenceNumber = sequenceNumber;
5057 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5058 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5060 T(YAFFS_TRACE_SCAN_DEBUG,
5061 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5062 state, sequenceNumber));
5065 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5066 /* todo .. fix free space ? */
5068 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5069 T(YAFFS_TRACE_BAD_BLOCKS,
5070 (TSTR("block %d is bad" TENDSTR), blk));
5071 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5072 T(YAFFS_TRACE_SCAN_DEBUG,
5073 (TSTR("Block empty " TENDSTR)));
5074 dev->nErasedBlocks++;
5075 dev->nFreeChunks += dev->nChunksPerBlock;
5076 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5078 /* Determine the highest sequence number */
5079 if (dev->isYaffs2 &&
5080 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5081 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5083 blockIndex[nBlocksToScan].seq = sequenceNumber;
5084 blockIndex[nBlocksToScan].block = blk;
5088 if (sequenceNumber >= dev->sequenceNumber) {
5089 dev->sequenceNumber = sequenceNumber;
5091 } else if (dev->isYaffs2) {
5092 /* TODO: Nasty sequence number! */
5095 ("Block scanning block %d has bad sequence number %d"
5096 TENDSTR), blk, sequenceNumber));
5103 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5109 /* Sort the blocks */
5110 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5112 /* Use qsort now. */
5113 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5117 /* Dungy old bubble sort... */
5119 yaffs_BlockIndex temp;
5123 for (i = 0; i < nBlocksToScan; i++)
5124 for (j = i + 1; j < nBlocksToScan; j++)
5125 if (blockIndex[i].seq > blockIndex[j].seq) {
5126 temp = blockIndex[j];
5127 blockIndex[j] = blockIndex[i];
5128 blockIndex[i] = temp;
5135 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5137 /* Now scan the blocks looking at the data. */
5139 endIterator = nBlocksToScan - 1;
5140 T(YAFFS_TRACE_SCAN_DEBUG,
5141 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5143 /* For each block.... backwards */
5144 for (blockIterator = endIterator; blockIterator >= startIterator;
5146 /* Cooperative multitasking! This loop can run for so
5147 long that watchdog timers expire. */
5150 /* get the block to scan in the correct order */
5151 blk = blockIndex[blockIterator].block;
5153 bi = yaffs_GetBlockInfo(dev, blk);
5154 state = bi->blockState;
5158 /* For each chunk in each block that needs scanning.... */
5159 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5160 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5161 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5162 /* Scan backwards...
5163 * Read the tags and decide what to do
5165 chunk = blk * dev->nChunksPerBlock + c;
5167 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5170 /* Let's have a good look at this chunk... */
5172 if (!tags.chunkUsed) {
5173 // An unassigned chunk in the block
5174 // This means that either the block is empty or
5175 // this is the one being allocated from
5178 /* We're looking at the first chunk in the block so the block is unused */
5179 state = YAFFS_BLOCK_STATE_EMPTY;
5180 dev->nErasedBlocks++;
5182 /* this is the block being allocated from */
5184 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5187 (" Allocating from %d %d"
5190 state = YAFFS_BLOCK_STATE_ALLOCATING;
5191 dev->allocationBlock = blk;
5192 dev->allocationPage = c;
5193 dev->allocationBlockFinder = blk;
5194 /* Set it to here to encourage the allocator to
5195 * go forth from here.
5198 /* Yaffs2 sanity check:
5199 * This should be the one with the highest sequence number
5202 && (dev->sequenceNumber !=
5203 bi->sequenceNumber)) {
5204 T(YAFFS_TRACE_ALWAYS,
5206 ("yaffs: Allocation block %d was not highest sequence "
5207 "id: block seq = %d, dev seq = %d"
5210 dev->sequenceNumber));
5215 } else if (tags.chunkId > 0) {
5216 /* chunkId > 0 so it is a data chunk... */
5217 unsigned int endpos;
5220 (tags.chunkId - 1) * dev->nBytesPerChunk;
5222 yaffs_SetChunkBit(dev, blk, c);
5225 in = yaffs_FindOrCreateObjectByNumber(dev,
5228 YAFFS_OBJECT_TYPE_FILE);
5229 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5231 in->variant.fileVariant.shrinkSize) {
5232 /* This has not been invalidated by a resize */
5233 yaffs_PutChunkIntoFile(in, tags.chunkId,
5236 /* File size is calculated by looking at the data chunks if we have not
5237 * seen an object header yet. Stop this practice once we find an object header.
5241 1) * dev->nBytesPerChunk +
5244 if (!in->valid && /* have not got an object header yet */
5245 in->variant.fileVariant.
5246 scannedFileSize < endpos) {
5247 in->variant.fileVariant.
5248 scannedFileSize = endpos;
5249 in->variant.fileVariant.
5251 in->variant.fileVariant.
5256 /* This chunk has been invalidated by a resize, so delete */
5257 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5261 /* chunkId == 0, so it is an ObjectHeader.
5262 * Thus, we read in the object header and make the object
5264 yaffs_SetChunkBit(dev, blk, c);
5270 if (tags.extraHeaderInfoAvailable) {
5271 in = yaffs_FindOrCreateObjectByNumber
5272 (dev, tags.objectId,
5273 tags.extraObjectType);
5277 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5280 tags.extraShadows ||
5282 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5283 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5286 /* If we don't have valid info then we need to read the chunk
5287 * TODO In future we can probably defer reading the chunk and
5288 * living with invalid data until needed.
5291 yaffs_ReadChunkWithTagsFromNAND(dev,
5296 oh = (yaffs_ObjectHeader *) chunkData;
5299 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5304 /* TODO Hoosterman we have a problem! */
5305 T(YAFFS_TRACE_ERROR,
5307 ("yaffs tragedy: Could not make object for object %d "
5308 "at chunk %d during scan"
5309 TENDSTR), tags.objectId, chunk));
5314 /* We have already filled this one.
5315 * We have a duplicate that will be discarded, but
5316 * we first have to suck out resize info if it is a file.
5319 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5321 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5322 (tags.extraHeaderInfoAvailable &&
5323 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5326 (oh) ? oh->fileSize : tags.
5328 __u32 parentObjectId =
5330 parentObjectId : tags.
5331 extraParentObjectId;
5333 (oh) ? oh->isShrink : tags.
5334 extraIsShrinkHeader;
5336 /* If it is deleted (unlinked at start also means deleted)
5337 * we treat the file size as being zeroed at this point.
5339 if (parentObjectId ==
5340 YAFFS_OBJECTID_DELETED
5341 || parentObjectId ==
5342 YAFFS_OBJECTID_UNLINKED) {
5348 in->variant.fileVariant.
5349 shrinkSize > thisSize) {
5350 in->variant.fileVariant.
5356 bi->hasShrinkHeader = 1;
5360 /* Use existing - destroy this one. */
5361 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5366 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5368 YAFFS_OBJECTID_LOSTNFOUND)) {
5369 /* We only load some info, don't fiddle with directory structure */
5373 in->variantType = oh->type;
5375 in->yst_mode = oh->yst_mode;
5376 #ifdef CONFIG_YAFFS_WINCE
5377 in->win_atime[0] = oh->win_atime[0];
5378 in->win_ctime[0] = oh->win_ctime[0];
5379 in->win_mtime[0] = oh->win_mtime[0];
5380 in->win_atime[1] = oh->win_atime[1];
5381 in->win_ctime[1] = oh->win_ctime[1];
5382 in->win_mtime[1] = oh->win_mtime[1];
5384 in->yst_uid = oh->yst_uid;
5385 in->yst_gid = oh->yst_gid;
5386 in->yst_atime = oh->yst_atime;
5387 in->yst_mtime = oh->yst_mtime;
5388 in->yst_ctime = oh->yst_ctime;
5389 in->yst_rdev = oh->yst_rdev;
5393 in->variantType = tags.extraObjectType;
5397 in->chunkId = chunk;
5399 } else if (!in->valid) {
5400 /* we need to load this info */
5403 in->chunkId = chunk;
5406 in->variantType = oh->type;
5408 in->yst_mode = oh->yst_mode;
5409 #ifdef CONFIG_YAFFS_WINCE
5410 in->win_atime[0] = oh->win_atime[0];
5411 in->win_ctime[0] = oh->win_ctime[0];
5412 in->win_mtime[0] = oh->win_mtime[0];
5413 in->win_atime[1] = oh->win_atime[1];
5414 in->win_ctime[1] = oh->win_ctime[1];
5415 in->win_mtime[1] = oh->win_mtime[1];
5417 in->yst_uid = oh->yst_uid;
5418 in->yst_gid = oh->yst_gid;
5419 in->yst_atime = oh->yst_atime;
5420 in->yst_mtime = oh->yst_mtime;
5421 in->yst_ctime = oh->yst_ctime;
5422 in->yst_rdev = oh->yst_rdev;
5425 if (oh->shadowsObject > 0)
5426 yaffs_HandleShadowedObject(dev,
5432 yaffs_SetObjectName(in, oh->name);
5434 yaffs_FindOrCreateObjectByNumber
5435 (dev, oh->parentObjectId,
5436 YAFFS_OBJECT_TYPE_DIRECTORY);
5438 fileSize = oh->fileSize;
5439 isShrink = oh->isShrink;
5440 equivalentObjectId = oh->equivalentObjectId;
5444 in->variantType = tags.extraObjectType;
5446 yaffs_FindOrCreateObjectByNumber
5447 (dev, tags.extraParentObjectId,
5448 YAFFS_OBJECT_TYPE_DIRECTORY);
5449 fileSize = tags.extraFileLength;
5450 isShrink = tags.extraIsShrinkHeader;
5451 equivalentObjectId = tags.extraEquivalentObjectId;
5457 /* directory stuff...
5461 if (parent->variantType ==
5462 YAFFS_OBJECT_TYPE_UNKNOWN) {
5463 /* Set up as a directory */
5464 parent->variantType =
5465 YAFFS_OBJECT_TYPE_DIRECTORY;
5466 INIT_LIST_HEAD(&parent->variant.
5469 } else if (parent->variantType !=
5470 YAFFS_OBJECT_TYPE_DIRECTORY)
5472 /* Hoosterman, another problem....
5473 * We're trying to use a non-directory as a directory
5476 T(YAFFS_TRACE_ERROR,
5478 ("yaffs tragedy: attempting to use non-directory as"
5479 " a directory in scan. Put in lost+found."
5481 parent = dev->lostNFoundDir;
5484 yaffs_AddObjectToDirectory(parent, in);
5486 itsUnlinked = (parent == dev->deletedDir) ||
5487 (parent == dev->unlinkedDir);
5490 /* Mark the block as having a shrinkHeader */
5491 bi->hasShrinkHeader = 1;
5494 /* Note re hardlinks.
5495 * Since we might scan a hardlink before its equivalent object is scanned
5496 * we put them all in a list.
5497 * After scanning is complete, we should have all the objects, so we run
5498 * through this list and fix up all the chains.
5501 switch (in->variantType) {
5502 case YAFFS_OBJECT_TYPE_UNKNOWN:
5503 /* Todo got a problem */
5505 case YAFFS_OBJECT_TYPE_FILE:
5507 if (in->variant.fileVariant.
5508 scannedFileSize < fileSize) {
5509 /* This covers the case where the file size is greater
5510 * than where the data is
5511 * This will happen if the file is resized to be larger
5512 * than its current data extents.
5514 in->variant.fileVariant.fileSize = fileSize;
5515 in->variant.fileVariant.scannedFileSize =
5516 in->variant.fileVariant.fileSize;
5520 in->variant.fileVariant.shrinkSize > fileSize) {
5521 in->variant.fileVariant.shrinkSize = fileSize;
5525 case YAFFS_OBJECT_TYPE_HARDLINK:
5527 in->variant.hardLinkVariant.equivalentObjectId =
5529 in->hardLinks.next =
5530 (struct list_head *) hardList;
5534 case YAFFS_OBJECT_TYPE_DIRECTORY:
5537 case YAFFS_OBJECT_TYPE_SPECIAL:
5540 case YAFFS_OBJECT_TYPE_SYMLINK:
5542 in->variant.symLinkVariant.alias =
5543 yaffs_CloneString(oh->
5552 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5553 /* If we got this far while scanning, then the block is fully allocated. */
5554 state = YAFFS_BLOCK_STATE_FULL;
5557 bi->blockState = state;
5559 /* Now let's see if it was dirty */
5560 if (bi->pagesInUse == 0 &&
5561 !bi->hasShrinkHeader &&
5562 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5563 yaffs_BlockBecameDirty(dev, blk);
5569 YFREE_ALT(blockIndex);
5573 /* Ok, we've done all the scanning.
5574 * Fix up the hard link chains.
5575 * We should now have scanned all the objects, now it's time to add these
5578 yaffs_HardlinkFixup(dev,hardList);
5582 * Sort out state of unlinked and deleted objects.
5585 struct list_head *i;
5586 struct list_head *n;
5590 /* Soft delete all the unlinked files */
5591 list_for_each_safe(i, n,
5592 &dev->unlinkedDir->variant.directoryVariant.
5595 l = list_entry(i, yaffs_Object, siblings);
5596 yaffs_DestroyObject(l);
5600 /* Soft delete all the deletedDir files */
5601 list_for_each_safe(i, n,
5602 &dev->deletedDir->variant.directoryVariant.
5605 l = list_entry(i, yaffs_Object, siblings);
5606 yaffs_DestroyObject(l);
5612 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5614 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5619 /*------------------------------ Directory Functions ----------------------------- */
5621 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5623 yaffs_Device *dev = obj->myDev;
5625 if(dev && dev->removeObjectCallback)
5626 dev->removeObjectCallback(obj);
5628 list_del_init(&obj->siblings);
5633 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5638 T(YAFFS_TRACE_ALWAYS,
5640 ("tragedy: Trying to add an object to a null pointer directory"
5644 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5645 T(YAFFS_TRACE_ALWAYS,
5647 ("tragedy: Trying to add an object to a non-directory"
5652 if (obj->siblings.prev == NULL) {
5653 /* Not initialised */
5654 INIT_LIST_HEAD(&obj->siblings);
5656 } else if (!list_empty(&obj->siblings)) {
5657 /* If it is holed up somewhere else, un hook it */
5658 yaffs_RemoveObjectFromDirectory(obj);
5661 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5662 obj->parent = directory;
5664 if (directory == obj->myDev->unlinkedDir
5665 || directory == obj->myDev->deletedDir) {
5667 obj->myDev->nUnlinkedFiles++;
5668 obj->renameAllowed = 0;
5672 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5677 struct list_head *i;
5678 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5687 T(YAFFS_TRACE_ALWAYS,
5689 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5693 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5694 T(YAFFS_TRACE_ALWAYS,
5696 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5700 sum = yaffs_CalcNameSum(name);
5702 list_for_each(i, &directory->variant.directoryVariant.children) {
5704 l = list_entry(i, yaffs_Object, siblings);
5706 yaffs_CheckObjectDetailsLoaded(l);
5708 /* Special case for lost-n-found */
5709 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5710 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5713 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5715 /* LostnFound cunk called Objxxx
5718 yaffs_GetObjectName(l, buffer,
5719 YAFFS_MAX_NAME_LENGTH);
5720 if (yaffs_strcmp(name, buffer) == 0) {
5733 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5734 int (*fn) (yaffs_Object *))
5736 struct list_head *i;
5740 T(YAFFS_TRACE_ALWAYS,
5742 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5746 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5747 T(YAFFS_TRACE_ALWAYS,
5749 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5753 list_for_each(i, &theDir->variant.directoryVariant.children) {
5755 l = list_entry(i, yaffs_Object, siblings);
5767 /* GetEquivalentObject dereferences any hard links to get to the
5771 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5773 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5774 /* We want the object id of the equivalent object, not this one */
5775 obj = obj->variant.hardLinkVariant.equivalentObject;
5781 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5783 memset(name, 0, buffSize * sizeof(YCHAR));
5785 yaffs_CheckObjectDetailsLoaded(obj);
5787 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5788 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5789 } else if (obj->chunkId <= 0) {
5791 /* make up a name */
5792 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5794 yaffs_strncpy(name, locName, buffSize - 1);
5797 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5798 else if (obj->shortName[0]) {
5799 yaffs_strcpy(name, obj->shortName);
5803 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5805 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5807 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5809 if (obj->chunkId >= 0) {
5810 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5811 obj->chunkId, buffer,
5814 yaffs_strncpy(name, oh->name, buffSize - 1);
5816 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5819 return yaffs_strlen(name);
5822 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5825 /* Dereference any hard linking */
5826 obj = yaffs_GetEquivalentObject(obj);
5828 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5829 return obj->variant.fileVariant.fileSize;
5831 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5832 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5834 /* Only a directory should drop through to here */
5835 return obj->myDev->nBytesPerChunk;
5839 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5842 struct list_head *i;
5844 if (!obj->unlinked) {
5845 count++; /* the object itself */
5847 list_for_each(i, &obj->hardLinks) {
5848 count++; /* add the hard links; */
5854 int yaffs_GetObjectInode(yaffs_Object * obj)
5856 obj = yaffs_GetEquivalentObject(obj);
5858 return obj->objectId;
5861 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5863 obj = yaffs_GetEquivalentObject(obj);
5865 switch (obj->variantType) {
5866 case YAFFS_OBJECT_TYPE_FILE:
5869 case YAFFS_OBJECT_TYPE_DIRECTORY:
5872 case YAFFS_OBJECT_TYPE_SYMLINK:
5875 case YAFFS_OBJECT_TYPE_HARDLINK:
5878 case YAFFS_OBJECT_TYPE_SPECIAL:
5879 if (S_ISFIFO(obj->yst_mode))
5881 if (S_ISCHR(obj->yst_mode))
5883 if (S_ISBLK(obj->yst_mode))
5885 if (S_ISSOCK(obj->yst_mode))
5893 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5895 obj = yaffs_GetEquivalentObject(obj);
5896 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5897 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5899 return yaffs_CloneString(_Y(""));
5903 #ifndef CONFIG_YAFFS_WINCE
5905 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5907 unsigned int valid = attr->ia_valid;
5909 if (valid & ATTR_MODE)
5910 obj->yst_mode = attr->ia_mode;
5911 if (valid & ATTR_UID)
5912 obj->yst_uid = attr->ia_uid;
5913 if (valid & ATTR_GID)
5914 obj->yst_gid = attr->ia_gid;
5916 if (valid & ATTR_ATIME)
5917 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5918 if (valid & ATTR_CTIME)
5919 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5920 if (valid & ATTR_MTIME)
5921 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5923 if (valid & ATTR_SIZE)
5924 yaffs_ResizeFile(obj, attr->ia_size);
5926 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5931 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5933 unsigned int valid = 0;
5935 attr->ia_mode = obj->yst_mode;
5937 attr->ia_uid = obj->yst_uid;
5939 attr->ia_gid = obj->yst_gid;
5942 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5943 valid |= ATTR_ATIME;
5944 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5945 valid |= ATTR_CTIME;
5946 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5947 valid |= ATTR_MTIME;
5949 attr->ia_size = yaffs_GetFileSize(obj);
5952 attr->ia_valid = valid;
5961 int yaffs_DumpObject(yaffs_Object * obj)
5965 yaffs_GetObjectName(obj, name, 256);
5967 T(YAFFS_TRACE_ALWAYS,
5969 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5970 " chunk %d type %d size %d\n"
5971 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5972 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5973 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5979 /*---------------------------- Initialisation code -------------------------------------- */
5981 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5984 /* Common functions, gotta have */
5985 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5988 #ifdef CONFIG_YAFFS_YAFFS2
5990 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5991 if (dev->writeChunkWithTagsToNAND &&
5992 dev->readChunkWithTagsFromNAND &&
5993 !dev->writeChunkToNAND &&
5994 !dev->readChunkFromNAND &&
5995 dev->markNANDBlockBad && dev->queryNANDBlock)
5999 /* Can use the "spare" style interface for yaffs1 */
6000 if (!dev->isYaffs2 &&
6001 !dev->writeChunkWithTagsToNAND &&
6002 !dev->readChunkWithTagsFromNAND &&
6003 dev->writeChunkToNAND &&
6004 dev->readChunkFromNAND &&
6005 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6012 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6014 /* Initialise the unlinked, deleted, root and lost and found directories */
6016 dev->lostNFoundDir = dev->rootDir = NULL;
6017 dev->unlinkedDir = dev->deletedDir = NULL;
6020 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6022 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6025 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6026 YAFFS_ROOT_MODE | S_IFDIR);
6027 dev->lostNFoundDir =
6028 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6029 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6030 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6033 int yaffs_GutsInitialise(yaffs_Device * dev)
6039 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6041 /* Check stuff that must be set */
6044 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6048 dev->internalStartBlock = dev->startBlock;
6049 dev->internalEndBlock = dev->endBlock;
6050 dev->blockOffset = 0;
6051 dev->chunkOffset = 0;
6052 dev->nFreeChunks = 0;
6054 if (dev->startBlock == 0) {
6055 dev->internalStartBlock = dev->startBlock + 1;
6056 dev->internalEndBlock = dev->endBlock + 1;
6057 dev->blockOffset = 1;
6058 dev->chunkOffset = dev->nChunksPerBlock;
6061 /* Check geometry parameters. */
6063 if ((dev->isYaffs2 && dev->nBytesPerChunk < 1024) ||
6064 (!dev->isYaffs2 && dev->nBytesPerChunk != 512) ||
6065 dev->nChunksPerBlock < 2 ||
6066 dev->nReservedBlocks < 2 ||
6067 dev->internalStartBlock <= 0 ||
6068 dev->internalEndBlock <= 0 ||
6069 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6071 T(YAFFS_TRACE_ALWAYS,
6073 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6074 TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6078 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6079 T(YAFFS_TRACE_ALWAYS,
6080 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6084 /* Got the right mix of functions? */
6085 if (!yaffs_CheckDevFunctions(dev)) {
6086 /* Function missing */
6087 T(YAFFS_TRACE_ALWAYS,
6089 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6094 /* This is really a compilation check. */
6095 if (!yaffs_CheckStructures()) {
6096 T(YAFFS_TRACE_ALWAYS,
6097 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6101 if (dev->isMounted) {
6102 T(YAFFS_TRACE_ALWAYS,
6103 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6107 /* Finished with most checks. One or two more checks happen later on too. */
6113 /* OK now calculate a few things for the device
6114 * Calculate chunkGroupBits.
6115 * We need to find the next power of 2 > than internalEndBlock
6118 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6120 for (bits = extraBits = 0; x > 1; bits++) {
6129 /* Set up tnode width if wide tnodes are enabled. */
6130 if(!dev->wideTnodesDisabled){
6131 /* bits must be even so that we end up with 32-bit words */
6135 dev->tnodeWidth = 16;
6137 dev->tnodeWidth = bits;
6140 dev->tnodeWidth = 16;
6142 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6144 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6145 * so if the bitwidth of the
6146 * chunk range we're using is greater than 16 we need
6147 * to figure out chunk shift and chunkGroupSize
6150 if (bits <= dev->tnodeWidth)
6151 dev->chunkGroupBits = 0;
6153 dev->chunkGroupBits = bits - dev->tnodeWidth;
6156 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6158 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6159 /* We have a problem because the soft delete won't work if
6160 * the chunk group size > chunks per block.
6161 * This can be remedied by using larger "virtual blocks".
6163 T(YAFFS_TRACE_ALWAYS,
6164 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6169 /* OK, we've finished verifying the device, lets continue with initialisation */
6171 /* More device initialisation */
6172 dev->garbageCollections = 0;
6173 dev->passiveGarbageCollections = 0;
6174 dev->currentDirtyChecker = 0;
6175 dev->bufferedBlock = -1;
6176 dev->doingBufferedBlockRewrite = 0;
6177 dev->nDeletedFiles = 0;
6178 dev->nBackgroundDeletions = 0;
6179 dev->nUnlinkedFiles = 0;
6181 dev->eccUnfixed = 0;
6182 dev->tagsEccFixed = 0;
6183 dev->tagsEccUnfixed = 0;
6184 dev->nErasureFailures = 0;
6185 dev->nErasedBlocks = 0;
6188 /* Initialise temporary buffers and caches. */
6191 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6192 dev->tempBuffer[i].line = 0; /* not in use */
6193 dev->tempBuffer[i].buffer =
6194 YMALLOC_DMA(dev->nBytesPerChunk);
6198 if (dev->nShortOpCaches > 0) {
6201 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6202 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6206 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6208 for (i = 0; i < dev->nShortOpCaches; i++) {
6209 dev->srCache[i].object = NULL;
6210 dev->srCache[i].lastUse = 0;
6211 dev->srCache[i].dirty = 0;
6212 dev->srCache[i].data = YMALLOC_DMA(dev->nBytesPerChunk);
6219 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6221 if (dev->isYaffs2) {
6222 dev->useHeaderFileSize = 1;
6225 yaffs_InitialiseBlocks(dev);
6226 yaffs_InitialiseTnodes(dev);
6227 yaffs_InitialiseObjects(dev);
6229 yaffs_CreateInitialDirectories(dev);
6232 /* Now scan the flash. */
6233 if (dev->isYaffs2) {
6234 if(yaffs_CheckpointRestore(dev)) {
6235 T(YAFFS_TRACE_ALWAYS,
6236 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6239 /* Clean up the mess caused by an aborted checkpoint load
6240 * and scan backwards.
6242 yaffs_DeinitialiseBlocks(dev);
6243 yaffs_DeinitialiseTnodes(dev);
6244 yaffs_DeinitialiseObjects(dev);
6245 yaffs_InitialiseBlocks(dev);
6246 yaffs_InitialiseTnodes(dev);
6247 yaffs_InitialiseObjects(dev);
6248 yaffs_CreateInitialDirectories(dev);
6250 yaffs_ScanBackwards(dev);
6255 /* Zero out stats */
6256 dev->nPageReads = 0;
6257 dev->nPageWrites = 0;
6258 dev->nBlockErasures = 0;
6260 dev->nRetriedWrites = 0;
6262 dev->nRetiredBlocks = 0;
6264 yaffs_VerifyFreeChunks(dev);
6266 T(YAFFS_TRACE_TRACING,
6267 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6272 void yaffs_Deinitialise(yaffs_Device * dev)
6274 if (dev->isMounted) {
6277 yaffs_DeinitialiseBlocks(dev);
6278 yaffs_DeinitialiseTnodes(dev);
6279 yaffs_DeinitialiseObjects(dev);
6280 if (dev->nShortOpCaches > 0) {
6282 for (i = 0; i < dev->nShortOpCaches; i++) {
6283 YFREE(dev->srCache[i].data);
6286 YFREE(dev->srCache);
6289 YFREE(dev->gcCleanupList);
6291 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6292 YFREE(dev->tempBuffer[i].buffer);
6300 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6305 yaffs_BlockInfo *blk;
6307 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6309 blk = yaffs_GetBlockInfo(dev, b);
6311 switch (blk->blockState) {
6312 case YAFFS_BLOCK_STATE_EMPTY:
6313 case YAFFS_BLOCK_STATE_ALLOCATING:
6314 case YAFFS_BLOCK_STATE_COLLECTING:
6315 case YAFFS_BLOCK_STATE_FULL:
6317 (dev->nChunksPerBlock - blk->pagesInUse +
6318 blk->softDeletions);
6329 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6331 /* This is what we report to the outside world */
6334 int nDirtyCacheChunks;
6335 int blocksForCheckpoint;
6338 nFree = dev->nFreeChunks;
6340 nFree = yaffs_CountFreeChunks(dev);
6343 nFree += dev->nDeletedFiles;
6345 /* Now count the number of dirty chunks in the cache and subtract those */
6349 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6350 if (dev->srCache[i].dirty)
6351 nDirtyCacheChunks++;
6355 nFree -= nDirtyCacheChunks;
6357 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6359 /* Now we figure out how much to reserve for the checkpoint and report that... */
6360 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6361 if(blocksForCheckpoint < 0)
6362 blocksForCheckpoint = 0;
6364 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6373 static int yaffs_freeVerificationFailures;
6375 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6377 int counted = yaffs_CountFreeChunks(dev);
6379 int difference = dev->nFreeChunks - counted;
6382 T(YAFFS_TRACE_ALWAYS,
6383 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6384 dev->nFreeChunks, counted, difference));
6385 yaffs_freeVerificationFailures++;
6389 /*---------------------------------------- YAFFS test code ----------------------*/
6391 #define yaffs_CheckStruct(structure,syze, name) \
6392 if(sizeof(structure) != syze) \
6394 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6395 name,syze,sizeof(structure))); \
6396 return YAFFS_FAIL; \
6399 static int yaffs_CheckStructures(void)
6401 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6402 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6403 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6404 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6405 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6407 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")