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.34 2006-05-21 09:39:12 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 /* printf("Read object %d type %d\n",cp.objectId,cp.variantType); */
3572 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3574 yaffs_CheckpointObjectToObject(obj,&cp);
3575 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3576 ok = yaffs_ReadCheckpointTnodes(obj);
3577 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3578 obj->hardLinks.next =
3579 (struct list_head *)
3589 yaffs_HardlinkFixup(dev,hardList);
3594 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3599 ok = yaffs_CheckpointOpen(dev,1);
3602 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3604 ok = yaffs_WriteCheckpointDevice(dev);
3606 ok = yaffs_WriteCheckpointObjects(dev);
3608 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3610 if(!yaffs_CheckpointClose(dev))
3614 dev->isCheckpointed = 1;
3616 dev->isCheckpointed = 0;
3618 return dev->isCheckpointed;
3621 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3625 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3628 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3630 ok = yaffs_ReadCheckpointDevice(dev);
3632 ok = yaffs_ReadCheckpointObjects(dev);
3634 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3638 if(!yaffs_CheckpointClose(dev))
3642 dev->isCheckpointed = 1;
3644 dev->isCheckpointed = 0;
3650 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3652 if(dev->isCheckpointed ||
3653 dev->blocksInCheckpoint > 0){
3654 dev->isCheckpointed = 0;
3655 yaffs_CheckpointInvalidateStream(dev);
3656 if(dev->superBlock && dev->markSuperBlockDirty)
3657 dev->markSuperBlockDirty(dev->superBlock);
3662 int yaffs_CheckpointSave(yaffs_Device *dev)
3664 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3666 if(!dev->isCheckpointed)
3667 yaffs_WriteCheckpointData(dev);
3669 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3671 return dev->isCheckpointed;
3674 int yaffs_CheckpointRestore(yaffs_Device *dev)
3677 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3679 retval = yaffs_ReadCheckpointData(dev);
3681 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3686 /*--------------------- File read/write ------------------------
3687 * Read and write have very similar structures.
3688 * In general the read/write has three parts to it
3689 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3690 * Some complete chunks
3691 * An incomplete chunk to end off with
3693 * Curve-balls: the first chunk might also be the last chunk.
3696 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3705 yaffs_ChunkCache *cache;
3712 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3713 start = offset % dev->nBytesPerChunk;
3715 /* OK now check for the curveball where the start and end are in
3718 if ((start + n) < dev->nBytesPerChunk) {
3721 nToCopy = dev->nBytesPerChunk - start;
3724 cache = yaffs_FindChunkCache(in, chunk);
3726 /* If the chunk is already in the cache or it is less than a whole chunk
3727 * then use the cache (if there is caching)
3728 * else bypass the cache.
3730 if (cache || nToCopy != dev->nBytesPerChunk) {
3731 if (dev->nShortOpCaches > 0) {
3733 /* If we can't find the data in the cache, then load it up. */
3736 cache = yaffs_GrabChunkCache(in->myDev);
3738 cache->chunkId = chunk;
3741 yaffs_ReadChunkDataFromObject(in, chunk,
3747 yaffs_UseChunkCache(dev, cache, 0);
3751 #ifdef CONFIG_YAFFS_WINCE
3752 yfsd_UnlockYAFFS(TRUE);
3754 memcpy(buffer, &cache->data[start], nToCopy);
3756 #ifdef CONFIG_YAFFS_WINCE
3757 yfsd_LockYAFFS(TRUE);
3761 /* Read into the local buffer then copy..*/
3764 yaffs_GetTempBuffer(dev, __LINE__);
3765 yaffs_ReadChunkDataFromObject(in, chunk,
3767 #ifdef CONFIG_YAFFS_WINCE
3768 yfsd_UnlockYAFFS(TRUE);
3770 memcpy(buffer, &localBuffer[start], nToCopy);
3772 #ifdef CONFIG_YAFFS_WINCE
3773 yfsd_LockYAFFS(TRUE);
3775 yaffs_ReleaseTempBuffer(dev, localBuffer,
3780 #ifdef CONFIG_YAFFS_WINCE
3781 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3783 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3784 * This is because we otherwise screw up WinCE's memory mapper
3786 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3788 #ifdef CONFIG_YAFFS_WINCE
3789 yfsd_UnlockYAFFS(TRUE);
3791 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3793 #ifdef CONFIG_YAFFS_WINCE
3794 yfsd_LockYAFFS(TRUE);
3795 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3799 /* A full chunk. Read directly into the supplied buffer. */
3800 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3814 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3815 int nBytes, int writeThrough)
3824 int startOfWrite = offset;
3825 int chunkWritten = 0;
3832 while (n > 0 && chunkWritten >= 0) {
3833 chunk = offset / dev->nBytesPerChunk + 1;
3834 start = offset % dev->nBytesPerChunk;
3836 /* OK now check for the curveball where the start and end are in
3840 if ((start + n) < dev->nBytesPerChunk) {
3843 /* Now folks, to calculate how many bytes to write back....
3844 * If we're overwriting and not writing to then end of file then
3845 * we need to write back as much as was there before.
3849 in->variant.fileVariant.fileSize -
3850 ((chunk - 1) * dev->nBytesPerChunk);
3852 if (nBytesRead > dev->nBytesPerChunk) {
3853 nBytesRead = dev->nBytesPerChunk;
3858 (start + n)) ? nBytesRead : (start + n);
3861 nToCopy = dev->nBytesPerChunk - start;
3862 nToWriteBack = dev->nBytesPerChunk;
3865 if (nToCopy != dev->nBytesPerChunk) {
3866 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3867 if (dev->nShortOpCaches > 0) {
3868 yaffs_ChunkCache *cache;
3869 /* If we can't find the data in the cache, then load the cache */
3870 cache = yaffs_FindChunkCache(in, chunk);
3873 && yaffs_CheckSpaceForAllocation(in->
3875 cache = yaffs_GrabChunkCache(in->myDev);
3877 cache->chunkId = chunk;
3880 yaffs_ReadChunkDataFromObject(in, chunk,
3886 !yaffs_CheckSpaceForAllocation(in->myDev)){
3887 /* Drop the cache if it was a read cache item and
3888 * no space check has been made for it.
3894 yaffs_UseChunkCache(dev, cache, 1);
3896 #ifdef CONFIG_YAFFS_WINCE
3897 yfsd_UnlockYAFFS(TRUE);
3900 memcpy(&cache->data[start], buffer,
3903 #ifdef CONFIG_YAFFS_WINCE
3904 yfsd_LockYAFFS(TRUE);
3907 cache->nBytes = nToWriteBack;
3911 yaffs_WriteChunkDataToObject
3914 cache->data, cache->nBytes,
3920 chunkWritten = -1; /* fail the write */
3923 /* An incomplete start or end chunk (or maybe both start and end chunk)
3924 * Read into the local buffer then copy, then copy over and write back.
3928 yaffs_GetTempBuffer(dev, __LINE__);
3930 yaffs_ReadChunkDataFromObject(in, chunk,
3933 #ifdef CONFIG_YAFFS_WINCE
3934 yfsd_UnlockYAFFS(TRUE);
3937 memcpy(&localBuffer[start], buffer, nToCopy);
3939 #ifdef CONFIG_YAFFS_WINCE
3940 yfsd_LockYAFFS(TRUE);
3943 yaffs_WriteChunkDataToObject(in, chunk,
3948 yaffs_ReleaseTempBuffer(dev, localBuffer,
3955 #ifdef CONFIG_YAFFS_WINCE
3956 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3957 * This is because we otherwise screw up WinCE's memory mapper
3959 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3960 #ifdef CONFIG_YAFFS_WINCE
3961 yfsd_UnlockYAFFS(TRUE);
3963 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3964 #ifdef CONFIG_YAFFS_WINCE
3965 yfsd_LockYAFFS(TRUE);
3968 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3969 dev->nBytesPerChunk,
3971 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3973 /* A full chunk. Write directly from the supplied buffer. */
3975 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3976 dev->nBytesPerChunk,
3979 /* Since we've overwritten the cached data, we better invalidate it. */
3980 yaffs_InvalidateChunkCache(in, chunk);
3983 if (chunkWritten >= 0) {
3992 /* Update file object */
3994 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3995 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4004 /* ---------------------- File resizing stuff ------------------ */
4006 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4009 yaffs_Device *dev = in->myDev;
4010 int oldFileSize = in->variant.fileVariant.fileSize;
4012 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
4014 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
4015 dev->nBytesPerChunk;
4019 /* Delete backwards so that we don't end up with holes if
4020 * power is lost part-way through the operation.
4022 for (i = lastDel; i >= startDel; i--) {
4023 /* NB this could be optimised somewhat,
4024 * eg. could retrieve the tags and write them without
4025 * using yaffs_DeleteChunk
4028 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4031 (dev->internalStartBlock * dev->nChunksPerBlock)
4033 ((dev->internalEndBlock +
4034 1) * dev->nChunksPerBlock)) {
4035 T(YAFFS_TRACE_ALWAYS,
4036 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4040 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4047 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
4050 int oldFileSize = in->variant.fileVariant.fileSize;
4051 int sizeOfPartialChunk;
4052 yaffs_Device *dev = in->myDev;
4054 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
4056 yaffs_FlushFilesChunkCache(in);
4057 yaffs_InvalidateWholeChunkCache(in);
4059 yaffs_CheckGarbageCollection(dev);
4061 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4062 return yaffs_GetFileSize(in);
4065 if (newSize == oldFileSize) {
4069 if (newSize < oldFileSize) {
4071 yaffs_PruneResizedChunks(in, newSize);
4073 if (sizeOfPartialChunk != 0) {
4074 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
4075 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4077 /* Got to read and rewrite the last chunk with its new size and zero pad */
4078 yaffs_ReadChunkDataFromObject(in, lastChunk,
4081 memset(localBuffer + sizeOfPartialChunk, 0,
4082 dev->nBytesPerChunk - sizeOfPartialChunk);
4084 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4085 sizeOfPartialChunk, 1);
4087 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4090 in->variant.fileVariant.fileSize = newSize;
4092 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4094 /* Write a new object header.
4095 * show we've shrunk the file, if need be
4096 * Do this only if the file is not in the deleted directories.
4098 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4099 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4100 yaffs_UpdateObjectHeader(in, NULL, 0,
4101 (newSize < oldFileSize) ? 1 : 0, 0);
4107 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4109 obj = yaffs_GetEquivalentObject(obj);
4111 switch (obj->variantType) {
4112 case YAFFS_OBJECT_TYPE_FILE:
4113 return obj->variant.fileVariant.fileSize;
4114 case YAFFS_OBJECT_TYPE_SYMLINK:
4115 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4123 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4127 yaffs_FlushFilesChunkCache(in);
4129 #ifdef CONFIG_YAFFS_WINCE
4130 yfsd_WinFileTimeNow(in->win_mtime);
4133 in->yst_mtime = Y_CURRENT_TIME;
4139 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4140 0) ? YAFFS_OK : YAFFS_FAIL;
4149 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4152 /* First off, invalidate the file's data in the cache, without flushing. */
4153 yaffs_InvalidateWholeChunkCache(in);
4155 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4156 /* Move to the unlinked directory so we have a record that it was deleted. */
4157 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4161 yaffs_RemoveObjectFromDirectory(in);
4162 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4165 yaffs_FreeObject(in);
4170 /* yaffs_DeleteFile deletes the whole file data
4171 * and the inode associated with the file.
4172 * It does not delete the links associated with the file.
4174 static int yaffs_UnlinkFile(yaffs_Object * in)
4178 int immediateDeletion = 0;
4183 immediateDeletion = 1;
4187 if (in->inUse <= 0) {
4188 immediateDeletion = 1;
4192 if (immediateDeletion) {
4194 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4196 T(YAFFS_TRACE_TRACING,
4197 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4200 in->myDev->nDeletedFiles++;
4201 if (0 && in->myDev->isYaffs2) {
4202 yaffs_ResizeFile(in, 0);
4204 yaffs_SoftDeleteFile(in);
4207 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4215 int yaffs_DeleteFile(yaffs_Object * in)
4217 int retVal = YAFFS_OK;
4219 if (in->nDataChunks > 0) {
4220 /* Use soft deletion if there is data in the file */
4221 if (!in->unlinked) {
4222 retVal = yaffs_UnlinkFile(in);
4224 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4226 in->myDev->nDeletedFiles++;
4227 yaffs_SoftDeleteFile(in);
4229 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4231 /* The file has no data chunks so we toss it immediately */
4232 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4233 in->variant.fileVariant.top = NULL;
4234 yaffs_DoGenericObjectDeletion(in);
4240 static int yaffs_DeleteDirectory(yaffs_Object * in)
4242 /* First check that the directory is empty. */
4243 if (list_empty(&in->variant.directoryVariant.children)) {
4244 return yaffs_DoGenericObjectDeletion(in);
4251 static int yaffs_DeleteSymLink(yaffs_Object * in)
4253 YFREE(in->variant.symLinkVariant.alias);
4255 return yaffs_DoGenericObjectDeletion(in);
4258 static int yaffs_DeleteHardLink(yaffs_Object * in)
4260 /* remove this hardlink from the list assocaited with the equivalent
4263 list_del(&in->hardLinks);
4264 return yaffs_DoGenericObjectDeletion(in);
4267 static void yaffs_DestroyObject(yaffs_Object * obj)
4269 switch (obj->variantType) {
4270 case YAFFS_OBJECT_TYPE_FILE:
4271 yaffs_DeleteFile(obj);
4273 case YAFFS_OBJECT_TYPE_DIRECTORY:
4274 yaffs_DeleteDirectory(obj);
4276 case YAFFS_OBJECT_TYPE_SYMLINK:
4277 yaffs_DeleteSymLink(obj);
4279 case YAFFS_OBJECT_TYPE_HARDLINK:
4280 yaffs_DeleteHardLink(obj);
4282 case YAFFS_OBJECT_TYPE_SPECIAL:
4283 yaffs_DoGenericObjectDeletion(obj);
4285 case YAFFS_OBJECT_TYPE_UNKNOWN:
4286 break; /* should not happen. */
4290 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4293 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4294 return yaffs_DeleteHardLink(obj);
4295 } else if (!list_empty(&obj->hardLinks)) {
4296 /* Curve ball: We're unlinking an object that has a hardlink.
4298 * This problem arises because we are not strictly following
4299 * The Linux link/inode model.
4301 * We can't really delete the object.
4302 * Instead, we do the following:
4303 * - Select a hardlink.
4304 * - Unhook it from the hard links
4305 * - Unhook it from its parent directory (so that the rename can work)
4306 * - Rename the object to the hardlink's name.
4307 * - Delete the hardlink
4312 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4314 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4316 list_del_init(&hl->hardLinks);
4317 list_del_init(&hl->siblings);
4319 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4321 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4323 if (retVal == YAFFS_OK) {
4324 retVal = yaffs_DoGenericObjectDeletion(hl);
4329 switch (obj->variantType) {
4330 case YAFFS_OBJECT_TYPE_FILE:
4331 return yaffs_UnlinkFile(obj);
4333 case YAFFS_OBJECT_TYPE_DIRECTORY:
4334 return yaffs_DeleteDirectory(obj);
4336 case YAFFS_OBJECT_TYPE_SYMLINK:
4337 return yaffs_DeleteSymLink(obj);
4339 case YAFFS_OBJECT_TYPE_SPECIAL:
4340 return yaffs_DoGenericObjectDeletion(obj);
4342 case YAFFS_OBJECT_TYPE_HARDLINK:
4343 case YAFFS_OBJECT_TYPE_UNKNOWN:
4351 static int yaffs_UnlinkObject( yaffs_Object *obj)
4354 if (obj && obj->unlinkAllowed) {
4355 return yaffs_UnlinkWorker(obj);
4361 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4365 obj = yaffs_FindObjectByName(dir, name);
4366 return yaffs_UnlinkObject(obj);
4369 /*----------------------- Initialisation Scanning ---------------------- */
4371 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4372 int backwardScanning)
4376 if (!backwardScanning) {
4377 /* Handle YAFFS1 forward scanning case
4378 * For YAFFS1 we always do the deletion
4382 /* Handle YAFFS2 case (backward scanning)
4383 * If the shadowed object exists then ignore.
4385 if (yaffs_FindObjectByNumber(dev, objId)) {
4390 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4391 * We put it in unlinked dir to be cleaned up after the scanning
4394 yaffs_FindOrCreateObjectByNumber(dev, objId,
4395 YAFFS_OBJECT_TYPE_FILE);
4396 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4397 obj->variant.fileVariant.shrinkSize = 0;
4398 obj->valid = 1; /* So that we don't read any other info for this file */
4408 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4415 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4417 in = yaffs_FindObjectByNumber(dev,
4418 hl->variant.hardLinkVariant.
4419 equivalentObjectId);
4422 /* Add the hardlink pointers */
4423 hl->variant.hardLinkVariant.equivalentObject = in;
4424 list_add(&hl->hardLinks, &in->hardLinks);
4426 /* Todo Need to report/handle this better.
4427 * Got a problem... hardlink to a non-existant object
4429 hl->variant.hardLinkVariant.equivalentObject = NULL;
4430 INIT_LIST_HEAD(&hl->hardLinks);
4442 static int ybicmp(const void *a, const void *b){
4443 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4444 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4445 register int ablock = ((yaffs_BlockIndex *)a)->block;
4446 register int bblock = ((yaffs_BlockIndex *)b)->block;
4448 return ablock - bblock;
4454 static int yaffs_Scan(yaffs_Device * dev)
4456 yaffs_ExtendedTags tags;
4461 int nBlocksToScan = 0;
4466 yaffs_BlockState state;
4467 yaffs_Object *hardList = NULL;
4469 yaffs_BlockInfo *bi;
4471 yaffs_ObjectHeader *oh;
4473 yaffs_Object *parent;
4474 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4478 yaffs_BlockIndex *blockIndex = NULL;
4481 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4482 dev->internalStartBlock, dev->internalEndBlock));
4484 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4486 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4488 if (dev->isYaffs2) {
4489 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4492 /* Scan all the blocks to determine their state */
4493 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4494 bi = yaffs_GetBlockInfo(dev, blk);
4495 yaffs_ClearChunkBits(dev, blk);
4497 bi->softDeletions = 0;
4499 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4501 bi->blockState = state;
4502 bi->sequenceNumber = sequenceNumber;
4504 T(YAFFS_TRACE_SCAN_DEBUG,
4505 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4506 state, sequenceNumber));
4508 if (state == YAFFS_BLOCK_STATE_DEAD) {
4509 T(YAFFS_TRACE_BAD_BLOCKS,
4510 (TSTR("block %d is bad" TENDSTR), blk));
4511 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4512 T(YAFFS_TRACE_SCAN_DEBUG,
4513 (TSTR("Block empty " TENDSTR)));
4514 dev->nErasedBlocks++;
4515 dev->nFreeChunks += dev->nChunksPerBlock;
4516 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4518 /* Determine the highest sequence number */
4519 if (dev->isYaffs2 &&
4520 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4521 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4523 blockIndex[nBlocksToScan].seq = sequenceNumber;
4524 blockIndex[nBlocksToScan].block = blk;
4528 if (sequenceNumber >= dev->sequenceNumber) {
4529 dev->sequenceNumber = sequenceNumber;
4531 } else if (dev->isYaffs2) {
4532 /* TODO: Nasty sequence number! */
4535 ("Block scanning block %d has bad sequence number %d"
4536 TENDSTR), blk, sequenceNumber));
4543 * Dungy old bubble sort for now...
4545 if (dev->isYaffs2) {
4546 yaffs_BlockIndex temp;
4550 for (i = 0; i < nBlocksToScan; i++)
4551 for (j = i + 1; j < nBlocksToScan; j++)
4552 if (blockIndex[i].seq > blockIndex[j].seq) {
4553 temp = blockIndex[j];
4554 blockIndex[j] = blockIndex[i];
4555 blockIndex[i] = temp;
4559 /* Now scan the blocks looking at the data. */
4560 if (dev->isYaffs2) {
4562 endIterator = nBlocksToScan - 1;
4563 T(YAFFS_TRACE_SCAN_DEBUG,
4564 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4566 startIterator = dev->internalStartBlock;
4567 endIterator = dev->internalEndBlock;
4570 /* For each block.... */
4571 for (blockIterator = startIterator; blockIterator <= endIterator;
4574 if (dev->isYaffs2) {
4575 /* get the block to scan in the correct order */
4576 blk = blockIndex[blockIterator].block;
4578 blk = blockIterator;
4581 bi = yaffs_GetBlockInfo(dev, blk);
4582 state = bi->blockState;
4586 /* For each chunk in each block that needs scanning....*/
4587 for (c = 0; c < dev->nChunksPerBlock &&
4588 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4589 /* Read the tags and decide what to do */
4590 chunk = blk * dev->nChunksPerBlock + c;
4592 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4595 /* Let's have a good look at this chunk... */
4597 if (!dev->isYaffs2 && tags.chunkDeleted) {
4603 /*T((" %d %d deleted\n",blk,c)); */
4604 } else if (!tags.chunkUsed) {
4605 /* An unassigned chunk in the block
4606 * This means that either the block is empty or
4607 * this is the one being allocated from
4611 /* We're looking at the first chunk in the block so the block is unused */
4612 state = YAFFS_BLOCK_STATE_EMPTY;
4613 dev->nErasedBlocks++;
4615 /* this is the block being allocated from */
4618 (" Allocating from %d %d" TENDSTR),
4620 state = YAFFS_BLOCK_STATE_ALLOCATING;
4621 dev->allocationBlock = blk;
4622 dev->allocationPage = c;
4623 dev->allocationBlockFinder = blk;
4624 /* Set it to here to encourage the allocator to go forth from here. */
4626 /* Yaffs2 sanity check:
4627 * This should be the one with the highest sequence number
4630 && (dev->sequenceNumber !=
4631 bi->sequenceNumber)) {
4632 T(YAFFS_TRACE_ALWAYS,
4634 ("yaffs: Allocation block %d was not highest sequence id:"
4635 " block seq = %d, dev seq = %d"
4636 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4640 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4641 } else if (tags.chunkId > 0) {
4642 /* chunkId > 0 so it is a data chunk... */
4643 unsigned int endpos;
4645 yaffs_SetChunkBit(dev, blk, c);
4648 in = yaffs_FindOrCreateObjectByNumber(dev,
4651 YAFFS_OBJECT_TYPE_FILE);
4652 /* PutChunkIntoFile checks for a clash (two data chunks with
4653 * the same chunkId).
4655 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4658 (tags.chunkId - 1) * dev->nBytesPerChunk +
4660 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4661 && in->variant.fileVariant.scannedFileSize <
4663 in->variant.fileVariant.
4664 scannedFileSize = endpos;
4665 if (!dev->useHeaderFileSize) {
4666 in->variant.fileVariant.
4668 in->variant.fileVariant.
4673 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4675 /* chunkId == 0, so it is an ObjectHeader.
4676 * Thus, we read in the object header and make the object
4678 yaffs_SetChunkBit(dev, blk, c);
4681 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4685 oh = (yaffs_ObjectHeader *) chunkData;
4687 in = yaffs_FindObjectByNumber(dev,
4689 if (in && in->variantType != oh->type) {
4690 /* This should not happen, but somehow
4691 * Wev'e ended up with an objectId that has been reused but not yet
4692 * deleted, and worse still it has changed type. Delete the old object.
4695 yaffs_DestroyObject(in);
4700 in = yaffs_FindOrCreateObjectByNumber(dev,
4705 if (oh->shadowsObject > 0) {
4706 yaffs_HandleShadowedObject(dev,
4713 /* We have already filled this one. We have a duplicate and need to resolve it. */
4715 unsigned existingSerial = in->serial;
4716 unsigned newSerial = tags.serialNumber;
4718 if (dev->isYaffs2 ||
4719 ((existingSerial + 1) & 3) ==
4721 /* Use new one - destroy the exisiting one */
4722 yaffs_DeleteChunk(dev,
4727 /* Use existing - destroy this one. */
4728 yaffs_DeleteChunk(dev, chunk, 1,
4734 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4735 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4736 /* We only load some info, don't fiddle with directory structure */
4738 in->variantType = oh->type;
4740 in->yst_mode = oh->yst_mode;
4741 #ifdef CONFIG_YAFFS_WINCE
4742 in->win_atime[0] = oh->win_atime[0];
4743 in->win_ctime[0] = oh->win_ctime[0];
4744 in->win_mtime[0] = oh->win_mtime[0];
4745 in->win_atime[1] = oh->win_atime[1];
4746 in->win_ctime[1] = oh->win_ctime[1];
4747 in->win_mtime[1] = oh->win_mtime[1];
4749 in->yst_uid = oh->yst_uid;
4750 in->yst_gid = oh->yst_gid;
4751 in->yst_atime = oh->yst_atime;
4752 in->yst_mtime = oh->yst_mtime;
4753 in->yst_ctime = oh->yst_ctime;
4754 in->yst_rdev = oh->yst_rdev;
4756 in->chunkId = chunk;
4758 } else if (!in->valid) {
4759 /* we need to load this info */
4762 in->variantType = oh->type;
4764 in->yst_mode = oh->yst_mode;
4765 #ifdef CONFIG_YAFFS_WINCE
4766 in->win_atime[0] = oh->win_atime[0];
4767 in->win_ctime[0] = oh->win_ctime[0];
4768 in->win_mtime[0] = oh->win_mtime[0];
4769 in->win_atime[1] = oh->win_atime[1];
4770 in->win_ctime[1] = oh->win_ctime[1];
4771 in->win_mtime[1] = oh->win_mtime[1];
4773 in->yst_uid = oh->yst_uid;
4774 in->yst_gid = oh->yst_gid;
4775 in->yst_atime = oh->yst_atime;
4776 in->yst_mtime = oh->yst_mtime;
4777 in->yst_ctime = oh->yst_ctime;
4778 in->yst_rdev = oh->yst_rdev;
4780 in->chunkId = chunk;
4782 yaffs_SetObjectName(in, oh->name);
4785 /* directory stuff...
4790 yaffs_FindOrCreateObjectByNumber
4791 (dev, oh->parentObjectId,
4792 YAFFS_OBJECT_TYPE_DIRECTORY);
4793 if (parent->variantType ==
4794 YAFFS_OBJECT_TYPE_UNKNOWN) {
4795 /* Set up as a directory */
4796 parent->variantType =
4797 YAFFS_OBJECT_TYPE_DIRECTORY;
4798 INIT_LIST_HEAD(&parent->variant.
4801 } else if (parent->variantType !=
4802 YAFFS_OBJECT_TYPE_DIRECTORY)
4804 /* Hoosterman, another problem....
4805 * We're trying to use a non-directory as a directory
4808 T(YAFFS_TRACE_ERROR,
4810 ("yaffs tragedy: attempting to use non-directory as"
4811 " a directory in scan. Put in lost+found."
4813 parent = dev->lostNFoundDir;
4816 yaffs_AddObjectToDirectory(parent, in);
4818 if (0 && (parent == dev->deletedDir ||
4819 parent == dev->unlinkedDir)) {
4820 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
4821 dev->nDeletedFiles++;
4823 /* Note re hardlinks.
4824 * Since we might scan a hardlink before its equivalent object is scanned
4825 * we put them all in a list.
4826 * After scanning is complete, we should have all the objects, so we run through this
4827 * list and fix up all the chains.
4830 switch (in->variantType) {
4831 case YAFFS_OBJECT_TYPE_UNKNOWN:
4832 /* Todo got a problem */
4834 case YAFFS_OBJECT_TYPE_FILE:
4837 /* Prune back the shrunken chunks */
4838 yaffs_PruneResizedChunks
4840 /* Mark the block as having a shrinkHeader */
4841 bi->hasShrinkHeader = 1;
4844 if (dev->useHeaderFileSize)
4846 in->variant.fileVariant.
4851 case YAFFS_OBJECT_TYPE_HARDLINK:
4852 in->variant.hardLinkVariant.
4853 equivalentObjectId =
4854 oh->equivalentObjectId;
4855 in->hardLinks.next =
4856 (struct list_head *)
4860 case YAFFS_OBJECT_TYPE_DIRECTORY:
4863 case YAFFS_OBJECT_TYPE_SPECIAL:
4866 case YAFFS_OBJECT_TYPE_SYMLINK:
4867 in->variant.symLinkVariant.
4869 yaffs_CloneString(oh->alias);
4873 if (parent == dev->deletedDir) {
4874 yaffs_DestroyObject(in);
4875 bi->hasShrinkHeader = 1;
4881 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4882 /* If we got this far while scanning, then the block is fully allocated.*/
4883 state = YAFFS_BLOCK_STATE_FULL;
4886 bi->blockState = state;
4888 /* Now let's see if it was dirty */
4889 if (bi->pagesInUse == 0 &&
4890 !bi->hasShrinkHeader &&
4891 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4892 yaffs_BlockBecameDirty(dev, blk);
4902 /* Ok, we've done all the scanning.
4903 * Fix up the hard link chains.
4904 * We should now have scanned all the objects, now it's time to add these
4908 yaffs_HardlinkFixup(dev,hardList);
4910 /* Handle the unlinked files. Since they were left in an unlinked state we should
4914 struct list_head *i;
4915 struct list_head *n;
4918 /* Soft delete all the unlinked files */
4919 list_for_each_safe(i, n,
4920 &dev->unlinkedDir->variant.directoryVariant.
4923 l = list_entry(i, yaffs_Object, siblings);
4924 yaffs_DestroyObject(l);
4929 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4931 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4936 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4939 yaffs_ObjectHeader *oh;
4940 yaffs_Device *dev = in->myDev;
4944 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4946 yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,NULL);
4947 oh = (yaffs_ObjectHeader *) chunkData;
4949 in->yst_mode = oh->yst_mode;
4950 #ifdef CONFIG_YAFFS_WINCE
4951 in->win_atime[0] = oh->win_atime[0];
4952 in->win_ctime[0] = oh->win_ctime[0];
4953 in->win_mtime[0] = oh->win_mtime[0];
4954 in->win_atime[1] = oh->win_atime[1];
4955 in->win_ctime[1] = oh->win_ctime[1];
4956 in->win_mtime[1] = oh->win_mtime[1];
4958 in->yst_uid = oh->yst_uid;
4959 in->yst_gid = oh->yst_gid;
4960 in->yst_atime = oh->yst_atime;
4961 in->yst_mtime = oh->yst_mtime;
4962 in->yst_ctime = oh->yst_ctime;
4963 in->yst_rdev = oh->yst_rdev;
4966 yaffs_SetObjectName(in, oh->name);
4968 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4969 in->variant.symLinkVariant.alias =
4970 yaffs_CloneString(oh->alias);
4972 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
4976 static int yaffs_ScanBackwards(yaffs_Device * dev)
4978 yaffs_ExtendedTags tags;
4983 int nBlocksToScan = 0;
4988 yaffs_BlockState state;
4989 yaffs_Object *hardList = NULL;
4990 yaffs_BlockInfo *bi;
4992 yaffs_ObjectHeader *oh;
4994 yaffs_Object *parent;
4995 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5001 int equivalentObjectId;
5004 yaffs_BlockIndex *blockIndex = NULL;
5006 if (!dev->isYaffs2) {
5008 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5014 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5015 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5017 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5019 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5021 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5023 /* Scan all the blocks to determine their state */
5024 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5025 bi = yaffs_GetBlockInfo(dev, blk);
5026 yaffs_ClearChunkBits(dev, blk);
5028 bi->softDeletions = 0;
5030 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5032 bi->blockState = state;
5033 bi->sequenceNumber = sequenceNumber;
5035 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5036 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5038 T(YAFFS_TRACE_SCAN_DEBUG,
5039 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5040 state, sequenceNumber));
5043 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5044 /* todo .. fix free space ? */
5046 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5047 T(YAFFS_TRACE_BAD_BLOCKS,
5048 (TSTR("block %d is bad" TENDSTR), blk));
5049 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5050 T(YAFFS_TRACE_SCAN_DEBUG,
5051 (TSTR("Block empty " TENDSTR)));
5052 dev->nErasedBlocks++;
5053 dev->nFreeChunks += dev->nChunksPerBlock;
5054 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5056 /* Determine the highest sequence number */
5057 if (dev->isYaffs2 &&
5058 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5059 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5061 blockIndex[nBlocksToScan].seq = sequenceNumber;
5062 blockIndex[nBlocksToScan].block = blk;
5066 if (sequenceNumber >= dev->sequenceNumber) {
5067 dev->sequenceNumber = sequenceNumber;
5069 } else if (dev->isYaffs2) {
5070 /* TODO: Nasty sequence number! */
5073 ("Block scanning block %d has bad sequence number %d"
5074 TENDSTR), blk, sequenceNumber));
5081 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5087 /* Sort the blocks */
5088 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5090 /* Use qsort now. */
5091 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5095 /* Dungy old bubble sort... */
5097 yaffs_BlockIndex temp;
5101 for (i = 0; i < nBlocksToScan; i++)
5102 for (j = i + 1; j < nBlocksToScan; j++)
5103 if (blockIndex[i].seq > blockIndex[j].seq) {
5104 temp = blockIndex[j];
5105 blockIndex[j] = blockIndex[i];
5106 blockIndex[i] = temp;
5113 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5115 /* Now scan the blocks looking at the data. */
5117 endIterator = nBlocksToScan - 1;
5118 T(YAFFS_TRACE_SCAN_DEBUG,
5119 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5121 /* For each block.... backwards */
5122 for (blockIterator = endIterator; blockIterator >= startIterator;
5124 /* Cooperative multitasking! This loop can run for so
5125 long that watchdog timers expire. */
5128 /* get the block to scan in the correct order */
5129 blk = blockIndex[blockIterator].block;
5131 bi = yaffs_GetBlockInfo(dev, blk);
5132 state = bi->blockState;
5136 /* For each chunk in each block that needs scanning.... */
5137 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5138 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5139 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5140 /* Scan backwards...
5141 * Read the tags and decide what to do
5143 chunk = blk * dev->nChunksPerBlock + c;
5145 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5148 /* Let's have a good look at this chunk... */
5150 if (!tags.chunkUsed) {
5151 // An unassigned chunk in the block
5152 // This means that either the block is empty or
5153 // this is the one being allocated from
5156 /* We're looking at the first chunk in the block so the block is unused */
5157 state = YAFFS_BLOCK_STATE_EMPTY;
5158 dev->nErasedBlocks++;
5160 /* this is the block being allocated from */
5162 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5165 (" Allocating from %d %d"
5168 state = YAFFS_BLOCK_STATE_ALLOCATING;
5169 dev->allocationBlock = blk;
5170 dev->allocationPage = c;
5171 dev->allocationBlockFinder = blk;
5172 /* Set it to here to encourage the allocator to
5173 * go forth from here.
5176 /* Yaffs2 sanity check:
5177 * This should be the one with the highest sequence number
5180 && (dev->sequenceNumber !=
5181 bi->sequenceNumber)) {
5182 T(YAFFS_TRACE_ALWAYS,
5184 ("yaffs: Allocation block %d was not highest sequence "
5185 "id: block seq = %d, dev seq = %d"
5188 dev->sequenceNumber));
5193 } else if (tags.chunkId > 0) {
5194 /* chunkId > 0 so it is a data chunk... */
5195 unsigned int endpos;
5198 (tags.chunkId - 1) * dev->nBytesPerChunk;
5200 yaffs_SetChunkBit(dev, blk, c);
5203 in = yaffs_FindOrCreateObjectByNumber(dev,
5206 YAFFS_OBJECT_TYPE_FILE);
5207 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5209 in->variant.fileVariant.shrinkSize) {
5210 /* This has not been invalidated by a resize */
5211 yaffs_PutChunkIntoFile(in, tags.chunkId,
5214 /* File size is calculated by looking at the data chunks if we have not
5215 * seen an object header yet. Stop this practice once we find an object header.
5219 1) * dev->nBytesPerChunk +
5222 if (!in->valid && /* have not got an object header yet */
5223 in->variant.fileVariant.
5224 scannedFileSize < endpos) {
5225 in->variant.fileVariant.
5226 scannedFileSize = endpos;
5227 in->variant.fileVariant.
5229 in->variant.fileVariant.
5234 /* This chunk has been invalidated by a resize, so delete */
5235 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5239 /* chunkId == 0, so it is an ObjectHeader.
5240 * Thus, we read in the object header and make the object
5242 yaffs_SetChunkBit(dev, blk, c);
5248 if (tags.extraHeaderInfoAvailable) {
5249 in = yaffs_FindOrCreateObjectByNumber
5250 (dev, tags.objectId,
5251 tags.extraObjectType);
5255 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5258 tags.extraShadows ||
5260 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5261 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5264 /* If we don't have valid info then we need to read the chunk
5265 * TODO In future we can probably defer reading the chunk and
5266 * living with invalid data until needed.
5269 yaffs_ReadChunkWithTagsFromNAND(dev,
5274 oh = (yaffs_ObjectHeader *) chunkData;
5277 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5282 /* TODO Hoosterman we have a problem! */
5283 T(YAFFS_TRACE_ERROR,
5285 ("yaffs tragedy: Could not make object for object %d "
5286 "at chunk %d during scan"
5287 TENDSTR), tags.objectId, chunk));
5292 /* We have already filled this one.
5293 * We have a duplicate that will be discarded, but
5294 * we first have to suck out resize info if it is a file.
5297 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5299 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5300 (tags.extraHeaderInfoAvailable &&
5301 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5304 (oh) ? oh->fileSize : tags.
5306 __u32 parentObjectId =
5308 parentObjectId : tags.
5309 extraParentObjectId;
5311 (oh) ? oh->isShrink : tags.
5312 extraIsShrinkHeader;
5314 /* If it is deleted (unlinked at start also means deleted)
5315 * we treat the file size as being zeroed at this point.
5317 if (parentObjectId ==
5318 YAFFS_OBJECTID_DELETED
5319 || parentObjectId ==
5320 YAFFS_OBJECTID_UNLINKED) {
5326 in->variant.fileVariant.
5327 shrinkSize > thisSize) {
5328 in->variant.fileVariant.
5334 bi->hasShrinkHeader = 1;
5338 /* Use existing - destroy this one. */
5339 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5344 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5346 YAFFS_OBJECTID_LOSTNFOUND)) {
5347 /* We only load some info, don't fiddle with directory structure */
5351 in->variantType = oh->type;
5353 in->yst_mode = oh->yst_mode;
5354 #ifdef CONFIG_YAFFS_WINCE
5355 in->win_atime[0] = oh->win_atime[0];
5356 in->win_ctime[0] = oh->win_ctime[0];
5357 in->win_mtime[0] = oh->win_mtime[0];
5358 in->win_atime[1] = oh->win_atime[1];
5359 in->win_ctime[1] = oh->win_ctime[1];
5360 in->win_mtime[1] = oh->win_mtime[1];
5362 in->yst_uid = oh->yst_uid;
5363 in->yst_gid = oh->yst_gid;
5364 in->yst_atime = oh->yst_atime;
5365 in->yst_mtime = oh->yst_mtime;
5366 in->yst_ctime = oh->yst_ctime;
5367 in->yst_rdev = oh->yst_rdev;
5371 in->variantType = tags.extraObjectType;
5375 in->chunkId = chunk;
5377 } else if (!in->valid) {
5378 /* we need to load this info */
5381 in->chunkId = chunk;
5384 in->variantType = oh->type;
5386 in->yst_mode = oh->yst_mode;
5387 #ifdef CONFIG_YAFFS_WINCE
5388 in->win_atime[0] = oh->win_atime[0];
5389 in->win_ctime[0] = oh->win_ctime[0];
5390 in->win_mtime[0] = oh->win_mtime[0];
5391 in->win_atime[1] = oh->win_atime[1];
5392 in->win_ctime[1] = oh->win_ctime[1];
5393 in->win_mtime[1] = oh->win_mtime[1];
5395 in->yst_uid = oh->yst_uid;
5396 in->yst_gid = oh->yst_gid;
5397 in->yst_atime = oh->yst_atime;
5398 in->yst_mtime = oh->yst_mtime;
5399 in->yst_ctime = oh->yst_ctime;
5400 in->yst_rdev = oh->yst_rdev;
5403 if (oh->shadowsObject > 0)
5404 yaffs_HandleShadowedObject(dev,
5410 yaffs_SetObjectName(in, oh->name);
5412 yaffs_FindOrCreateObjectByNumber
5413 (dev, oh->parentObjectId,
5414 YAFFS_OBJECT_TYPE_DIRECTORY);
5416 fileSize = oh->fileSize;
5417 isShrink = oh->isShrink;
5418 equivalentObjectId = oh->equivalentObjectId;
5422 in->variantType = tags.extraObjectType;
5424 yaffs_FindOrCreateObjectByNumber
5425 (dev, tags.extraParentObjectId,
5426 YAFFS_OBJECT_TYPE_DIRECTORY);
5427 fileSize = tags.extraFileLength;
5428 isShrink = tags.extraIsShrinkHeader;
5429 equivalentObjectId = tags.extraEquivalentObjectId;
5435 /* directory stuff...
5439 if (parent->variantType ==
5440 YAFFS_OBJECT_TYPE_UNKNOWN) {
5441 /* Set up as a directory */
5442 parent->variantType =
5443 YAFFS_OBJECT_TYPE_DIRECTORY;
5444 INIT_LIST_HEAD(&parent->variant.
5447 } else if (parent->variantType !=
5448 YAFFS_OBJECT_TYPE_DIRECTORY)
5450 /* Hoosterman, another problem....
5451 * We're trying to use a non-directory as a directory
5454 T(YAFFS_TRACE_ERROR,
5456 ("yaffs tragedy: attempting to use non-directory as"
5457 " a directory in scan. Put in lost+found."
5459 parent = dev->lostNFoundDir;
5462 yaffs_AddObjectToDirectory(parent, in);
5464 itsUnlinked = (parent == dev->deletedDir) ||
5465 (parent == dev->unlinkedDir);
5468 /* Mark the block as having a shrinkHeader */
5469 bi->hasShrinkHeader = 1;
5472 /* Note re hardlinks.
5473 * Since we might scan a hardlink before its equivalent object is scanned
5474 * we put them all in a list.
5475 * After scanning is complete, we should have all the objects, so we run
5476 * through this list and fix up all the chains.
5479 switch (in->variantType) {
5480 case YAFFS_OBJECT_TYPE_UNKNOWN:
5481 /* Todo got a problem */
5483 case YAFFS_OBJECT_TYPE_FILE:
5485 if (in->variant.fileVariant.
5486 scannedFileSize < fileSize) {
5487 /* This covers the case where the file size is greater
5488 * than where the data is
5489 * This will happen if the file is resized to be larger
5490 * than its current data extents.
5492 in->variant.fileVariant.fileSize = fileSize;
5493 in->variant.fileVariant.scannedFileSize =
5494 in->variant.fileVariant.fileSize;
5498 in->variant.fileVariant.shrinkSize > fileSize) {
5499 in->variant.fileVariant.shrinkSize = fileSize;
5503 case YAFFS_OBJECT_TYPE_HARDLINK:
5505 in->variant.hardLinkVariant.equivalentObjectId =
5507 in->hardLinks.next =
5508 (struct list_head *) hardList;
5512 case YAFFS_OBJECT_TYPE_DIRECTORY:
5515 case YAFFS_OBJECT_TYPE_SPECIAL:
5518 case YAFFS_OBJECT_TYPE_SYMLINK:
5520 in->variant.symLinkVariant.alias =
5521 yaffs_CloneString(oh->
5530 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5531 /* If we got this far while scanning, then the block is fully allocated. */
5532 state = YAFFS_BLOCK_STATE_FULL;
5535 bi->blockState = state;
5537 /* Now let's see if it was dirty */
5538 if (bi->pagesInUse == 0 &&
5539 !bi->hasShrinkHeader &&
5540 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5541 yaffs_BlockBecameDirty(dev, blk);
5549 /* Ok, we've done all the scanning.
5550 * Fix up the hard link chains.
5551 * We should now have scanned all the objects, now it's time to add these
5554 yaffs_HardlinkFixup(dev,hardList);
5558 * Sort out state of unlinked and deleted objects.
5561 struct list_head *i;
5562 struct list_head *n;
5566 /* Soft delete all the unlinked files */
5567 list_for_each_safe(i, n,
5568 &dev->unlinkedDir->variant.directoryVariant.
5571 l = list_entry(i, yaffs_Object, siblings);
5572 yaffs_DestroyObject(l);
5576 /* Soft delete all the deletedDir files */
5577 list_for_each_safe(i, n,
5578 &dev->deletedDir->variant.directoryVariant.
5581 l = list_entry(i, yaffs_Object, siblings);
5582 yaffs_DestroyObject(l);
5588 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5590 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5595 /*------------------------------ Directory Functions ----------------------------- */
5597 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5599 yaffs_Device *dev = obj->myDev;
5601 if(dev && dev->removeObjectCallback)
5602 dev->removeObjectCallback(obj);
5604 list_del_init(&obj->siblings);
5609 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5614 T(YAFFS_TRACE_ALWAYS,
5616 ("tragedy: Trying to add an object to a null pointer directory"
5620 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5621 T(YAFFS_TRACE_ALWAYS,
5623 ("tragedy: Trying to add an object to a non-directory"
5628 if (obj->siblings.prev == NULL) {
5629 /* Not initialised */
5630 INIT_LIST_HEAD(&obj->siblings);
5632 } else if (!list_empty(&obj->siblings)) {
5633 /* If it is holed up somewhere else, un hook it */
5634 yaffs_RemoveObjectFromDirectory(obj);
5637 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5638 obj->parent = directory;
5640 if (directory == obj->myDev->unlinkedDir
5641 || directory == obj->myDev->deletedDir) {
5643 obj->myDev->nUnlinkedFiles++;
5644 obj->renameAllowed = 0;
5648 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5653 struct list_head *i;
5654 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5663 T(YAFFS_TRACE_ALWAYS,
5665 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5669 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5670 T(YAFFS_TRACE_ALWAYS,
5672 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5676 sum = yaffs_CalcNameSum(name);
5678 list_for_each(i, &directory->variant.directoryVariant.children) {
5680 l = list_entry(i, yaffs_Object, siblings);
5682 yaffs_CheckObjectDetailsLoaded(l);
5684 /* Special case for lost-n-found */
5685 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5686 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5689 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5691 /* LostnFound cunk called Objxxx
5694 yaffs_GetObjectName(l, buffer,
5695 YAFFS_MAX_NAME_LENGTH);
5696 if (yaffs_strcmp(name, buffer) == 0) {
5709 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5710 int (*fn) (yaffs_Object *))
5712 struct list_head *i;
5716 T(YAFFS_TRACE_ALWAYS,
5718 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5722 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5723 T(YAFFS_TRACE_ALWAYS,
5725 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5729 list_for_each(i, &theDir->variant.directoryVariant.children) {
5731 l = list_entry(i, yaffs_Object, siblings);
5743 /* GetEquivalentObject dereferences any hard links to get to the
5747 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5749 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5750 /* We want the object id of the equivalent object, not this one */
5751 obj = obj->variant.hardLinkVariant.equivalentObject;
5757 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5759 memset(name, 0, buffSize * sizeof(YCHAR));
5761 yaffs_CheckObjectDetailsLoaded(obj);
5763 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5764 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5765 } else if (obj->chunkId <= 0) {
5767 /* make up a name */
5768 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5770 yaffs_strncpy(name, locName, buffSize - 1);
5773 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5774 else if (obj->shortName[0]) {
5775 yaffs_strcpy(name, obj->shortName);
5779 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5781 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5783 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5785 if (obj->chunkId >= 0) {
5786 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5787 obj->chunkId, buffer,
5790 yaffs_strncpy(name, oh->name, buffSize - 1);
5792 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5795 return yaffs_strlen(name);
5798 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5801 /* Dereference any hard linking */
5802 obj = yaffs_GetEquivalentObject(obj);
5804 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5805 return obj->variant.fileVariant.fileSize;
5807 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5808 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5810 /* Only a directory should drop through to here */
5811 return obj->myDev->nBytesPerChunk;
5815 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5818 struct list_head *i;
5820 if (!obj->unlinked) {
5821 count++; /* the object itself */
5823 list_for_each(i, &obj->hardLinks) {
5824 count++; /* add the hard links; */
5830 int yaffs_GetObjectInode(yaffs_Object * obj)
5832 obj = yaffs_GetEquivalentObject(obj);
5834 return obj->objectId;
5837 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5839 obj = yaffs_GetEquivalentObject(obj);
5841 switch (obj->variantType) {
5842 case YAFFS_OBJECT_TYPE_FILE:
5845 case YAFFS_OBJECT_TYPE_DIRECTORY:
5848 case YAFFS_OBJECT_TYPE_SYMLINK:
5851 case YAFFS_OBJECT_TYPE_HARDLINK:
5854 case YAFFS_OBJECT_TYPE_SPECIAL:
5855 if (S_ISFIFO(obj->yst_mode))
5857 if (S_ISCHR(obj->yst_mode))
5859 if (S_ISBLK(obj->yst_mode))
5861 if (S_ISSOCK(obj->yst_mode))
5869 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5871 obj = yaffs_GetEquivalentObject(obj);
5872 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5873 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5875 return yaffs_CloneString(_Y(""));
5879 #ifndef CONFIG_YAFFS_WINCE
5881 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5883 unsigned int valid = attr->ia_valid;
5885 if (valid & ATTR_MODE)
5886 obj->yst_mode = attr->ia_mode;
5887 if (valid & ATTR_UID)
5888 obj->yst_uid = attr->ia_uid;
5889 if (valid & ATTR_GID)
5890 obj->yst_gid = attr->ia_gid;
5892 if (valid & ATTR_ATIME)
5893 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5894 if (valid & ATTR_CTIME)
5895 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5896 if (valid & ATTR_MTIME)
5897 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5899 if (valid & ATTR_SIZE)
5900 yaffs_ResizeFile(obj, attr->ia_size);
5902 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5907 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5909 unsigned int valid = 0;
5911 attr->ia_mode = obj->yst_mode;
5913 attr->ia_uid = obj->yst_uid;
5915 attr->ia_gid = obj->yst_gid;
5918 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5919 valid |= ATTR_ATIME;
5920 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5921 valid |= ATTR_CTIME;
5922 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5923 valid |= ATTR_MTIME;
5925 attr->ia_size = yaffs_GetFileSize(obj);
5928 attr->ia_valid = valid;
5937 int yaffs_DumpObject(yaffs_Object * obj)
5941 yaffs_GetObjectName(obj, name, 256);
5943 T(YAFFS_TRACE_ALWAYS,
5945 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5946 " chunk %d type %d size %d\n"
5947 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5948 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5949 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5955 /*---------------------------- Initialisation code -------------------------------------- */
5957 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5960 /* Common functions, gotta have */
5961 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5964 #ifdef CONFIG_YAFFS_YAFFS2
5966 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5967 if (dev->writeChunkWithTagsToNAND &&
5968 dev->readChunkWithTagsFromNAND &&
5969 !dev->writeChunkToNAND &&
5970 !dev->readChunkFromNAND &&
5971 dev->markNANDBlockBad && dev->queryNANDBlock)
5975 /* Can use the "spare" style interface for yaffs1 */
5976 if (!dev->isYaffs2 &&
5977 !dev->writeChunkWithTagsToNAND &&
5978 !dev->readChunkWithTagsFromNAND &&
5979 dev->writeChunkToNAND &&
5980 dev->readChunkFromNAND &&
5981 !dev->markNANDBlockBad && !dev->queryNANDBlock)
5988 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
5990 /* Initialise the unlinked, deleted, root and lost and found directories */
5992 dev->lostNFoundDir = dev->rootDir = NULL;
5993 dev->unlinkedDir = dev->deletedDir = NULL;
5996 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5998 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6001 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6002 YAFFS_ROOT_MODE | S_IFDIR);
6003 dev->lostNFoundDir =
6004 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6005 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6006 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6009 int yaffs_GutsInitialise(yaffs_Device * dev)
6015 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6017 /* Check stuff that must be set */
6020 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6024 dev->internalStartBlock = dev->startBlock;
6025 dev->internalEndBlock = dev->endBlock;
6026 dev->blockOffset = 0;
6027 dev->chunkOffset = 0;
6028 dev->nFreeChunks = 0;
6030 if (dev->startBlock == 0) {
6031 dev->internalStartBlock = dev->startBlock + 1;
6032 dev->internalEndBlock = dev->endBlock + 1;
6033 dev->blockOffset = 1;
6034 dev->chunkOffset = dev->nChunksPerBlock;
6037 /* Check geometry parameters. */
6039 if ((dev->isYaffs2 && dev->nBytesPerChunk < 1024) ||
6040 (!dev->isYaffs2 && dev->nBytesPerChunk != 512) ||
6041 dev->nChunksPerBlock < 2 ||
6042 dev->nReservedBlocks < 2 ||
6043 dev->internalStartBlock <= 0 ||
6044 dev->internalEndBlock <= 0 ||
6045 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6047 T(YAFFS_TRACE_ALWAYS,
6049 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6050 TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6054 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6055 T(YAFFS_TRACE_ALWAYS,
6056 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6060 /* Got the right mix of functions? */
6061 if (!yaffs_CheckDevFunctions(dev)) {
6062 /* Function missing */
6063 T(YAFFS_TRACE_ALWAYS,
6065 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6070 /* This is really a compilation check. */
6071 if (!yaffs_CheckStructures()) {
6072 T(YAFFS_TRACE_ALWAYS,
6073 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6077 if (dev->isMounted) {
6078 T(YAFFS_TRACE_ALWAYS,
6079 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6083 /* Finished with most checks. One or two more checks happen later on too. */
6089 /* OK now calculate a few things for the device
6090 * Calculate chunkGroupBits.
6091 * We need to find the next power of 2 > than internalEndBlock
6094 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6096 for (bits = extraBits = 0; x > 1; bits++) {
6105 /* Set up tnode width if wide tnodes are enabled. */
6106 if(!dev->wideTnodesDisabled){
6107 /* bits must be even so that we end up with 32-bit words */
6111 dev->tnodeWidth = 16;
6113 dev->tnodeWidth = bits;
6116 dev->tnodeWidth = 16;
6118 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6120 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6121 * so if the bitwidth of the
6122 * chunk range we're using is greater than 16 we need
6123 * to figure out chunk shift and chunkGroupSize
6126 if (bits <= dev->tnodeWidth)
6127 dev->chunkGroupBits = 0;
6129 dev->chunkGroupBits = bits - dev->tnodeWidth;
6132 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6134 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6135 /* We have a problem because the soft delete won't work if
6136 * the chunk group size > chunks per block.
6137 * This can be remedied by using larger "virtual blocks".
6139 T(YAFFS_TRACE_ALWAYS,
6140 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6145 /* OK, we've finished verifying the device, lets continue with initialisation */
6147 /* More device initialisation */
6148 dev->garbageCollections = 0;
6149 dev->passiveGarbageCollections = 0;
6150 dev->currentDirtyChecker = 0;
6151 dev->bufferedBlock = -1;
6152 dev->doingBufferedBlockRewrite = 0;
6153 dev->nDeletedFiles = 0;
6154 dev->nBackgroundDeletions = 0;
6155 dev->nUnlinkedFiles = 0;
6157 dev->eccUnfixed = 0;
6158 dev->tagsEccFixed = 0;
6159 dev->tagsEccUnfixed = 0;
6160 dev->nErasureFailures = 0;
6161 dev->nErasedBlocks = 0;
6164 /* Initialise temporary buffers and caches. */
6167 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6168 dev->tempBuffer[i].line = 0; /* not in use */
6169 dev->tempBuffer[i].buffer =
6170 YMALLOC_DMA(dev->nBytesPerChunk);
6174 if (dev->nShortOpCaches > 0) {
6177 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6178 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6182 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6184 for (i = 0; i < dev->nShortOpCaches; i++) {
6185 dev->srCache[i].object = NULL;
6186 dev->srCache[i].lastUse = 0;
6187 dev->srCache[i].dirty = 0;
6188 dev->srCache[i].data = YMALLOC_DMA(dev->nBytesPerChunk);
6195 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6197 if (dev->isYaffs2) {
6198 dev->useHeaderFileSize = 1;
6201 yaffs_InitialiseBlocks(dev);
6202 yaffs_InitialiseTnodes(dev);
6203 yaffs_InitialiseObjects(dev);
6205 yaffs_CreateInitialDirectories(dev);
6208 /* Now scan the flash. */
6209 if (dev->isYaffs2) {
6210 if(yaffs_CheckpointRestore(dev)) {
6211 T(YAFFS_TRACE_ALWAYS,
6212 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6215 /* Clean up the mess caused by an aborted checkpoint load
6216 * and scan backwards.
6218 yaffs_DeinitialiseBlocks(dev);
6219 yaffs_DeinitialiseTnodes(dev);
6220 yaffs_DeinitialiseObjects(dev);
6221 yaffs_InitialiseBlocks(dev);
6222 yaffs_InitialiseTnodes(dev);
6223 yaffs_InitialiseObjects(dev);
6224 yaffs_CreateInitialDirectories(dev);
6226 yaffs_ScanBackwards(dev);
6231 /* Zero out stats */
6232 dev->nPageReads = 0;
6233 dev->nPageWrites = 0;
6234 dev->nBlockErasures = 0;
6236 dev->nRetriedWrites = 0;
6238 dev->nRetiredBlocks = 0;
6240 yaffs_VerifyFreeChunks(dev);
6242 T(YAFFS_TRACE_TRACING,
6243 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6248 void yaffs_Deinitialise(yaffs_Device * dev)
6250 if (dev->isMounted) {
6253 yaffs_DeinitialiseBlocks(dev);
6254 yaffs_DeinitialiseTnodes(dev);
6255 yaffs_DeinitialiseObjects(dev);
6256 if (dev->nShortOpCaches > 0) {
6258 for (i = 0; i < dev->nShortOpCaches; i++) {
6259 YFREE(dev->srCache[i].data);
6262 YFREE(dev->srCache);
6265 YFREE(dev->gcCleanupList);
6267 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6268 YFREE(dev->tempBuffer[i].buffer);
6276 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6281 yaffs_BlockInfo *blk;
6283 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6285 blk = yaffs_GetBlockInfo(dev, b);
6287 switch (blk->blockState) {
6288 case YAFFS_BLOCK_STATE_EMPTY:
6289 case YAFFS_BLOCK_STATE_ALLOCATING:
6290 case YAFFS_BLOCK_STATE_COLLECTING:
6291 case YAFFS_BLOCK_STATE_FULL:
6293 (dev->nChunksPerBlock - blk->pagesInUse +
6294 blk->softDeletions);
6305 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6307 /* This is what we report to the outside world */
6310 int nDirtyCacheChunks;
6311 int blocksForCheckpoint;
6314 nFree = dev->nFreeChunks;
6316 nFree = yaffs_CountFreeChunks(dev);
6319 nFree += dev->nDeletedFiles;
6321 /* Now count the number of dirty chunks in the cache and subtract those */
6325 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6326 if (dev->srCache[i].dirty)
6327 nDirtyCacheChunks++;
6331 nFree -= nDirtyCacheChunks;
6333 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6335 /* Now we figure out how much to reserve for the checkpoint and report that... */
6336 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6337 if(blocksForCheckpoint < 0)
6338 blocksForCheckpoint = 0;
6340 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6349 static int yaffs_freeVerificationFailures;
6351 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6353 int counted = yaffs_CountFreeChunks(dev);
6355 int difference = dev->nFreeChunks - counted;
6358 T(YAFFS_TRACE_ALWAYS,
6359 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6360 dev->nFreeChunks, counted, difference));
6361 yaffs_freeVerificationFailures++;
6365 /*---------------------------------------- YAFFS test code ----------------------*/
6367 #define yaffs_CheckStruct(structure,syze, name) \
6368 if(sizeof(structure) != syze) \
6370 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6371 name,syze,sizeof(structure))); \
6372 return YAFFS_FAIL; \
6375 static int yaffs_CheckStructures(void)
6377 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6378 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6379 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6380 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6381 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6383 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")