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.36 2006-09-05 23:23:34 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);
56 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62 yaffs_ExtendedTags * tags,
64 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
65 int chunkInNAND, int inScan);
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
68 yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
72 int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
76 int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
82 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
85 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
88 static int yaffs_UnlinkWorker(yaffs_Object * obj);
89 static void yaffs_DestroyObject(yaffs_Object * obj);
91 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
94 loff_t yaffs_GetFileSize(yaffs_Object * obj);
96 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
98 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
100 #ifdef YAFFS_PARANOID
101 static int yaffs_CheckFileSanity(yaffs_Object * in);
103 #define yaffs_CheckFileSanity(in)
106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
107 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
109 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
112 * Temporary buffer manipulations.
115 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
118 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
119 if (dev->tempBuffer[i].line == 0) {
120 dev->tempBuffer[i].line = lineNo;
121 if ((i + 1) > dev->maxTemp) {
122 dev->maxTemp = i + 1;
123 for (j = 0; j <= i; j++)
124 dev->tempBuffer[j].maxLine =
125 dev->tempBuffer[j].line;
128 return dev->tempBuffer[i].buffer;
132 T(YAFFS_TRACE_BUFFERS,
133 (TSTR("Out of temp buffers at line %d, other held by lines:"),
135 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
136 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
138 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
141 * If we got here then we have to allocate an unmanaged one
145 dev->unmanagedTempAllocations++;
146 return YMALLOC(dev->nBytesPerChunk);
150 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
154 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
155 if (dev->tempBuffer[i].buffer == buffer) {
156 dev->tempBuffer[i].line = 0;
162 /* assume it is an unmanaged one. */
163 T(YAFFS_TRACE_BUFFERS,
164 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
167 dev->unmanagedTempDeallocations++;
173 * Determine if we have a managed buffer.
175 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
178 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
179 if (dev->tempBuffer[i].buffer == buffer)
184 for (i = 0; i < dev->nShortOpCaches; i++) {
185 if( dev->srCache[i].data == buffer )
190 if (buffer == dev->checkpointBuffer)
193 T(YAFFS_TRACE_ALWAYS,
194 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
199 * Chunk bitmap manipulations
202 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
204 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
206 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
210 return dev->chunkBits +
211 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
214 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
216 __u8 *blkBits = yaffs_BlockBits(dev, blk);
218 memset(blkBits, 0, dev->chunkBitmapStride);
221 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
223 __u8 *blkBits = yaffs_BlockBits(dev, blk);
225 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
228 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
230 __u8 *blkBits = yaffs_BlockBits(dev, blk);
232 blkBits[chunk / 8] |= (1 << (chunk & 7));
235 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
237 __u8 *blkBits = yaffs_BlockBits(dev, blk);
238 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
241 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
243 __u8 *blkBits = yaffs_BlockBits(dev, blk);
245 for (i = 0; i < dev->chunkBitmapStride; i++) {
254 * Simple hash function. Needs to have a reasonable spread
257 static Y_INLINE int yaffs_HashFunction(int n)
260 return (n % YAFFS_NOBJECT_BUCKETS);
264 * Access functions to useful fake objects
267 yaffs_Object *yaffs_Root(yaffs_Device * dev)
272 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
274 return dev->lostNFoundDir;
279 * Erased NAND checking functions
282 int yaffs_CheckFF(__u8 * buffer, int nBytes)
284 /* Horrible, slow implementation */
293 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
297 int retval = YAFFS_OK;
298 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
299 yaffs_ExtendedTags tags;
301 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
303 if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
304 T(YAFFS_TRACE_NANDACCESS,
305 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
309 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
315 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
317 yaffs_ExtendedTags * tags,
325 yaffs_InvalidateCheckpoint(dev);
328 chunk = yaffs_AllocateChunk(dev, useReserve);
332 /* First check this chunk is erased... */
333 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
334 writeOk = yaffs_CheckChunkErased(dev, chunk);
339 ("**>> yaffs chunk %d was not erased"
343 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
350 * Copy the data into the robustification buffer.
351 * NB We do this at the end to prevent duplicates in the case of a write error.
354 yaffs_HandleWriteChunkOk(dev, chunk, data,
357 yaffs_HandleWriteChunkError(dev, chunk);
361 } while (chunk >= 0 && !writeOk);
365 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
367 dev->nRetriedWrites += (attempts - 1);
374 * Block retiring for handling a broken block.
377 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
380 yaffs_InvalidateCheckpoint(dev);
382 yaffs_MarkBlockBad(dev, blockInNAND);
384 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
385 YAFFS_BLOCK_STATE_DEAD;
387 dev->nRetiredBlocks++;
391 * Functions for robustisizing TODO
395 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
397 const yaffs_ExtendedTags * tags)
401 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
402 const yaffs_ExtendedTags * tags)
406 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
408 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
410 /* Mark the block for retirement */
411 yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
412 /* Delete the chunk */
413 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
417 /*---------------- Name handling functions ------------*/
419 static __u16 yaffs_CalcNameSum(const YCHAR * name)
424 YUCHAR *bname = (YUCHAR *) name;
426 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
428 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
429 sum += yaffs_toupper(*bname) * i;
440 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
442 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
443 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
444 yaffs_strcpy(obj->shortName, name);
446 obj->shortName[0] = _Y('\0');
449 obj->sum = yaffs_CalcNameSum(name);
452 /*-------------------- TNODES -------------------
454 * List of spare tnodes
455 * The list is hooked together using the first pointer
459 /* yaffs_CreateTnodes creates a bunch more tnodes and
460 * adds them to the tnode free list.
461 * Don't use this function directly
464 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
468 yaffs_Tnode *newTnodes;
472 yaffs_TnodeList *tnl;
477 /* Calculate the tnode size in bytes for variable width tnode support.
478 * Must be a multiple of 32-bits */
479 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
481 /* make these things */
483 newTnodes = YMALLOC(nTnodes * tnodeSize);
484 mem = (__u8 *)newTnodes;
488 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
492 /* Hook them into the free list */
494 for (i = 0; i < nTnodes - 1; i++) {
495 newTnodes[i].internal[0] = &newTnodes[i + 1];
496 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
497 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
501 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
502 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
503 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
505 dev->freeTnodes = newTnodes;
507 /* New hookup for wide tnodes */
508 for(i = 0; i < nTnodes -1; i++) {
509 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
510 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
511 curr->internal[0] = next;
514 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
515 curr->internal[0] = dev->freeTnodes;
516 dev->freeTnodes = (yaffs_Tnode *)mem;
521 dev->nFreeTnodes += nTnodes;
522 dev->nTnodesCreated += nTnodes;
524 /* Now add this bunch of tnodes to a list for freeing up.
525 * NB If we can't add this to the management list it isn't fatal
526 * but it just means we can't free this bunch of tnodes later.
529 tnl = YMALLOC(sizeof(yaffs_TnodeList));
533 ("yaffs: Could not add tnodes to management list" TENDSTR)));
536 tnl->tnodes = newTnodes;
537 tnl->next = dev->allocatedTnodeList;
538 dev->allocatedTnodeList = tnl;
541 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
546 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
548 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
550 yaffs_Tnode *tn = NULL;
552 /* If there are none left make more */
553 if (!dev->freeTnodes) {
554 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
557 if (dev->freeTnodes) {
558 tn = dev->freeTnodes;
559 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
560 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
561 /* Hoosterman, this thing looks like it isn't in the list */
562 T(YAFFS_TRACE_ALWAYS,
563 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
566 dev->freeTnodes = dev->freeTnodes->internal[0];
573 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
575 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
578 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
583 /* FreeTnode frees up a tnode and puts it back on the free list */
584 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
587 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
588 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
589 /* Hoosterman, this thing looks like it is already in the list */
590 T(YAFFS_TRACE_ALWAYS,
591 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
593 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
595 tn->internal[0] = dev->freeTnodes;
596 dev->freeTnodes = tn;
601 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
603 /* Free the list of allocated tnodes */
604 yaffs_TnodeList *tmp;
606 while (dev->allocatedTnodeList) {
607 tmp = dev->allocatedTnodeList->next;
609 YFREE(dev->allocatedTnodeList->tnodes);
610 YFREE(dev->allocatedTnodeList);
611 dev->allocatedTnodeList = tmp;
615 dev->freeTnodes = NULL;
616 dev->nFreeTnodes = 0;
619 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
621 dev->allocatedTnodeList = NULL;
622 dev->freeTnodes = NULL;
623 dev->nFreeTnodes = 0;
624 dev->nTnodesCreated = 0;
629 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
631 __u32 *map = (__u32 *)tn;
637 pos &= YAFFS_TNODES_LEVEL0_MASK;
638 val >>= dev->chunkGroupBits;
640 bitInMap = pos * dev->tnodeWidth;
641 wordInMap = bitInMap /32;
642 bitInWord = bitInMap & (32 -1);
644 mask = dev->tnodeMask << bitInWord;
646 map[wordInMap] &= ~mask;
647 map[wordInMap] |= (mask & (val << bitInWord));
649 if(dev->tnodeWidth > (32-bitInWord)) {
650 bitInWord = (32 - bitInWord);
652 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
653 map[wordInMap] &= ~mask;
654 map[wordInMap] |= (mask & (val >> bitInWord));
658 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
660 __u32 *map = (__u32 *)tn;
666 pos &= YAFFS_TNODES_LEVEL0_MASK;
668 bitInMap = pos * dev->tnodeWidth;
669 wordInMap = bitInMap /32;
670 bitInWord = bitInMap & (32 -1);
672 val = map[wordInMap] >> bitInWord;
674 if(dev->tnodeWidth > (32-bitInWord)) {
675 bitInWord = (32 - bitInWord);
677 val |= (map[wordInMap] << bitInWord);
680 val &= dev->tnodeMask;
681 val <<= dev->chunkGroupBits;
686 /* ------------------- End of individual tnode manipulation -----------------*/
688 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
689 * The look up tree is represented by the top tnode and the number of topLevel
690 * in the tree. 0 means only the level 0 tnode is in the tree.
693 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
694 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
695 yaffs_FileStructure * fStruct,
699 yaffs_Tnode *tn = fStruct->top;
701 int requiredTallness;
702 int level = fStruct->topLevel;
704 /* Check sane level and chunk Id */
705 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
709 if (chunkId > YAFFS_MAX_CHUNK_ID) {
713 /* First check we're tall enough (ie enough topLevel) */
715 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
716 requiredTallness = 0;
718 i >>= YAFFS_TNODES_INTERNAL_BITS;
722 if (requiredTallness > fStruct->topLevel) {
723 /* Not tall enough, so we can't find it, return NULL. */
727 /* Traverse down to level 0 */
728 while (level > 0 && tn) {
731 ( YAFFS_TNODES_LEVEL0_BITS +
733 YAFFS_TNODES_INTERNAL_BITS)
735 YAFFS_TNODES_INTERNAL_MASK];
743 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
744 * This happens in two steps:
745 * 1. If the tree isn't tall enough, then make it taller.
746 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
748 * Used when modifying the tree.
750 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
751 * be plugged into the ttree.
754 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
755 yaffs_FileStructure * fStruct,
757 yaffs_Tnode *passedTn)
760 int requiredTallness;
768 /* Check sane level and page Id */
769 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
773 if (chunkId > YAFFS_MAX_CHUNK_ID) {
777 /* First check we're tall enough (ie enough topLevel) */
779 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
780 requiredTallness = 0;
782 x >>= YAFFS_TNODES_INTERNAL_BITS;
787 if (requiredTallness > fStruct->topLevel) {
788 /* Not tall enough,gotta make the tree taller */
789 for (i = fStruct->topLevel; i < requiredTallness; i++) {
791 tn = yaffs_GetTnode(dev);
794 tn->internal[0] = fStruct->top;
798 (TSTR("yaffs: no more tnodes" TENDSTR)));
802 fStruct->topLevel = requiredTallness;
805 /* Traverse down to level 0, adding anything we need */
807 l = fStruct->topLevel;
811 while (l > 0 && tn) {
813 ( YAFFS_TNODES_LEVEL0_BITS +
814 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
815 YAFFS_TNODES_INTERNAL_MASK;
818 if((l>1) && !tn->internal[x]){
819 /* Add missing non-level-zero tnode */
820 tn->internal[x] = yaffs_GetTnode(dev);
823 /* Looking from level 1 at level 0 */
825 /* If we already have one, then release it.*/
827 yaffs_FreeTnode(dev,tn->internal[x]);
828 tn->internal[x] = passedTn;
830 } else if(!tn->internal[x]) {
831 /* Don't have one, none passed in */
832 tn->internal[x] = yaffs_GetTnode(dev);
836 tn = tn->internal[x];
842 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
843 yaffs_FreeTnode(dev,passedTn);
850 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
851 yaffs_ExtendedTags * tags, int objectId,
856 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
857 if (yaffs_CheckChunkBit
858 (dev, theChunk / dev->nChunksPerBlock,
859 theChunk % dev->nChunksPerBlock)) {
860 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
862 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
874 /* DeleteWorker scans backwards through the tnode tree and deletes all the
875 * chunks and tnodes in the file
876 * Returns 1 if the tree was deleted.
877 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
880 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
881 int chunkOffset, int *limit)
886 yaffs_ExtendedTags tags;
888 yaffs_Device *dev = in->myDev;
895 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
897 if (tn->internal[i]) {
898 if (limit && (*limit) < 0) {
902 yaffs_DeleteWorker(in,
910 YAFFS_TNODES_INTERNAL_BITS)
918 tn->internal[i] = NULL;
923 return (allDone) ? 1 : 0;
924 } else if (level == 0) {
927 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
929 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
934 YAFFS_TNODES_LEVEL0_BITS) + i;
937 yaffs_FindChunkInGroup(dev,
943 if (foundChunk > 0) {
944 yaffs_DeleteChunk(dev,
957 yaffs_PutLevel0Tnode(dev,tn,i,0);
961 return (i < 0) ? 1 : 0;
971 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
974 yaffs_BlockInfo *theBlock;
976 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
978 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
980 theBlock->softDeletions++;
985 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
986 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
988 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
991 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
992 __u32 level, int chunkOffset)
997 yaffs_Device *dev = in->myDev;
1002 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1004 if (tn->internal[i]) {
1006 yaffs_SoftDeleteWorker(in,
1012 YAFFS_TNODES_INTERNAL_BITS)
1015 yaffs_FreeTnode(dev,
1018 tn->internal[i] = NULL;
1020 /* Hoosterman... how could this happen? */
1024 return (allDone) ? 1 : 0;
1025 } else if (level == 0) {
1027 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1028 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1030 /* Note this does not find the real chunk, only the chunk group.
1031 * We make an assumption that a chunk group is not larger than
1034 yaffs_SoftDeleteChunk(dev, theChunk);
1035 yaffs_PutLevel0Tnode(dev,tn,i,0);
1049 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1052 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1053 if (obj->nDataChunks <= 0) {
1054 /* Empty file with no duplicate object headers, just delete it immediately */
1055 yaffs_FreeTnode(obj->myDev,
1056 obj->variant.fileVariant.top);
1057 obj->variant.fileVariant.top = NULL;
1058 T(YAFFS_TRACE_TRACING,
1059 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1061 yaffs_DoGenericObjectDeletion(obj);
1063 yaffs_SoftDeleteWorker(obj,
1064 obj->variant.fileVariant.top,
1065 obj->variant.fileVariant.
1067 obj->softDeleted = 1;
1072 /* Pruning removes any part of the file structure tree that is beyond the
1073 * bounds of the file (ie that does not point to chunks).
1075 * A file should only get pruned when its size is reduced.
1077 * Before pruning, the chunks must be pulled from the tree and the
1078 * level 0 tnode entries must be zeroed out.
1079 * Could also use this for file deletion, but that's probably better handled
1080 * by a special case.
1083 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1084 __u32 level, int del0)
1092 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1093 if (tn->internal[i] && level > 0) {
1095 yaffs_PruneWorker(dev, tn->internal[i],
1097 (i == 0) ? del0 : 1);
1100 if (tn->internal[i]) {
1105 if (hasData == 0 && del0) {
1106 /* Free and return NULL */
1108 yaffs_FreeTnode(dev, tn);
1118 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1119 yaffs_FileStructure * fStruct)
1126 if (fStruct->topLevel > 0) {
1128 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1130 /* Now we have a tree with all the non-zero branches NULL but the height
1131 * is the same as it was.
1132 * Let's see if we can trim internal tnodes to shorten the tree.
1133 * We can do this if only the 0th element in the tnode is in use
1134 * (ie all the non-zero are NULL)
1137 while (fStruct->topLevel && !done) {
1141 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1142 if (tn->internal[i]) {
1148 fStruct->top = tn->internal[0];
1149 fStruct->topLevel--;
1150 yaffs_FreeTnode(dev, tn);
1160 /*-------------------- End of File Structure functions.-------------------*/
1162 /* yaffs_CreateFreeObjects creates a bunch more objects and
1163 * adds them to the object free list.
1165 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1168 yaffs_Object *newObjects;
1169 yaffs_ObjectList *list;
1174 /* make these things */
1175 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1178 T(YAFFS_TRACE_ALLOCATE,
1179 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1183 /* Hook them into the free list */
1184 for (i = 0; i < nObjects - 1; i++) {
1185 newObjects[i].siblings.next =
1186 (struct list_head *)(&newObjects[i + 1]);
1189 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1190 dev->freeObjects = newObjects;
1191 dev->nFreeObjects += nObjects;
1192 dev->nObjectsCreated += nObjects;
1194 /* Now add this bunch of Objects to a list for freeing up. */
1196 list = YMALLOC(sizeof(yaffs_ObjectList));
1198 T(YAFFS_TRACE_ALLOCATE,
1199 (TSTR("Could not add objects to management list" TENDSTR)));
1201 list->objects = newObjects;
1202 list->next = dev->allocatedObjectList;
1203 dev->allocatedObjectList = list;
1210 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1211 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1213 yaffs_Object *tn = NULL;
1215 /* If there are none left make more */
1216 if (!dev->freeObjects) {
1217 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1220 if (dev->freeObjects) {
1221 tn = dev->freeObjects;
1223 (yaffs_Object *) (dev->freeObjects->siblings.next);
1224 dev->nFreeObjects--;
1226 /* Now sweeten it up... */
1228 memset(tn, 0, sizeof(yaffs_Object));
1231 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1232 INIT_LIST_HEAD(&(tn->hardLinks));
1233 INIT_LIST_HEAD(&(tn->hashLink));
1234 INIT_LIST_HEAD(&tn->siblings);
1236 /* Add it to the lost and found directory.
1237 * NB Can't put root or lostNFound in lostNFound so
1238 * check if lostNFound exists first
1240 if (dev->lostNFoundDir) {
1241 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1248 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1253 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1255 obj->fake = 1; /* it is fake so it has no NAND presence... */
1256 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1257 obj->unlinkAllowed = 0; /* ... or unlink it */
1260 obj->yst_mode = mode;
1262 obj->chunkId = 0; /* Not a valid chunk. */
1269 static void yaffs_UnhashObject(yaffs_Object * tn)
1272 yaffs_Device *dev = tn->myDev;
1274 /* If it is still linked into the bucket list, free from the list */
1275 if (!list_empty(&tn->hashLink)) {
1276 list_del_init(&tn->hashLink);
1277 bucket = yaffs_HashFunction(tn->objectId);
1278 dev->objectBucket[bucket].count--;
1283 /* FreeObject frees up a Object and puts it back on the free list */
1284 static void yaffs_FreeObject(yaffs_Object * tn)
1287 yaffs_Device *dev = tn->myDev;
1291 /* We're still hooked up to a cached inode.
1292 * Don't delete now, but mark for later deletion
1294 tn->deferedFree = 1;
1299 yaffs_UnhashObject(tn);
1301 /* Link into the free list. */
1302 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1303 dev->freeObjects = tn;
1304 dev->nFreeObjects++;
1309 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1311 if (obj->deferedFree) {
1312 yaffs_FreeObject(obj);
1318 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1320 /* Free the list of allocated Objects */
1322 yaffs_ObjectList *tmp;
1324 while (dev->allocatedObjectList) {
1325 tmp = dev->allocatedObjectList->next;
1326 YFREE(dev->allocatedObjectList->objects);
1327 YFREE(dev->allocatedObjectList);
1329 dev->allocatedObjectList = tmp;
1332 dev->freeObjects = NULL;
1333 dev->nFreeObjects = 0;
1336 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1340 dev->allocatedObjectList = NULL;
1341 dev->freeObjects = NULL;
1342 dev->nFreeObjects = 0;
1344 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1345 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1346 dev->objectBucket[i].count = 0;
1351 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1356 int lowest = 999999;
1358 /* First let's see if we can find one that's empty. */
1360 for (i = 0; i < 10 && lowest > 0; i++) {
1362 x %= YAFFS_NOBJECT_BUCKETS;
1363 if (dev->objectBucket[x].count < lowest) {
1364 lowest = dev->objectBucket[x].count;
1370 /* If we didn't find an empty list, then try
1371 * looking a bit further for a short one
1374 for (i = 0; i < 10 && lowest > 3; i++) {
1376 x %= YAFFS_NOBJECT_BUCKETS;
1377 if (dev->objectBucket[x].count < lowest) {
1378 lowest = dev->objectBucket[x].count;
1387 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1389 int bucket = yaffs_FindNiceObjectBucket(dev);
1391 /* Now find an object value that has not already been taken
1392 * by scanning the list.
1396 struct list_head *i;
1398 __u32 n = (__u32) bucket;
1400 /* yaffs_CheckObjectHashSanity(); */
1404 n += YAFFS_NOBJECT_BUCKETS;
1405 if (1 || dev->objectBucket[bucket].count > 0) {
1406 list_for_each(i, &dev->objectBucket[bucket].list) {
1407 /* If there is already one in the list */
1409 && list_entry(i, yaffs_Object,
1410 hashLink)->objectId == n) {
1421 static void yaffs_HashObject(yaffs_Object * in)
1423 int bucket = yaffs_HashFunction(in->objectId);
1424 yaffs_Device *dev = in->myDev;
1426 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1427 dev->objectBucket[bucket].count++;
1431 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1433 int bucket = yaffs_HashFunction(number);
1434 struct list_head *i;
1437 list_for_each(i, &dev->objectBucket[bucket].list) {
1438 /* Look if it is in the list */
1440 in = list_entry(i, yaffs_Object, hashLink);
1441 if (in->objectId == number) {
1443 /* Don't tell the VFS about this one if it is defered free */
1444 if (in->deferedFree)
1456 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1457 yaffs_ObjectType type)
1460 yaffs_Object *theObject;
1463 number = yaffs_CreateNewObjectNumber(dev);
1466 theObject = yaffs_AllocateEmptyObject(dev);
1469 theObject->fake = 0;
1470 theObject->renameAllowed = 1;
1471 theObject->unlinkAllowed = 1;
1472 theObject->objectId = number;
1473 yaffs_HashObject(theObject);
1474 theObject->variantType = type;
1475 #ifdef CONFIG_YAFFS_WINCE
1476 yfsd_WinFileTimeNow(theObject->win_atime);
1477 theObject->win_ctime[0] = theObject->win_mtime[0] =
1478 theObject->win_atime[0];
1479 theObject->win_ctime[1] = theObject->win_mtime[1] =
1480 theObject->win_atime[1];
1484 theObject->yst_atime = theObject->yst_mtime =
1485 theObject->yst_ctime = Y_CURRENT_TIME;
1488 case YAFFS_OBJECT_TYPE_FILE:
1489 theObject->variant.fileVariant.fileSize = 0;
1490 theObject->variant.fileVariant.scannedFileSize = 0;
1491 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1492 theObject->variant.fileVariant.topLevel = 0;
1493 theObject->variant.fileVariant.top =
1494 yaffs_GetTnode(dev);
1496 case YAFFS_OBJECT_TYPE_DIRECTORY:
1497 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1500 case YAFFS_OBJECT_TYPE_SYMLINK:
1501 case YAFFS_OBJECT_TYPE_HARDLINK:
1502 case YAFFS_OBJECT_TYPE_SPECIAL:
1503 /* No action required */
1505 case YAFFS_OBJECT_TYPE_UNKNOWN:
1506 /* todo this should not happen */
1514 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1516 yaffs_ObjectType type)
1518 yaffs_Object *theObject = NULL;
1521 theObject = yaffs_FindObjectByNumber(dev, number);
1525 theObject = yaffs_CreateNewObject(dev, number, type);
1533 static YCHAR *yaffs_CloneString(const YCHAR * str)
1535 YCHAR *newStr = NULL;
1538 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1539 yaffs_strcpy(newStr, str);
1547 * Mknod (create) a new object.
1548 * equivalentObject only has meaning for a hard link;
1549 * aliasString only has meaning for a sumlink.
1550 * rdev only has meaning for devices (a subset of special objects)
1553 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1554 yaffs_Object * parent,
1559 yaffs_Object * equivalentObject,
1560 const YCHAR * aliasString, __u32 rdev)
1564 yaffs_Device *dev = parent->myDev;
1566 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1567 if (yaffs_FindObjectByName(parent, name)) {
1571 in = yaffs_CreateNewObject(dev, -1, type);
1576 in->variantType = type;
1578 in->yst_mode = mode;
1580 #ifdef CONFIG_YAFFS_WINCE
1581 yfsd_WinFileTimeNow(in->win_atime);
1582 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1583 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1586 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1588 in->yst_rdev = rdev;
1592 in->nDataChunks = 0;
1594 yaffs_SetObjectName(in, name);
1597 yaffs_AddObjectToDirectory(parent, in);
1599 in->myDev = parent->myDev;
1602 case YAFFS_OBJECT_TYPE_SYMLINK:
1603 in->variant.symLinkVariant.alias =
1604 yaffs_CloneString(aliasString);
1606 case YAFFS_OBJECT_TYPE_HARDLINK:
1607 in->variant.hardLinkVariant.equivalentObject =
1609 in->variant.hardLinkVariant.equivalentObjectId =
1610 equivalentObject->objectId;
1611 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1613 case YAFFS_OBJECT_TYPE_FILE:
1614 case YAFFS_OBJECT_TYPE_DIRECTORY:
1615 case YAFFS_OBJECT_TYPE_SPECIAL:
1616 case YAFFS_OBJECT_TYPE_UNKNOWN:
1621 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1622 /* Could not create the object header, fail the creation */
1623 yaffs_DestroyObject(in);
1632 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1633 __u32 mode, __u32 uid, __u32 gid)
1635 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1636 uid, gid, NULL, NULL, 0);
1639 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1640 __u32 mode, __u32 uid, __u32 gid)
1642 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1643 mode, uid, gid, NULL, NULL, 0);
1646 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1647 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1649 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1650 uid, gid, NULL, NULL, rdev);
1653 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1654 __u32 mode, __u32 uid, __u32 gid,
1655 const YCHAR * alias)
1657 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1658 uid, gid, NULL, alias, 0);
1661 /* yaffs_Link returns the object id of the equivalent object.*/
1662 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1663 yaffs_Object * equivalentObject)
1665 /* Get the real object in case we were fed a hard link as an equivalent object */
1666 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1668 if (yaffs_MknodObject
1669 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1670 equivalentObject, NULL, 0)) {
1671 return equivalentObject;
1678 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1679 const YCHAR * newName, int force, int shadows)
1684 yaffs_Object *existingTarget;
1686 if (newDir == NULL) {
1687 newDir = obj->parent; /* use the old directory */
1690 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1691 T(YAFFS_TRACE_ALWAYS,
1693 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1698 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1699 if (obj->myDev->isYaffs2) {
1700 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1702 unlinkOp = (newDir == obj->myDev->unlinkedDir
1703 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1706 deleteOp = (newDir == obj->myDev->deletedDir);
1708 existingTarget = yaffs_FindObjectByName(newDir, newName);
1710 /* If the object is a file going into the unlinked directory,
1711 * then it is OK to just stuff it in since duplicate names are allowed.
1712 * else only proceed if the new name does not exist and if we're putting
1713 * it into a directory.
1720 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1721 yaffs_SetObjectName(obj, newName);
1724 yaffs_AddObjectToDirectory(newDir, obj);
1729 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1730 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1737 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1738 yaffs_Object * newDir, const YCHAR * newName)
1741 yaffs_Object *existingTarget;
1744 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1745 /* Special case for case insemsitive systems (eg. WinCE).
1746 * While look-up is case insensitive, the name isn't.
1747 * Therefore we might want to change x.txt to X.txt
1749 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1754 obj = yaffs_FindObjectByName(oldDir, oldName);
1755 /* Check new name to long. */
1756 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1757 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1760 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1761 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1765 if (obj && obj->renameAllowed) {
1767 /* Now do the handling for an existing target, if there is one */
1769 existingTarget = yaffs_FindObjectByName(newDir, newName);
1770 if (existingTarget &&
1771 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1772 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1773 /* There is a target that is a non-empty directory, so we fail */
1774 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1775 } else if (existingTarget && existingTarget != obj) {
1776 /* Nuke the target first, using shadowing,
1777 * but only if it isn't the same object
1779 yaffs_ChangeObjectName(obj, newDir, newName, force,
1780 existingTarget->objectId);
1781 yaffs_UnlinkObject(existingTarget);
1784 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1789 /*------------------------- Block Management and Page Allocation ----------------*/
1791 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1793 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1795 dev->allocationBlock = -1; /* force it to get a new one */
1797 /* Todo we're assuming the malloc will pass. */
1798 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1799 if(!dev->blockInfo){
1800 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1801 dev->blockInfoAlt = 1;
1804 dev->blockInfoAlt = 0;
1806 /* Set up dynamic blockinfo stuff. */
1807 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; // round up bytes
1808 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1809 if(!dev->chunkBits){
1810 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1811 dev->chunkBitsAlt = 1;
1814 dev->chunkBitsAlt = 0;
1816 if (dev->blockInfo && dev->chunkBits) {
1817 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1818 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1826 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1828 if(dev->blockInfoAlt)
1829 YFREE_ALT(dev->blockInfo);
1831 YFREE(dev->blockInfo);
1832 dev->blockInfoAlt = 0;
1834 dev->blockInfo = NULL;
1836 if(dev->chunkBitsAlt)
1837 YFREE_ALT(dev->chunkBits);
1839 YFREE(dev->chunkBits);
1840 dev->chunkBitsAlt = 0;
1841 dev->chunkBits = NULL;
1844 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1845 yaffs_BlockInfo * bi)
1852 return 1; /* disqualification only applies to yaffs2. */
1854 if (!bi->hasShrinkHeader)
1855 return 1; /* can gc */
1857 /* Find the oldest dirty sequence number if we don't know it and save it
1858 * so we don't have to keep recomputing it.
1860 if (!dev->oldestDirtySequence) {
1861 seq = dev->sequenceNumber;
1863 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1865 b = yaffs_GetBlockInfo(dev, i);
1866 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1867 (b->pagesInUse - b->softDeletions) <
1868 dev->nChunksPerBlock && b->sequenceNumber < seq) {
1869 seq = b->sequenceNumber;
1872 dev->oldestDirtySequence = seq;
1875 /* Can't do gc of this block if there are any blocks older than this one that have
1878 return (bi->sequenceNumber <= dev->oldestDirtySequence);
1884 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1885 * for garbage collection.
1888 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1892 int b = dev->currentDirtyChecker;
1898 yaffs_BlockInfo *bi;
1899 static int nonAggressiveSkip = 0;
1901 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1903 * else (we're doing a leasurely gc), then we only bother to do this if the
1904 * block has only a few pages in use.
1907 nonAggressiveSkip--;
1909 if (!aggressive && (nonAggressiveSkip > 0)) {
1914 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1918 dev->internalEndBlock - dev->internalStartBlock + 1;
1921 dev->internalEndBlock - dev->internalStartBlock + 1;
1922 iterations = iterations / 16;
1923 if (iterations > 200) {
1928 for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1930 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1931 b = dev->internalStartBlock;
1934 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1935 T(YAFFS_TRACE_ERROR,
1936 (TSTR("**>> Block %d is not valid" TENDSTR), b));
1940 bi = yaffs_GetBlockInfo(dev, b);
1943 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
1950 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1951 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1952 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1954 pagesInUse = (bi->pagesInUse - bi->softDeletions);
1958 dev->currentDirtyChecker = b;
1962 (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1963 dev->nChunksPerBlock - pagesInUse));
1966 dev->oldestDirtySequence = 0;
1969 nonAggressiveSkip = 4;
1975 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1977 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1981 /* If the block is still healthy erase it and mark as clean.
1982 * If the block has had a data failure, then retire it.
1984 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1986 if (!bi->needsRetiring) {
1987 yaffs_InvalidateCheckpoint(dev);
1988 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1990 dev->nErasureFailures++;
1991 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1992 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1996 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
1998 for (i = 0; i < dev->nChunksPerBlock; i++) {
1999 if (!yaffs_CheckChunkErased
2000 (dev, blockNo * dev->nChunksPerBlock + i)) {
2001 T(YAFFS_TRACE_ERROR,
2003 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2004 TENDSTR), blockNo, i));
2010 /* Clean it up... */
2011 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2012 dev->nErasedBlocks++;
2014 bi->softDeletions = 0;
2015 bi->hasShrinkHeader = 0;
2016 yaffs_ClearChunkBits(dev, blockNo);
2018 T(YAFFS_TRACE_ERASE,
2019 (TSTR("Erased block %d" TENDSTR), blockNo));
2021 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2023 yaffs_RetireBlock(dev, blockNo);
2024 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2025 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2029 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2033 yaffs_BlockInfo *bi;
2035 if (dev->nErasedBlocks < 1) {
2036 /* Hoosterman we've got a problem.
2037 * Can't get space to gc
2039 T(YAFFS_TRACE_ERROR,
2040 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2045 /* Find an empty block. */
2047 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2048 dev->allocationBlockFinder++;
2049 if (dev->allocationBlockFinder < dev->internalStartBlock
2050 || dev->allocationBlockFinder > dev->internalEndBlock) {
2051 dev->allocationBlockFinder = dev->internalStartBlock;
2054 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2056 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2057 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2058 dev->sequenceNumber++;
2059 bi->sequenceNumber = dev->sequenceNumber;
2060 dev->nErasedBlocks--;
2061 T(YAFFS_TRACE_ALLOCATE,
2062 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2063 dev->allocationBlockFinder, dev->sequenceNumber,
2064 dev->nErasedBlocks));
2065 return dev->allocationBlockFinder;
2069 T(YAFFS_TRACE_ALWAYS,
2071 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2072 TENDSTR), dev->nErasedBlocks));
2078 // Check if there's space to allocate...
2079 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2080 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2083 int reservedBlocks = dev->nReservedBlocks;
2084 int checkpointBlocks;
2086 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2087 if(checkpointBlocks < 0)
2088 checkpointBlocks = 0;
2090 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2092 return (dev->nFreeChunks > reservedChunks);
2095 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2098 yaffs_BlockInfo *bi;
2100 if (dev->allocationBlock < 0) {
2101 /* Get next block to allocate off */
2102 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2103 dev->allocationPage = 0;
2106 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2107 /* Not enough space to allocate unless we're allowed to use the reserve. */
2111 if (dev->nErasedBlocks < dev->nReservedBlocks
2112 && dev->allocationPage == 0) {
2113 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2116 /* Next page please.... */
2117 if (dev->allocationBlock >= 0) {
2118 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2120 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2121 dev->allocationPage;
2123 yaffs_SetChunkBit(dev, dev->allocationBlock,
2124 dev->allocationPage);
2126 dev->allocationPage++;
2130 /* If the block is full set the state to full */
2131 if (dev->allocationPage >= dev->nChunksPerBlock) {
2132 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2133 dev->allocationBlock = -1;
2139 T(YAFFS_TRACE_ERROR,
2140 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2145 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2149 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2151 if (dev->allocationBlock > 0) {
2152 n += (dev->nChunksPerBlock - dev->allocationPage);
2159 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2165 int retVal = YAFFS_OK;
2168 int isCheckpointBlock;
2170 int chunksBefore = yaffs_GetErasedChunks(dev);
2173 yaffs_ExtendedTags tags;
2175 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2177 yaffs_Object *object;
2179 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2181 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2183 T(YAFFS_TRACE_TRACING,
2184 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2185 bi->pagesInUse, bi->hasShrinkHeader));
2187 /*yaffs_VerifyFreeChunks(dev); */
2189 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2191 /* Take off the number of soft deleted entries because
2192 * they're going to get really deleted during GC.
2194 dev->nFreeChunks -= bi->softDeletions;
2198 if (isCheckpointBlock ||
2199 !yaffs_StillSomeChunkBits(dev, block)) {
2200 T(YAFFS_TRACE_TRACING,
2202 ("Collecting block %d that has no chunks in use" TENDSTR),
2204 yaffs_BlockBecameDirty(dev, block);
2207 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2209 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2210 chunkInBlock < dev->nChunksPerBlock
2211 && yaffs_StillSomeChunkBits(dev, block);
2212 chunkInBlock++, oldChunk++) {
2213 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2215 /* This page is in use and might need to be copied off */
2219 yaffs_InitialiseTags(&tags);
2221 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2225 yaffs_FindObjectByNumber(dev,
2228 T(YAFFS_TRACE_GC_DETAIL,
2230 ("Collecting page %d, %d %d %d " TENDSTR),
2231 chunkInBlock, tags.objectId, tags.chunkId,
2235 T(YAFFS_TRACE_ERROR,
2237 ("page %d in gc has no object "
2238 TENDSTR), oldChunk));
2241 if (object && object->deleted
2242 && tags.chunkId != 0) {
2243 /* Data chunk in a deleted file, throw it away
2244 * It's a soft deleted data chunk,
2245 * No need to copy this, just forget about it and
2246 * fix up the object.
2249 object->nDataChunks--;
2251 if (object->nDataChunks <= 0) {
2252 /* remeber to clean up the object */
2253 dev->gcCleanupList[cleanups] =
2259 /* Todo object && object->deleted && object->nDataChunks == 0 */
2261 /* Deleted object header with no data chunks.
2262 * Can be discarded and the file deleted.
2264 object->chunkId = 0;
2265 yaffs_FreeTnode(object->myDev,
2268 object->variant.fileVariant.top = NULL;
2269 yaffs_DoGenericObjectDeletion(object);
2271 } else if (object) {
2272 /* It's either a data chunk in a live file or
2273 * an ObjectHeader, so we're interested in it.
2274 * NB Need to keep the ObjectHeaders of deleted files
2275 * until the whole file has been deleted off
2277 tags.serialNumber++;
2281 if (tags.chunkId == 0) {
2282 /* It is an object Id,
2283 * We need to nuke the shrinkheader flags first
2284 * We no longer want the shrinkHeader flag since its work is done
2285 * and if it is left in place it will mess up scanning.
2286 * Also, clear out any shadowing stuff
2289 yaffs_ObjectHeader *oh;
2290 oh = (yaffs_ObjectHeader *)buffer;
2292 oh->shadowsObject = -1;
2293 tags.extraShadows = 0;
2294 tags.extraIsShrinkHeader = 0;
2298 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2301 retVal = YAFFS_FAIL;
2304 /* Ok, now fix up the Tnodes etc. */
2306 if (tags.chunkId == 0) {
2308 object->chunkId = newChunk;
2309 object->serial = tags.serialNumber;
2311 /* It's a data chunk */
2312 yaffs_PutChunkIntoFile
2320 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2325 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2328 /* Do any required cleanups */
2329 for (i = 0; i < cleanups; i++) {
2330 /* Time to delete the file too */
2332 yaffs_FindObjectByNumber(dev,
2333 dev->gcCleanupList[i]);
2335 yaffs_FreeTnode(dev,
2336 object->variant.fileVariant.
2338 object->variant.fileVariant.top = NULL;
2341 ("yaffs: About to finally delete object %d"
2342 TENDSTR), object->objectId));
2343 yaffs_DoGenericObjectDeletion(object);
2344 object->myDev->nDeletedFiles--;
2351 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2354 ("gc did not increase free chunks before %d after %d"
2355 TENDSTR), chunksBefore, chunksAfter));
2363 /* New garbage collector
2364 * If we're very low on erased blocks then we do aggressive garbage collection
2365 * otherwise we do "leasurely" garbage collection.
2366 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2367 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2369 * The idea is to help clear out space in a more spread-out manner.
2370 * Dunno if it really does anything useful.
2372 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2376 int gcOk = YAFFS_OK;
2379 int checkpointBlockAdjust;
2381 if (dev->isDoingGC) {
2382 /* Bail out so we don't get recursive gc */
2386 /* This loop should pass the first time.
2387 * We'll only see looping here if the erase of the collected block fails.
2393 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2394 if(checkpointBlockAdjust < 0)
2395 checkpointBlockAdjust = 0;
2397 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2398 /* We need a block soon...*/
2401 /* We're in no hurry */
2405 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2408 dev->garbageCollections++;
2410 dev->passiveGarbageCollections++;
2415 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2416 dev->nErasedBlocks, aggressive));
2418 gcOk = yaffs_GarbageCollectBlock(dev, block);
2421 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2424 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2425 TENDSTR), dev->nErasedBlocks, maxTries, block));
2427 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2430 return aggressive ? gcOk : YAFFS_OK;
2433 /*------------------------- TAGS --------------------------------*/
2435 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2438 return (tags->chunkId == chunkInObject &&
2439 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2444 /*-------------------- Data file manipulation -----------------*/
2446 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2447 yaffs_ExtendedTags * tags)
2449 /*Get the Tnode, then get the level 0 offset chunk offset */
2452 yaffs_ExtendedTags localTags;
2455 yaffs_Device *dev = in->myDev;
2458 /* Passed a NULL, so use our own tags space */
2462 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2465 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2468 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2474 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2475 yaffs_ExtendedTags * tags)
2477 /* Get the Tnode, then get the level 0 offset chunk offset */
2480 yaffs_ExtendedTags localTags;
2482 yaffs_Device *dev = in->myDev;
2486 /* Passed a NULL, so use our own tags space */
2490 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2494 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2497 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2500 /* Delete the entry in the filestructure (if found) */
2502 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2505 /*T(("No level 0 found for %d\n", chunkInInode)); */
2509 /* T(("Could not find %d to delete\n",chunkInInode)); */
2514 #ifdef YAFFS_PARANOID
2516 static int yaffs_CheckFileSanity(yaffs_Object * in)
2524 yaffs_Tags localTags;
2525 yaffs_Tags *tags = &localTags;
2529 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2530 /* T(("Object not a file\n")); */
2534 objId = in->objectId;
2535 fSize = in->variant.fileVariant.fileSize;
2537 (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2539 for (chunk = 1; chunk <= nChunks; chunk++) {
2540 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2545 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2547 if (yaffs_CheckChunkBits
2548 (dev, theChunk / dev->nChunksPerBlock,
2549 theChunk % dev->nChunksPerBlock)) {
2551 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2555 (tags, in->objectId, chunk, chunkDeleted)) {
2565 /* T(("No level 0 found for %d\n", chunk)); */
2569 return failed ? YAFFS_FAIL : YAFFS_OK;
2574 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2575 int chunkInNAND, int inScan)
2577 /* NB inScan is zero unless scanning.
2578 * For forward scanning, inScan is > 0;
2579 * for backward scanning inScan is < 0
2583 yaffs_Device *dev = in->myDev;
2585 yaffs_ExtendedTags existingTags;
2586 yaffs_ExtendedTags newTags;
2587 unsigned existingSerial, newSerial;
2589 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2590 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2591 * If it is not during Scanning then something went wrong!
2594 T(YAFFS_TRACE_ERROR,
2596 ("yaffs tragedy:attempt to put data chunk into a non-file"
2601 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2605 tn = yaffs_AddOrFindLevel0Tnode(dev,
2606 &in->variant.fileVariant,
2613 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2616 /* If we're scanning then we need to test for duplicates
2617 * NB This does not need to be efficient since it should only ever
2618 * happen when the power fails during a write, then only one
2619 * chunk should ever be affected.
2621 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2622 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2625 if (existingChunk != 0) {
2626 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2627 * thus we have to do a FindChunkInFile to get the real chunk id.
2629 * We have a duplicate now we need to decide which one to use:
2631 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2632 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2633 * YAFFS1: Get both sets of tags and compare serial numbers.
2637 /* Only do this for forward scanning */
2638 yaffs_ReadChunkWithTagsFromNAND(dev,
2642 /* Do a proper find */
2644 yaffs_FindChunkInFile(in, chunkInInode,
2648 if (existingChunk <= 0) {
2649 /*Hoosterman - how did this happen? */
2651 T(YAFFS_TRACE_ERROR,
2653 ("yaffs tragedy: existing chunk < 0 in scan"
2658 /* NB The deleted flags should be false, otherwise the chunks will
2659 * not be loaded during a scan
2662 newSerial = newTags.serialNumber;
2663 existingSerial = existingTags.serialNumber;
2666 (in->myDev->isYaffs2 ||
2667 existingChunk <= 0 ||
2668 ((existingSerial + 1) & 3) == newSerial)) {
2669 /* Forward scanning.
2671 * Delete the old one and drop through to update the tnode
2673 yaffs_DeleteChunk(dev, existingChunk, 1,
2676 /* Backward scanning or we want to use the existing one
2678 * Delete the new one and return early so that the tnode isn't changed
2680 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2688 if (existingChunk == 0) {
2692 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2697 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2700 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2702 if (chunkInNAND >= 0) {
2703 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2706 T(YAFFS_TRACE_NANDACCESS,
2707 (TSTR("Chunk %d not found zero instead" TENDSTR),
2709 /* get sane (zero) data if you read a hole */
2710 memset(buffer, 0, in->myDev->nBytesPerChunk);
2716 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2720 yaffs_ExtendedTags tags;
2721 yaffs_BlockInfo *bi;
2727 block = chunkId / dev->nChunksPerBlock;
2728 page = chunkId % dev->nChunksPerBlock;
2730 bi = yaffs_GetBlockInfo(dev, block);
2732 T(YAFFS_TRACE_DELETION,
2733 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2736 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2738 yaffs_InitialiseTags(&tags);
2740 tags.chunkDeleted = 1;
2742 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2743 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2745 dev->nUnmarkedDeletions++;
2748 /* Pull out of the management area.
2749 * If the whole block became dirty, this will kick off an erasure.
2751 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2752 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2753 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2754 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2757 yaffs_ClearChunkBit(dev, block, page);
2761 if (bi->pagesInUse == 0 &&
2762 !bi->hasShrinkHeader &&
2763 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2764 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2765 yaffs_BlockBecameDirty(dev, block);
2769 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2774 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2775 const __u8 * buffer, int nBytes,
2778 /* Find old chunk Need to do this to get serial number
2779 * Write new one and patch into tree.
2780 * Invalidate old tags.
2784 yaffs_ExtendedTags prevTags;
2787 yaffs_ExtendedTags newTags;
2789 yaffs_Device *dev = in->myDev;
2791 yaffs_CheckGarbageCollection(dev);
2793 /* Get the previous chunk at this location in the file if it exists */
2794 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2796 /* Set up new tags */
2797 yaffs_InitialiseTags(&newTags);
2799 newTags.chunkId = chunkInInode;
2800 newTags.objectId = in->objectId;
2801 newTags.serialNumber =
2802 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2803 newTags.byteCount = nBytes;
2806 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2809 if (newChunkId >= 0) {
2810 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2812 if (prevChunkId >= 0) {
2813 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2817 yaffs_CheckFileSanity(in);
2823 /* UpdateObjectHeader updates the header on NAND for an object.
2824 * If name is not NULL, then that new name is used.
2826 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2827 int isShrink, int shadows)
2830 yaffs_BlockInfo *bi;
2832 yaffs_Device *dev = in->myDev;
2838 yaffs_ExtendedTags newTags;
2840 __u8 *buffer = NULL;
2841 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2843 yaffs_ObjectHeader *oh = NULL;
2845 if (!in->fake || force) {
2847 yaffs_CheckGarbageCollection(dev);
2849 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2850 oh = (yaffs_ObjectHeader *) buffer;
2852 prevChunkId = in->chunkId;
2854 if (prevChunkId >= 0) {
2855 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2857 memcpy(oldName, oh->name, sizeof(oh->name));
2860 memset(buffer, 0xFF, dev->nBytesPerChunk);
2862 oh->type = in->variantType;
2863 oh->yst_mode = in->yst_mode;
2864 oh->shadowsObject = shadows;
2866 #ifdef CONFIG_YAFFS_WINCE
2867 oh->win_atime[0] = in->win_atime[0];
2868 oh->win_ctime[0] = in->win_ctime[0];
2869 oh->win_mtime[0] = in->win_mtime[0];
2870 oh->win_atime[1] = in->win_atime[1];
2871 oh->win_ctime[1] = in->win_ctime[1];
2872 oh->win_mtime[1] = in->win_mtime[1];
2874 oh->yst_uid = in->yst_uid;
2875 oh->yst_gid = in->yst_gid;
2876 oh->yst_atime = in->yst_atime;
2877 oh->yst_mtime = in->yst_mtime;
2878 oh->yst_ctime = in->yst_ctime;
2879 oh->yst_rdev = in->yst_rdev;
2882 oh->parentObjectId = in->parent->objectId;
2884 oh->parentObjectId = 0;
2887 if (name && *name) {
2888 memset(oh->name, 0, sizeof(oh->name));
2889 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2890 } else if (prevChunkId) {
2891 memcpy(oh->name, oldName, sizeof(oh->name));
2893 memset(oh->name, 0, sizeof(oh->name));
2896 oh->isShrink = isShrink;
2898 switch (in->variantType) {
2899 case YAFFS_OBJECT_TYPE_UNKNOWN:
2900 /* Should not happen */
2902 case YAFFS_OBJECT_TYPE_FILE:
2904 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2905 || oh->parentObjectId ==
2906 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2907 fileVariant.fileSize;
2909 case YAFFS_OBJECT_TYPE_HARDLINK:
2910 oh->equivalentObjectId =
2911 in->variant.hardLinkVariant.equivalentObjectId;
2913 case YAFFS_OBJECT_TYPE_SPECIAL:
2916 case YAFFS_OBJECT_TYPE_DIRECTORY:
2919 case YAFFS_OBJECT_TYPE_SYMLINK:
2920 yaffs_strncpy(oh->alias,
2921 in->variant.symLinkVariant.alias,
2922 YAFFS_MAX_ALIAS_LENGTH);
2923 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2928 yaffs_InitialiseTags(&newTags);
2930 newTags.chunkId = 0;
2931 newTags.objectId = in->objectId;
2932 newTags.serialNumber = in->serial;
2934 /* Add extra info for file header */
2936 newTags.extraHeaderInfoAvailable = 1;
2937 newTags.extraParentObjectId = oh->parentObjectId;
2938 newTags.extraFileLength = oh->fileSize;
2939 newTags.extraIsShrinkHeader = oh->isShrink;
2940 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2941 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2942 newTags.extraObjectType = in->variantType;
2944 /* Create new chunk in NAND */
2946 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2947 (prevChunkId >= 0) ? 1 : 0);
2949 if (newChunkId >= 0) {
2951 in->chunkId = newChunkId;
2953 if (prevChunkId >= 0) {
2954 yaffs_DeleteChunk(dev, prevChunkId, 1,
2958 if(!yaffs_ObjectHasCachedWriteData(in))
2961 /* If this was a shrink, then mark the block that the chunk lives on */
2963 bi = yaffs_GetBlockInfo(in->myDev,
2964 newChunkId /in->myDev-> nChunksPerBlock);
2965 bi->hasShrinkHeader = 1;
2970 retVal = newChunkId;
2975 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2980 /*------------------------ Short Operations Cache ----------------------------------------
2981 * In many situations where there is no high level buffering (eg WinCE) a lot of
2982 * reads might be short sequential reads, and a lot of writes may be short
2983 * sequential writes. eg. scanning/writing a jpeg file.
2984 * In these cases, a short read/write cache can provide a huge perfomance benefit
2985 * with dumb-as-a-rock code.
2986 * In Linux, the page cache provides read buffering aand the short op cache provides write
2989 * There are a limited number (~10) of cache chunks per device so that we don't
2990 * need a very intelligent search.
2993 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
2995 yaffs_Device *dev = obj->myDev;
2997 yaffs_ChunkCache *cache;
2998 int nCaches = obj->myDev->nShortOpCaches;
3001 for(i = 0; i < nCaches; i++){
3002 if (dev->srCache[i].object == obj &&
3003 dev->srCache[i].dirty)
3012 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3014 yaffs_Device *dev = obj->myDev;
3015 int lowest = -99; /* Stop compiler whining. */
3017 yaffs_ChunkCache *cache;
3018 int chunkWritten = 0;
3019 int nCaches = obj->myDev->nShortOpCaches;
3025 /* Find the dirty cache for this object with the lowest chunk id. */
3026 for (i = 0; i < nCaches; i++) {
3027 if (dev->srCache[i].object == obj &&
3028 dev->srCache[i].dirty) {
3030 || dev->srCache[i].chunkId <
3032 cache = &dev->srCache[i];
3033 lowest = cache->chunkId;
3038 if (cache && !cache->locked) {
3039 /* Write it out and free it up */
3042 yaffs_WriteChunkDataToObject(cache->object,
3048 cache->object = NULL;
3051 } while (cache && chunkWritten > 0);
3054 /* Hoosterman, disk full while writing cache out. */
3055 T(YAFFS_TRACE_ERROR,
3056 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3063 /*yaffs_FlushEntireDeviceCache(dev)
3068 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3071 int nCaches = dev->nShortOpCaches;
3074 /* Find a dirty object in the cache and flush it...
3075 * until there are no further dirty objects.
3079 for( i = 0; i < nCaches && !obj; i++) {
3080 if (dev->srCache[i].object &&
3081 dev->srCache[i].dirty)
3082 obj = dev->srCache[i].object;
3086 yaffs_FlushFilesChunkCache(obj);
3093 /* Grab us a cache chunk for use.
3094 * First look for an empty one.
3095 * Then look for the least recently used non-dirty one.
3096 * Then look for the least recently used dirty one...., flush and look again.
3098 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3104 if (dev->nShortOpCaches > 0) {
3105 for (i = 0; i < dev->nShortOpCaches; i++) {
3106 if (!dev->srCache[i].object)
3107 return &dev->srCache[i];
3113 usage = 0; /* just to stop the compiler grizzling */
3115 for (i = 0; i < dev->nShortOpCaches; i++) {
3116 if (!dev->srCache[i].dirty &&
3117 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3119 usage = dev->srCache[i].lastUse;
3125 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3132 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3134 yaffs_ChunkCache *cache;
3135 yaffs_Object *theObj;
3140 if (dev->nShortOpCaches > 0) {
3141 /* Try find a non-dirty one... */
3143 cache = yaffs_GrabChunkCacheWorker(dev);
3146 /* They were all dirty, find the last recently used object and flush
3147 * its cache, then find again.
3148 * NB what's here is not very accurate, we actually flush the object
3149 * the last recently used page.
3152 /* With locking we can't assume we can use entry zero */
3159 for (i = 0; i < dev->nShortOpCaches; i++) {
3160 if (dev->srCache[i].object &&
3161 !dev->srCache[i].locked &&
3162 (dev->srCache[i].lastUse < usage || !cache))
3164 usage = dev->srCache[i].lastUse;
3165 theObj = dev->srCache[i].object;
3166 cache = &dev->srCache[i];
3171 if (!cache || cache->dirty) {
3172 /* Flush and try again */
3173 yaffs_FlushFilesChunkCache(theObj);
3174 cache = yaffs_GrabChunkCacheWorker(dev);
3184 /* Find a cached chunk */
3185 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3188 yaffs_Device *dev = obj->myDev;
3190 if (dev->nShortOpCaches > 0) {
3191 for (i = 0; i < dev->nShortOpCaches; i++) {
3192 if (dev->srCache[i].object == obj &&
3193 dev->srCache[i].chunkId == chunkId) {
3196 return &dev->srCache[i];
3203 /* Mark the chunk for the least recently used algorithym */
3204 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3208 if (dev->nShortOpCaches > 0) {
3209 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3210 /* Reset the cache usages */
3212 for (i = 1; i < dev->nShortOpCaches; i++) {
3213 dev->srCache[i].lastUse = 0;
3220 cache->lastUse = dev->srLastUse;
3228 /* Invalidate a single cache page.
3229 * Do this when a whole page gets written,
3230 * ie the short cache for this page is no longer valid.
3232 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3234 if (object->myDev->nShortOpCaches > 0) {
3235 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3238 cache->object = NULL;
3243 /* Invalidate all the cache pages associated with this object
3244 * Do this whenever ther file is deleted or resized.
3246 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3249 yaffs_Device *dev = in->myDev;
3251 if (dev->nShortOpCaches > 0) {
3252 /* Invalidate it. */
3253 for (i = 0; i < dev->nShortOpCaches; i++) {
3254 if (dev->srCache[i].object == in) {
3255 dev->srCache[i].object = NULL;
3261 /*--------------------- Checkpointing --------------------*/
3264 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3266 yaffs_CheckpointValidity cp;
3267 cp.structType = sizeof(cp);
3268 cp.magic = YAFFS_MAGIC;
3270 cp.head = (head) ? 1 : 0;
3272 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3276 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3278 yaffs_CheckpointValidity cp;
3281 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3284 ok = (cp.structType == sizeof(cp)) &&
3285 (cp.magic == YAFFS_MAGIC) &&
3286 (cp.version == 1) &&
3287 (cp.head == ((head) ? 1 : 0));
3291 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3294 cp->nErasedBlocks = dev->nErasedBlocks;
3295 cp->allocationBlock = dev->allocationBlock;
3296 cp->allocationPage = dev->allocationPage;
3297 cp->nFreeChunks = dev->nFreeChunks;
3299 cp->nDeletedFiles = dev->nDeletedFiles;
3300 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3301 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3302 cp->sequenceNumber = dev->sequenceNumber;
3303 cp->oldestDirtySequence = dev->oldestDirtySequence;
3307 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3308 yaffs_CheckpointDevice *cp)
3310 dev->nErasedBlocks = cp->nErasedBlocks;
3311 dev->allocationBlock = cp->allocationBlock;
3312 dev->allocationPage = cp->allocationPage;
3313 dev->nFreeChunks = cp->nFreeChunks;
3315 dev->nDeletedFiles = cp->nDeletedFiles;
3316 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3317 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3318 dev->sequenceNumber = cp->sequenceNumber;
3319 dev->oldestDirtySequence = cp->oldestDirtySequence;
3323 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3325 yaffs_CheckpointDevice cp;
3327 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3331 /* Write device runtime values*/
3332 yaffs_DeviceToCheckpointDevice(&cp,dev);
3333 cp.structType = sizeof(cp);
3335 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3337 /* Write block info */
3339 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3340 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3343 /* Write chunk bits */
3345 nBytes = nBlocks * dev->chunkBitmapStride;
3346 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3352 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3354 yaffs_CheckpointDevice cp;
3356 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3360 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3364 if(cp.structType != sizeof(cp))
3368 yaffs_CheckpointDeviceToDevice(dev,&cp);
3370 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3372 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3376 nBytes = nBlocks * dev->chunkBitmapStride;
3378 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3383 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3387 cp->objectId = obj->objectId;
3388 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3389 cp->chunkId = obj->chunkId;
3390 cp->variantType = obj->variantType;
3391 cp->deleted = obj->deleted;
3392 cp->softDeleted = obj->softDeleted;
3393 cp->unlinked = obj->unlinked;
3394 cp->fake = obj->fake;
3395 cp->renameAllowed = obj->renameAllowed;
3396 cp->unlinkAllowed = obj->unlinkAllowed;
3397 cp->serial = obj->serial;
3398 cp->nDataChunks = obj->nDataChunks;
3400 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3401 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3402 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3403 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3406 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3409 yaffs_Object *parent;
3411 obj->objectId = cp->objectId;
3414 parent = yaffs_FindOrCreateObjectByNumber(
3417 YAFFS_OBJECT_TYPE_DIRECTORY);
3422 yaffs_AddObjectToDirectory(parent, obj);
3424 obj->chunkId = cp->chunkId;
3425 obj->variantType = cp->variantType;
3426 obj->deleted = cp->deleted;
3427 obj->softDeleted = cp->softDeleted;
3428 obj->unlinked = cp->unlinked;
3429 obj->fake = cp->fake;
3430 obj->renameAllowed = cp->renameAllowed;
3431 obj->unlinkAllowed = cp->unlinkAllowed;
3432 obj->serial = cp->serial;
3433 obj->nDataChunks = cp->nDataChunks;
3435 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3436 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3437 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3438 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3440 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3441 obj->lazyLoaded = 1;
3446 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3447 __u32 level, int chunkOffset)
3450 yaffs_Device *dev = in->myDev;
3452 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3457 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3458 if (tn->internal[i]) {
3459 ok = yaffs_CheckpointTnodeWorker(in,
3462 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3465 } else if (level == 0) {
3466 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3467 /* printf("write tnode at %d\n",baseOffset); */
3468 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3470 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3478 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3480 __u32 endMarker = ~0;
3483 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3484 ok = yaffs_CheckpointTnodeWorker(obj,
3485 obj->variant.fileVariant.top,
3486 obj->variant.fileVariant.topLevel,
3489 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3496 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3500 yaffs_Device *dev = obj->myDev;
3501 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3504 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3506 while(ok && (~baseChunk)){
3507 /* Read level 0 tnode */
3509 /* printf("read tnode at %d\n",baseChunk); */
3510 tn = yaffs_GetTnodeRaw(dev);
3512 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3513 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3518 ok = yaffs_AddOrFindLevel0Tnode(dev,
3525 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3533 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3536 yaffs_CheckpointObject cp;
3539 struct list_head *lh;
3542 /* Iterate through the objects in each hash entry,
3543 * dumping them to the checkpointing stream.
3546 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3547 list_for_each(lh, &dev->objectBucket[i].list) {
3549 obj = list_entry(lh, yaffs_Object, hashLink);
3550 if (!obj->deferedFree) {
3551 yaffs_ObjectToCheckpointObject(&cp,obj);
3552 cp.structType = sizeof(cp);
3553 /* printf("Write out object %d type %d\n",obj->objectId,obj->variantType); */
3554 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3556 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3557 ok = yaffs_WriteCheckpointTnodes(obj);
3564 /* Dump end of list */
3565 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3566 cp.structType = sizeof(cp);
3569 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3574 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3577 yaffs_CheckpointObject cp;
3580 yaffs_Object *hardList = NULL;
3582 while(ok && !done) {
3583 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3584 if(cp.structType != sizeof(cp)) {
3585 /* printf("structure parsing failed\n"); */
3589 if(ok && cp.objectId == ~0)
3592 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Read object %d parent %d type %d" TENDSTR),
3593 cp.objectId,cp.parentId,cp.variantType));
3594 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3596 yaffs_CheckpointObjectToObject(obj,&cp);
3597 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3598 ok = yaffs_ReadCheckpointTnodes(obj);
3599 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3600 obj->hardLinks.next =
3601 (struct list_head *)
3611 yaffs_HardlinkFixup(dev,hardList);
3616 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3621 ok = yaffs_CheckpointOpen(dev,1);
3624 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3626 ok = yaffs_WriteCheckpointDevice(dev);
3628 ok = yaffs_WriteCheckpointObjects(dev);
3630 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3632 if(!yaffs_CheckpointClose(dev))
3636 dev->isCheckpointed = 1;
3638 dev->isCheckpointed = 0;
3640 return dev->isCheckpointed;
3643 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3647 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3650 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3652 ok = yaffs_ReadCheckpointDevice(dev);
3654 ok = yaffs_ReadCheckpointObjects(dev);
3656 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3660 if(!yaffs_CheckpointClose(dev))
3664 dev->isCheckpointed = 1;
3666 dev->isCheckpointed = 0;
3672 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3674 if(dev->isCheckpointed ||
3675 dev->blocksInCheckpoint > 0){
3676 dev->isCheckpointed = 0;
3677 yaffs_CheckpointInvalidateStream(dev);
3678 if(dev->superBlock && dev->markSuperBlockDirty)
3679 dev->markSuperBlockDirty(dev->superBlock);
3684 int yaffs_CheckpointSave(yaffs_Device *dev)
3686 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3688 if(!dev->isCheckpointed)
3689 yaffs_WriteCheckpointData(dev);
3691 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3693 return dev->isCheckpointed;
3696 int yaffs_CheckpointRestore(yaffs_Device *dev)
3699 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3701 retval = yaffs_ReadCheckpointData(dev);
3703 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3708 /*--------------------- File read/write ------------------------
3709 * Read and write have very similar structures.
3710 * In general the read/write has three parts to it
3711 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3712 * Some complete chunks
3713 * An incomplete chunk to end off with
3715 * Curve-balls: the first chunk might also be the last chunk.
3718 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3727 yaffs_ChunkCache *cache;
3734 chunk = offset / dev->nBytesPerChunk + 1; /* The first chunk is 1 */
3735 start = offset % dev->nBytesPerChunk;
3737 /* OK now check for the curveball where the start and end are in
3740 if ((start + n) < dev->nBytesPerChunk) {
3743 nToCopy = dev->nBytesPerChunk - start;
3746 cache = yaffs_FindChunkCache(in, chunk);
3748 /* If the chunk is already in the cache or it is less than a whole chunk
3749 * then use the cache (if there is caching)
3750 * else bypass the cache.
3752 if (cache || nToCopy != dev->nBytesPerChunk) {
3753 if (dev->nShortOpCaches > 0) {
3755 /* If we can't find the data in the cache, then load it up. */
3758 cache = yaffs_GrabChunkCache(in->myDev);
3760 cache->chunkId = chunk;
3763 yaffs_ReadChunkDataFromObject(in, chunk,
3769 yaffs_UseChunkCache(dev, cache, 0);
3773 #ifdef CONFIG_YAFFS_WINCE
3774 yfsd_UnlockYAFFS(TRUE);
3776 memcpy(buffer, &cache->data[start], nToCopy);
3778 #ifdef CONFIG_YAFFS_WINCE
3779 yfsd_LockYAFFS(TRUE);
3783 /* Read into the local buffer then copy..*/
3786 yaffs_GetTempBuffer(dev, __LINE__);
3787 yaffs_ReadChunkDataFromObject(in, chunk,
3789 #ifdef CONFIG_YAFFS_WINCE
3790 yfsd_UnlockYAFFS(TRUE);
3792 memcpy(buffer, &localBuffer[start], nToCopy);
3794 #ifdef CONFIG_YAFFS_WINCE
3795 yfsd_LockYAFFS(TRUE);
3797 yaffs_ReleaseTempBuffer(dev, localBuffer,
3802 #ifdef CONFIG_YAFFS_WINCE
3803 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3805 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3806 * This is because we otherwise screw up WinCE's memory mapper
3808 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3810 #ifdef CONFIG_YAFFS_WINCE
3811 yfsd_UnlockYAFFS(TRUE);
3813 memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3815 #ifdef CONFIG_YAFFS_WINCE
3816 yfsd_LockYAFFS(TRUE);
3817 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3821 /* A full chunk. Read directly into the supplied buffer. */
3822 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3836 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3837 int nBytes, int writeThrough)
3846 int startOfWrite = offset;
3847 int chunkWritten = 0;
3854 while (n > 0 && chunkWritten >= 0) {
3855 chunk = offset / dev->nBytesPerChunk + 1;
3856 start = offset % dev->nBytesPerChunk;
3858 /* OK now check for the curveball where the start and end are in
3862 if ((start + n) < dev->nBytesPerChunk) {
3865 /* Now folks, to calculate how many bytes to write back....
3866 * If we're overwriting and not writing to then end of file then
3867 * we need to write back as much as was there before.
3871 in->variant.fileVariant.fileSize -
3872 ((chunk - 1) * dev->nBytesPerChunk);
3874 if (nBytesRead > dev->nBytesPerChunk) {
3875 nBytesRead = dev->nBytesPerChunk;
3880 (start + n)) ? nBytesRead : (start + n);
3883 nToCopy = dev->nBytesPerChunk - start;
3884 nToWriteBack = dev->nBytesPerChunk;
3887 if (nToCopy != dev->nBytesPerChunk) {
3888 /* An incomplete start or end chunk (or maybe both start and end chunk) */
3889 if (dev->nShortOpCaches > 0) {
3890 yaffs_ChunkCache *cache;
3891 /* If we can't find the data in the cache, then load the cache */
3892 cache = yaffs_FindChunkCache(in, chunk);
3895 && yaffs_CheckSpaceForAllocation(in->
3897 cache = yaffs_GrabChunkCache(in->myDev);
3899 cache->chunkId = chunk;
3902 yaffs_ReadChunkDataFromObject(in, chunk,
3908 !yaffs_CheckSpaceForAllocation(in->myDev)){
3909 /* Drop the cache if it was a read cache item and
3910 * no space check has been made for it.
3916 yaffs_UseChunkCache(dev, cache, 1);
3918 #ifdef CONFIG_YAFFS_WINCE
3919 yfsd_UnlockYAFFS(TRUE);
3922 memcpy(&cache->data[start], buffer,
3925 #ifdef CONFIG_YAFFS_WINCE
3926 yfsd_LockYAFFS(TRUE);
3929 cache->nBytes = nToWriteBack;
3933 yaffs_WriteChunkDataToObject
3936 cache->data, cache->nBytes,
3942 chunkWritten = -1; /* fail the write */
3945 /* An incomplete start or end chunk (or maybe both start and end chunk)
3946 * Read into the local buffer then copy, then copy over and write back.
3950 yaffs_GetTempBuffer(dev, __LINE__);
3952 yaffs_ReadChunkDataFromObject(in, chunk,
3955 #ifdef CONFIG_YAFFS_WINCE
3956 yfsd_UnlockYAFFS(TRUE);
3959 memcpy(&localBuffer[start], buffer, nToCopy);
3961 #ifdef CONFIG_YAFFS_WINCE
3962 yfsd_LockYAFFS(TRUE);
3965 yaffs_WriteChunkDataToObject(in, chunk,
3970 yaffs_ReleaseTempBuffer(dev, localBuffer,
3977 #ifdef CONFIG_YAFFS_WINCE
3978 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3979 * This is because we otherwise screw up WinCE's memory mapper
3981 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3982 #ifdef CONFIG_YAFFS_WINCE
3983 yfsd_UnlockYAFFS(TRUE);
3985 memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3986 #ifdef CONFIG_YAFFS_WINCE
3987 yfsd_LockYAFFS(TRUE);
3990 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3991 dev->nBytesPerChunk,
3993 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3995 /* A full chunk. Write directly from the supplied buffer. */
3997 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3998 dev->nBytesPerChunk,
4001 /* Since we've overwritten the cached data, we better invalidate it. */
4002 yaffs_InvalidateChunkCache(in, chunk);
4005 if (chunkWritten >= 0) {
4014 /* Update file object */
4016 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4017 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4026 /* ---------------------- File resizing stuff ------------------ */
4028 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4031 yaffs_Device *dev = in->myDev;
4032 int oldFileSize = in->variant.fileVariant.fileSize;
4034 int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
4036 int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
4037 dev->nBytesPerChunk;
4041 /* Delete backwards so that we don't end up with holes if
4042 * power is lost part-way through the operation.
4044 for (i = lastDel; i >= startDel; i--) {
4045 /* NB this could be optimised somewhat,
4046 * eg. could retrieve the tags and write them without
4047 * using yaffs_DeleteChunk
4050 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4053 (dev->internalStartBlock * dev->nChunksPerBlock)
4055 ((dev->internalEndBlock +
4056 1) * dev->nChunksPerBlock)) {
4057 T(YAFFS_TRACE_ALWAYS,
4058 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4062 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4069 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
4072 int oldFileSize = in->variant.fileVariant.fileSize;
4073 int sizeOfPartialChunk;
4074 yaffs_Device *dev = in->myDev;
4076 sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
4078 yaffs_FlushFilesChunkCache(in);
4079 yaffs_InvalidateWholeChunkCache(in);
4081 yaffs_CheckGarbageCollection(dev);
4083 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4084 return yaffs_GetFileSize(in);
4087 if (newSize == oldFileSize) {
4091 if (newSize < oldFileSize) {
4093 yaffs_PruneResizedChunks(in, newSize);
4095 if (sizeOfPartialChunk != 0) {
4096 int lastChunk = 1 + newSize / dev->nBytesPerChunk;
4097 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4099 /* Got to read and rewrite the last chunk with its new size and zero pad */
4100 yaffs_ReadChunkDataFromObject(in, lastChunk,
4103 memset(localBuffer + sizeOfPartialChunk, 0,
4104 dev->nBytesPerChunk - sizeOfPartialChunk);
4106 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4107 sizeOfPartialChunk, 1);
4109 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4112 in->variant.fileVariant.fileSize = newSize;
4114 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4116 /* Write a new object header.
4117 * show we've shrunk the file, if need be
4118 * Do this only if the file is not in the deleted directories.
4120 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4121 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4122 yaffs_UpdateObjectHeader(in, NULL, 0,
4123 (newSize < oldFileSize) ? 1 : 0, 0);
4129 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4131 obj = yaffs_GetEquivalentObject(obj);
4133 switch (obj->variantType) {
4134 case YAFFS_OBJECT_TYPE_FILE:
4135 return obj->variant.fileVariant.fileSize;
4136 case YAFFS_OBJECT_TYPE_SYMLINK:
4137 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4145 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4149 yaffs_FlushFilesChunkCache(in);
4151 #ifdef CONFIG_YAFFS_WINCE
4152 yfsd_WinFileTimeNow(in->win_mtime);
4155 in->yst_mtime = Y_CURRENT_TIME;
4161 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4162 0) ? YAFFS_OK : YAFFS_FAIL;
4171 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4174 /* First off, invalidate the file's data in the cache, without flushing. */
4175 yaffs_InvalidateWholeChunkCache(in);
4177 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4178 /* Move to the unlinked directory so we have a record that it was deleted. */
4179 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4183 yaffs_RemoveObjectFromDirectory(in);
4184 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4187 yaffs_FreeObject(in);
4192 /* yaffs_DeleteFile deletes the whole file data
4193 * and the inode associated with the file.
4194 * It does not delete the links associated with the file.
4196 static int yaffs_UnlinkFile(yaffs_Object * in)
4200 int immediateDeletion = 0;
4205 immediateDeletion = 1;
4209 if (in->inUse <= 0) {
4210 immediateDeletion = 1;
4214 if (immediateDeletion) {
4216 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4218 T(YAFFS_TRACE_TRACING,
4219 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4222 in->myDev->nDeletedFiles++;
4223 if (0 && in->myDev->isYaffs2) {
4224 yaffs_ResizeFile(in, 0);
4226 yaffs_SoftDeleteFile(in);
4229 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4237 int yaffs_DeleteFile(yaffs_Object * in)
4239 int retVal = YAFFS_OK;
4241 if (in->nDataChunks > 0) {
4242 /* Use soft deletion if there is data in the file */
4243 if (!in->unlinked) {
4244 retVal = yaffs_UnlinkFile(in);
4246 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4248 in->myDev->nDeletedFiles++;
4249 yaffs_SoftDeleteFile(in);
4251 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4253 /* The file has no data chunks so we toss it immediately */
4254 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4255 in->variant.fileVariant.top = NULL;
4256 yaffs_DoGenericObjectDeletion(in);
4262 static int yaffs_DeleteDirectory(yaffs_Object * in)
4264 /* First check that the directory is empty. */
4265 if (list_empty(&in->variant.directoryVariant.children)) {
4266 return yaffs_DoGenericObjectDeletion(in);
4273 static int yaffs_DeleteSymLink(yaffs_Object * in)
4275 YFREE(in->variant.symLinkVariant.alias);
4277 return yaffs_DoGenericObjectDeletion(in);
4280 static int yaffs_DeleteHardLink(yaffs_Object * in)
4282 /* remove this hardlink from the list assocaited with the equivalent
4285 list_del(&in->hardLinks);
4286 return yaffs_DoGenericObjectDeletion(in);
4289 static void yaffs_DestroyObject(yaffs_Object * obj)
4291 switch (obj->variantType) {
4292 case YAFFS_OBJECT_TYPE_FILE:
4293 yaffs_DeleteFile(obj);
4295 case YAFFS_OBJECT_TYPE_DIRECTORY:
4296 yaffs_DeleteDirectory(obj);
4298 case YAFFS_OBJECT_TYPE_SYMLINK:
4299 yaffs_DeleteSymLink(obj);
4301 case YAFFS_OBJECT_TYPE_HARDLINK:
4302 yaffs_DeleteHardLink(obj);
4304 case YAFFS_OBJECT_TYPE_SPECIAL:
4305 yaffs_DoGenericObjectDeletion(obj);
4307 case YAFFS_OBJECT_TYPE_UNKNOWN:
4308 break; /* should not happen. */
4312 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4315 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4316 return yaffs_DeleteHardLink(obj);
4317 } else if (!list_empty(&obj->hardLinks)) {
4318 /* Curve ball: We're unlinking an object that has a hardlink.
4320 * This problem arises because we are not strictly following
4321 * The Linux link/inode model.
4323 * We can't really delete the object.
4324 * Instead, we do the following:
4325 * - Select a hardlink.
4326 * - Unhook it from the hard links
4327 * - Unhook it from its parent directory (so that the rename can work)
4328 * - Rename the object to the hardlink's name.
4329 * - Delete the hardlink
4334 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4336 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4338 list_del_init(&hl->hardLinks);
4339 list_del_init(&hl->siblings);
4341 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4343 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4345 if (retVal == YAFFS_OK) {
4346 retVal = yaffs_DoGenericObjectDeletion(hl);
4351 switch (obj->variantType) {
4352 case YAFFS_OBJECT_TYPE_FILE:
4353 return yaffs_UnlinkFile(obj);
4355 case YAFFS_OBJECT_TYPE_DIRECTORY:
4356 return yaffs_DeleteDirectory(obj);
4358 case YAFFS_OBJECT_TYPE_SYMLINK:
4359 return yaffs_DeleteSymLink(obj);
4361 case YAFFS_OBJECT_TYPE_SPECIAL:
4362 return yaffs_DoGenericObjectDeletion(obj);
4364 case YAFFS_OBJECT_TYPE_HARDLINK:
4365 case YAFFS_OBJECT_TYPE_UNKNOWN:
4373 static int yaffs_UnlinkObject( yaffs_Object *obj)
4376 if (obj && obj->unlinkAllowed) {
4377 return yaffs_UnlinkWorker(obj);
4383 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4387 obj = yaffs_FindObjectByName(dir, name);
4388 return yaffs_UnlinkObject(obj);
4391 /*----------------------- Initialisation Scanning ---------------------- */
4393 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4394 int backwardScanning)
4398 if (!backwardScanning) {
4399 /* Handle YAFFS1 forward scanning case
4400 * For YAFFS1 we always do the deletion
4404 /* Handle YAFFS2 case (backward scanning)
4405 * If the shadowed object exists then ignore.
4407 if (yaffs_FindObjectByNumber(dev, objId)) {
4412 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4413 * We put it in unlinked dir to be cleaned up after the scanning
4416 yaffs_FindOrCreateObjectByNumber(dev, objId,
4417 YAFFS_OBJECT_TYPE_FILE);
4418 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4419 obj->variant.fileVariant.shrinkSize = 0;
4420 obj->valid = 1; /* So that we don't read any other info for this file */
4430 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4437 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4439 in = yaffs_FindObjectByNumber(dev,
4440 hl->variant.hardLinkVariant.
4441 equivalentObjectId);
4444 /* Add the hardlink pointers */
4445 hl->variant.hardLinkVariant.equivalentObject = in;
4446 list_add(&hl->hardLinks, &in->hardLinks);
4448 /* Todo Need to report/handle this better.
4449 * Got a problem... hardlink to a non-existant object
4451 hl->variant.hardLinkVariant.equivalentObject = NULL;
4452 INIT_LIST_HEAD(&hl->hardLinks);
4464 static int ybicmp(const void *a, const void *b){
4465 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4466 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4467 register int ablock = ((yaffs_BlockIndex *)a)->block;
4468 register int bblock = ((yaffs_BlockIndex *)b)->block;
4470 return ablock - bblock;
4476 static int yaffs_Scan(yaffs_Device * dev)
4478 yaffs_ExtendedTags tags;
4483 int nBlocksToScan = 0;
4488 yaffs_BlockState state;
4489 yaffs_Object *hardList = NULL;
4491 yaffs_BlockInfo *bi;
4493 yaffs_ObjectHeader *oh;
4495 yaffs_Object *parent;
4496 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4500 yaffs_BlockIndex *blockIndex = NULL;
4502 if (dev->isYaffs2) {
4504 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4508 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4511 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4512 dev->internalStartBlock, dev->internalEndBlock));
4514 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4516 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4518 if (dev->isYaffs2) {
4519 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4522 /* Scan all the blocks to determine their state */
4523 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4524 bi = yaffs_GetBlockInfo(dev, blk);
4525 yaffs_ClearChunkBits(dev, blk);
4527 bi->softDeletions = 0;
4529 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4531 bi->blockState = state;
4532 bi->sequenceNumber = sequenceNumber;
4534 T(YAFFS_TRACE_SCAN_DEBUG,
4535 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4536 state, sequenceNumber));
4538 if (state == YAFFS_BLOCK_STATE_DEAD) {
4539 T(YAFFS_TRACE_BAD_BLOCKS,
4540 (TSTR("block %d is bad" TENDSTR), blk));
4541 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4542 T(YAFFS_TRACE_SCAN_DEBUG,
4543 (TSTR("Block empty " TENDSTR)));
4544 dev->nErasedBlocks++;
4545 dev->nFreeChunks += dev->nChunksPerBlock;
4546 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4548 /* Determine the highest sequence number */
4549 if (dev->isYaffs2 &&
4550 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4551 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4553 blockIndex[nBlocksToScan].seq = sequenceNumber;
4554 blockIndex[nBlocksToScan].block = blk;
4558 if (sequenceNumber >= dev->sequenceNumber) {
4559 dev->sequenceNumber = sequenceNumber;
4561 } else if (dev->isYaffs2) {
4562 /* TODO: Nasty sequence number! */
4565 ("Block scanning block %d has bad sequence number %d"
4566 TENDSTR), blk, sequenceNumber));
4573 * Dungy old bubble sort for now...
4575 if (dev->isYaffs2) {
4576 yaffs_BlockIndex temp;
4580 for (i = 0; i < nBlocksToScan; i++)
4581 for (j = i + 1; j < nBlocksToScan; j++)
4582 if (blockIndex[i].seq > blockIndex[j].seq) {
4583 temp = blockIndex[j];
4584 blockIndex[j] = blockIndex[i];
4585 blockIndex[i] = temp;
4589 /* Now scan the blocks looking at the data. */
4590 if (dev->isYaffs2) {
4592 endIterator = nBlocksToScan - 1;
4593 T(YAFFS_TRACE_SCAN_DEBUG,
4594 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4596 startIterator = dev->internalStartBlock;
4597 endIterator = dev->internalEndBlock;
4600 /* For each block.... */
4601 for (blockIterator = startIterator; blockIterator <= endIterator;
4604 if (dev->isYaffs2) {
4605 /* get the block to scan in the correct order */
4606 blk = blockIndex[blockIterator].block;
4608 blk = blockIterator;
4611 bi = yaffs_GetBlockInfo(dev, blk);
4612 state = bi->blockState;
4616 /* For each chunk in each block that needs scanning....*/
4617 for (c = 0; c < dev->nChunksPerBlock &&
4618 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4619 /* Read the tags and decide what to do */
4620 chunk = blk * dev->nChunksPerBlock + c;
4622 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4625 /* Let's have a good look at this chunk... */
4627 if (!dev->isYaffs2 && tags.chunkDeleted) {
4633 /*T((" %d %d deleted\n",blk,c)); */
4634 } else if (!tags.chunkUsed) {
4635 /* An unassigned chunk in the block
4636 * This means that either the block is empty or
4637 * this is the one being allocated from
4641 /* We're looking at the first chunk in the block so the block is unused */
4642 state = YAFFS_BLOCK_STATE_EMPTY;
4643 dev->nErasedBlocks++;
4645 /* this is the block being allocated from */
4648 (" Allocating from %d %d" TENDSTR),
4650 state = YAFFS_BLOCK_STATE_ALLOCATING;
4651 dev->allocationBlock = blk;
4652 dev->allocationPage = c;
4653 dev->allocationBlockFinder = blk;
4654 /* Set it to here to encourage the allocator to go forth from here. */
4656 /* Yaffs2 sanity check:
4657 * This should be the one with the highest sequence number
4660 && (dev->sequenceNumber !=
4661 bi->sequenceNumber)) {
4662 T(YAFFS_TRACE_ALWAYS,
4664 ("yaffs: Allocation block %d was not highest sequence id:"
4665 " block seq = %d, dev seq = %d"
4666 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4670 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4671 } else if (tags.chunkId > 0) {
4672 /* chunkId > 0 so it is a data chunk... */
4673 unsigned int endpos;
4675 yaffs_SetChunkBit(dev, blk, c);
4678 in = yaffs_FindOrCreateObjectByNumber(dev,
4681 YAFFS_OBJECT_TYPE_FILE);
4682 /* PutChunkIntoFile checks for a clash (two data chunks with
4683 * the same chunkId).
4685 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4688 (tags.chunkId - 1) * dev->nBytesPerChunk +
4690 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4691 && in->variant.fileVariant.scannedFileSize <
4693 in->variant.fileVariant.
4694 scannedFileSize = endpos;
4695 if (!dev->useHeaderFileSize) {
4696 in->variant.fileVariant.
4698 in->variant.fileVariant.
4703 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4705 /* chunkId == 0, so it is an ObjectHeader.
4706 * Thus, we read in the object header and make the object
4708 yaffs_SetChunkBit(dev, blk, c);
4711 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4715 oh = (yaffs_ObjectHeader *) chunkData;
4717 in = yaffs_FindObjectByNumber(dev,
4719 if (in && in->variantType != oh->type) {
4720 /* This should not happen, but somehow
4721 * Wev'e ended up with an objectId that has been reused but not yet
4722 * deleted, and worse still it has changed type. Delete the old object.
4725 yaffs_DestroyObject(in);
4730 in = yaffs_FindOrCreateObjectByNumber(dev,
4735 if (oh->shadowsObject > 0) {
4736 yaffs_HandleShadowedObject(dev,
4743 /* We have already filled this one. We have a duplicate and need to resolve it. */
4745 unsigned existingSerial = in->serial;
4746 unsigned newSerial = tags.serialNumber;
4748 if (dev->isYaffs2 ||
4749 ((existingSerial + 1) & 3) ==
4751 /* Use new one - destroy the exisiting one */
4752 yaffs_DeleteChunk(dev,
4757 /* Use existing - destroy this one. */
4758 yaffs_DeleteChunk(dev, chunk, 1,
4764 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4765 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4766 /* We only load some info, don't fiddle with directory structure */
4768 in->variantType = oh->type;
4770 in->yst_mode = oh->yst_mode;
4771 #ifdef CONFIG_YAFFS_WINCE
4772 in->win_atime[0] = oh->win_atime[0];
4773 in->win_ctime[0] = oh->win_ctime[0];
4774 in->win_mtime[0] = oh->win_mtime[0];
4775 in->win_atime[1] = oh->win_atime[1];
4776 in->win_ctime[1] = oh->win_ctime[1];
4777 in->win_mtime[1] = oh->win_mtime[1];
4779 in->yst_uid = oh->yst_uid;
4780 in->yst_gid = oh->yst_gid;
4781 in->yst_atime = oh->yst_atime;
4782 in->yst_mtime = oh->yst_mtime;
4783 in->yst_ctime = oh->yst_ctime;
4784 in->yst_rdev = oh->yst_rdev;
4786 in->chunkId = chunk;
4788 } else if (!in->valid) {
4789 /* we need to load this info */
4792 in->variantType = oh->type;
4794 in->yst_mode = oh->yst_mode;
4795 #ifdef CONFIG_YAFFS_WINCE
4796 in->win_atime[0] = oh->win_atime[0];
4797 in->win_ctime[0] = oh->win_ctime[0];
4798 in->win_mtime[0] = oh->win_mtime[0];
4799 in->win_atime[1] = oh->win_atime[1];
4800 in->win_ctime[1] = oh->win_ctime[1];
4801 in->win_mtime[1] = oh->win_mtime[1];
4803 in->yst_uid = oh->yst_uid;
4804 in->yst_gid = oh->yst_gid;
4805 in->yst_atime = oh->yst_atime;
4806 in->yst_mtime = oh->yst_mtime;
4807 in->yst_ctime = oh->yst_ctime;
4808 in->yst_rdev = oh->yst_rdev;
4810 in->chunkId = chunk;
4812 yaffs_SetObjectName(in, oh->name);
4815 /* directory stuff...
4820 yaffs_FindOrCreateObjectByNumber
4821 (dev, oh->parentObjectId,
4822 YAFFS_OBJECT_TYPE_DIRECTORY);
4823 if (parent->variantType ==
4824 YAFFS_OBJECT_TYPE_UNKNOWN) {
4825 /* Set up as a directory */
4826 parent->variantType =
4827 YAFFS_OBJECT_TYPE_DIRECTORY;
4828 INIT_LIST_HEAD(&parent->variant.
4831 } else if (parent->variantType !=
4832 YAFFS_OBJECT_TYPE_DIRECTORY)
4834 /* Hoosterman, another problem....
4835 * We're trying to use a non-directory as a directory
4838 T(YAFFS_TRACE_ERROR,
4840 ("yaffs tragedy: attempting to use non-directory as"
4841 " a directory in scan. Put in lost+found."
4843 parent = dev->lostNFoundDir;
4846 yaffs_AddObjectToDirectory(parent, in);
4848 if (0 && (parent == dev->deletedDir ||
4849 parent == dev->unlinkedDir)) {
4850 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
4851 dev->nDeletedFiles++;
4853 /* Note re hardlinks.
4854 * Since we might scan a hardlink before its equivalent object is scanned
4855 * we put them all in a list.
4856 * After scanning is complete, we should have all the objects, so we run through this
4857 * list and fix up all the chains.
4860 switch (in->variantType) {
4861 case YAFFS_OBJECT_TYPE_UNKNOWN:
4862 /* Todo got a problem */
4864 case YAFFS_OBJECT_TYPE_FILE:
4867 /* Prune back the shrunken chunks */
4868 yaffs_PruneResizedChunks
4870 /* Mark the block as having a shrinkHeader */
4871 bi->hasShrinkHeader = 1;
4874 if (dev->useHeaderFileSize)
4876 in->variant.fileVariant.
4881 case YAFFS_OBJECT_TYPE_HARDLINK:
4882 in->variant.hardLinkVariant.
4883 equivalentObjectId =
4884 oh->equivalentObjectId;
4885 in->hardLinks.next =
4886 (struct list_head *)
4890 case YAFFS_OBJECT_TYPE_DIRECTORY:
4893 case YAFFS_OBJECT_TYPE_SPECIAL:
4896 case YAFFS_OBJECT_TYPE_SYMLINK:
4897 in->variant.symLinkVariant.
4899 yaffs_CloneString(oh->alias);
4903 if (parent == dev->deletedDir) {
4904 yaffs_DestroyObject(in);
4905 bi->hasShrinkHeader = 1;
4911 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4912 /* If we got this far while scanning, then the block is fully allocated.*/
4913 state = YAFFS_BLOCK_STATE_FULL;
4916 bi->blockState = state;
4918 /* Now let's see if it was dirty */
4919 if (bi->pagesInUse == 0 &&
4920 !bi->hasShrinkHeader &&
4921 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4922 yaffs_BlockBecameDirty(dev, blk);
4932 /* Ok, we've done all the scanning.
4933 * Fix up the hard link chains.
4934 * We should now have scanned all the objects, now it's time to add these
4938 yaffs_HardlinkFixup(dev,hardList);
4940 /* Handle the unlinked files. Since they were left in an unlinked state we should
4944 struct list_head *i;
4945 struct list_head *n;
4948 /* Soft delete all the unlinked files */
4949 list_for_each_safe(i, n,
4950 &dev->unlinkedDir->variant.directoryVariant.
4953 l = list_entry(i, yaffs_Object, siblings);
4954 yaffs_DestroyObject(l);
4959 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4961 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4966 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4969 yaffs_ObjectHeader *oh;
4970 yaffs_Device *dev = in->myDev;
4974 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4976 yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,NULL);
4977 oh = (yaffs_ObjectHeader *) chunkData;
4979 in->yst_mode = oh->yst_mode;
4980 #ifdef CONFIG_YAFFS_WINCE
4981 in->win_atime[0] = oh->win_atime[0];
4982 in->win_ctime[0] = oh->win_ctime[0];
4983 in->win_mtime[0] = oh->win_mtime[0];
4984 in->win_atime[1] = oh->win_atime[1];
4985 in->win_ctime[1] = oh->win_ctime[1];
4986 in->win_mtime[1] = oh->win_mtime[1];
4988 in->yst_uid = oh->yst_uid;
4989 in->yst_gid = oh->yst_gid;
4990 in->yst_atime = oh->yst_atime;
4991 in->yst_mtime = oh->yst_mtime;
4992 in->yst_ctime = oh->yst_ctime;
4993 in->yst_rdev = oh->yst_rdev;
4996 yaffs_SetObjectName(in, oh->name);
4998 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4999 in->variant.symLinkVariant.alias =
5000 yaffs_CloneString(oh->alias);
5002 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5006 static int yaffs_ScanBackwards(yaffs_Device * dev)
5008 yaffs_ExtendedTags tags;
5013 int nBlocksToScan = 0;
5018 yaffs_BlockState state;
5019 yaffs_Object *hardList = NULL;
5020 yaffs_BlockInfo *bi;
5022 yaffs_ObjectHeader *oh;
5024 yaffs_Object *parent;
5025 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5031 int equivalentObjectId;
5034 yaffs_BlockIndex *blockIndex = NULL;
5035 int altBlockIndex = 0;
5037 if (!dev->isYaffs2) {
5039 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5045 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5046 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5049 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5051 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5054 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5060 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5064 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5066 /* Scan all the blocks to determine their state */
5067 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5068 bi = yaffs_GetBlockInfo(dev, blk);
5069 yaffs_ClearChunkBits(dev, blk);
5071 bi->softDeletions = 0;
5073 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5075 bi->blockState = state;
5076 bi->sequenceNumber = sequenceNumber;
5078 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5079 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5081 T(YAFFS_TRACE_SCAN_DEBUG,
5082 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5083 state, sequenceNumber));
5086 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5087 /* todo .. fix free space ? */
5089 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5090 T(YAFFS_TRACE_BAD_BLOCKS,
5091 (TSTR("block %d is bad" TENDSTR), blk));
5092 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5093 T(YAFFS_TRACE_SCAN_DEBUG,
5094 (TSTR("Block empty " TENDSTR)));
5095 dev->nErasedBlocks++;
5096 dev->nFreeChunks += dev->nChunksPerBlock;
5097 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5099 /* Determine the highest sequence number */
5100 if (dev->isYaffs2 &&
5101 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5102 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5104 blockIndex[nBlocksToScan].seq = sequenceNumber;
5105 blockIndex[nBlocksToScan].block = blk;
5109 if (sequenceNumber >= dev->sequenceNumber) {
5110 dev->sequenceNumber = sequenceNumber;
5112 } else if (dev->isYaffs2) {
5113 /* TODO: Nasty sequence number! */
5116 ("Block scanning block %d has bad sequence number %d"
5117 TENDSTR), blk, sequenceNumber));
5124 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5130 /* Sort the blocks */
5131 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5133 /* Use qsort now. */
5134 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5138 /* Dungy old bubble sort... */
5140 yaffs_BlockIndex temp;
5144 for (i = 0; i < nBlocksToScan; i++)
5145 for (j = i + 1; j < nBlocksToScan; j++)
5146 if (blockIndex[i].seq > blockIndex[j].seq) {
5147 temp = blockIndex[j];
5148 blockIndex[j] = blockIndex[i];
5149 blockIndex[i] = temp;
5156 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5158 /* Now scan the blocks looking at the data. */
5160 endIterator = nBlocksToScan - 1;
5161 T(YAFFS_TRACE_SCAN_DEBUG,
5162 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5164 /* For each block.... backwards */
5165 for (blockIterator = endIterator; blockIterator >= startIterator;
5167 /* Cooperative multitasking! This loop can run for so
5168 long that watchdog timers expire. */
5171 /* get the block to scan in the correct order */
5172 blk = blockIndex[blockIterator].block;
5174 bi = yaffs_GetBlockInfo(dev, blk);
5175 state = bi->blockState;
5179 /* For each chunk in each block that needs scanning.... */
5180 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5181 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5182 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5183 /* Scan backwards...
5184 * Read the tags and decide what to do
5186 chunk = blk * dev->nChunksPerBlock + c;
5188 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5191 /* Let's have a good look at this chunk... */
5193 if (!tags.chunkUsed) {
5194 // An unassigned chunk in the block
5195 // This means that either the block is empty or
5196 // this is the one being allocated from
5199 /* We're looking at the first chunk in the block so the block is unused */
5200 state = YAFFS_BLOCK_STATE_EMPTY;
5201 dev->nErasedBlocks++;
5203 /* this is the block being allocated from */
5205 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5208 (" Allocating from %d %d"
5211 state = YAFFS_BLOCK_STATE_ALLOCATING;
5212 dev->allocationBlock = blk;
5213 dev->allocationPage = c;
5214 dev->allocationBlockFinder = blk;
5215 /* Set it to here to encourage the allocator to
5216 * go forth from here.
5219 /* Yaffs2 sanity check:
5220 * This should be the one with the highest sequence number
5223 && (dev->sequenceNumber !=
5224 bi->sequenceNumber)) {
5225 T(YAFFS_TRACE_ALWAYS,
5227 ("yaffs: Allocation block %d was not highest sequence "
5228 "id: block seq = %d, dev seq = %d"
5231 dev->sequenceNumber));
5236 } else if (tags.chunkId > 0) {
5237 /* chunkId > 0 so it is a data chunk... */
5238 unsigned int endpos;
5241 (tags.chunkId - 1) * dev->nBytesPerChunk;
5243 yaffs_SetChunkBit(dev, blk, c);
5246 in = yaffs_FindOrCreateObjectByNumber(dev,
5249 YAFFS_OBJECT_TYPE_FILE);
5250 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5252 in->variant.fileVariant.shrinkSize) {
5253 /* This has not been invalidated by a resize */
5254 yaffs_PutChunkIntoFile(in, tags.chunkId,
5257 /* File size is calculated by looking at the data chunks if we have not
5258 * seen an object header yet. Stop this practice once we find an object header.
5262 1) * dev->nBytesPerChunk +
5265 if (!in->valid && /* have not got an object header yet */
5266 in->variant.fileVariant.
5267 scannedFileSize < endpos) {
5268 in->variant.fileVariant.
5269 scannedFileSize = endpos;
5270 in->variant.fileVariant.
5272 in->variant.fileVariant.
5277 /* This chunk has been invalidated by a resize, so delete */
5278 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5282 /* chunkId == 0, so it is an ObjectHeader.
5283 * Thus, we read in the object header and make the object
5285 yaffs_SetChunkBit(dev, blk, c);
5291 if (tags.extraHeaderInfoAvailable) {
5292 in = yaffs_FindOrCreateObjectByNumber
5293 (dev, tags.objectId,
5294 tags.extraObjectType);
5298 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5301 tags.extraShadows ||
5303 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5304 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5307 /* If we don't have valid info then we need to read the chunk
5308 * TODO In future we can probably defer reading the chunk and
5309 * living with invalid data until needed.
5312 yaffs_ReadChunkWithTagsFromNAND(dev,
5317 oh = (yaffs_ObjectHeader *) chunkData;
5320 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5325 /* TODO Hoosterman we have a problem! */
5326 T(YAFFS_TRACE_ERROR,
5328 ("yaffs tragedy: Could not make object for object %d "
5329 "at chunk %d during scan"
5330 TENDSTR), tags.objectId, chunk));
5335 /* We have already filled this one.
5336 * We have a duplicate that will be discarded, but
5337 * we first have to suck out resize info if it is a file.
5340 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5342 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5343 (tags.extraHeaderInfoAvailable &&
5344 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5347 (oh) ? oh->fileSize : tags.
5349 __u32 parentObjectId =
5351 parentObjectId : tags.
5352 extraParentObjectId;
5354 (oh) ? oh->isShrink : tags.
5355 extraIsShrinkHeader;
5357 /* If it is deleted (unlinked at start also means deleted)
5358 * we treat the file size as being zeroed at this point.
5360 if (parentObjectId ==
5361 YAFFS_OBJECTID_DELETED
5362 || parentObjectId ==
5363 YAFFS_OBJECTID_UNLINKED) {
5369 in->variant.fileVariant.
5370 shrinkSize > thisSize) {
5371 in->variant.fileVariant.
5377 bi->hasShrinkHeader = 1;
5381 /* Use existing - destroy this one. */
5382 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5387 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5389 YAFFS_OBJECTID_LOSTNFOUND)) {
5390 /* We only load some info, don't fiddle with directory structure */
5394 in->variantType = oh->type;
5396 in->yst_mode = oh->yst_mode;
5397 #ifdef CONFIG_YAFFS_WINCE
5398 in->win_atime[0] = oh->win_atime[0];
5399 in->win_ctime[0] = oh->win_ctime[0];
5400 in->win_mtime[0] = oh->win_mtime[0];
5401 in->win_atime[1] = oh->win_atime[1];
5402 in->win_ctime[1] = oh->win_ctime[1];
5403 in->win_mtime[1] = oh->win_mtime[1];
5405 in->yst_uid = oh->yst_uid;
5406 in->yst_gid = oh->yst_gid;
5407 in->yst_atime = oh->yst_atime;
5408 in->yst_mtime = oh->yst_mtime;
5409 in->yst_ctime = oh->yst_ctime;
5410 in->yst_rdev = oh->yst_rdev;
5414 in->variantType = tags.extraObjectType;
5418 in->chunkId = chunk;
5420 } else if (!in->valid) {
5421 /* we need to load this info */
5424 in->chunkId = chunk;
5427 in->variantType = oh->type;
5429 in->yst_mode = oh->yst_mode;
5430 #ifdef CONFIG_YAFFS_WINCE
5431 in->win_atime[0] = oh->win_atime[0];
5432 in->win_ctime[0] = oh->win_ctime[0];
5433 in->win_mtime[0] = oh->win_mtime[0];
5434 in->win_atime[1] = oh->win_atime[1];
5435 in->win_ctime[1] = oh->win_ctime[1];
5436 in->win_mtime[1] = oh->win_mtime[1];
5438 in->yst_uid = oh->yst_uid;
5439 in->yst_gid = oh->yst_gid;
5440 in->yst_atime = oh->yst_atime;
5441 in->yst_mtime = oh->yst_mtime;
5442 in->yst_ctime = oh->yst_ctime;
5443 in->yst_rdev = oh->yst_rdev;
5446 if (oh->shadowsObject > 0)
5447 yaffs_HandleShadowedObject(dev,
5453 yaffs_SetObjectName(in, oh->name);
5455 yaffs_FindOrCreateObjectByNumber
5456 (dev, oh->parentObjectId,
5457 YAFFS_OBJECT_TYPE_DIRECTORY);
5459 fileSize = oh->fileSize;
5460 isShrink = oh->isShrink;
5461 equivalentObjectId = oh->equivalentObjectId;
5465 in->variantType = tags.extraObjectType;
5467 yaffs_FindOrCreateObjectByNumber
5468 (dev, tags.extraParentObjectId,
5469 YAFFS_OBJECT_TYPE_DIRECTORY);
5470 fileSize = tags.extraFileLength;
5471 isShrink = tags.extraIsShrinkHeader;
5472 equivalentObjectId = tags.extraEquivalentObjectId;
5478 /* directory stuff...
5482 if (parent->variantType ==
5483 YAFFS_OBJECT_TYPE_UNKNOWN) {
5484 /* Set up as a directory */
5485 parent->variantType =
5486 YAFFS_OBJECT_TYPE_DIRECTORY;
5487 INIT_LIST_HEAD(&parent->variant.
5490 } else if (parent->variantType !=
5491 YAFFS_OBJECT_TYPE_DIRECTORY)
5493 /* Hoosterman, another problem....
5494 * We're trying to use a non-directory as a directory
5497 T(YAFFS_TRACE_ERROR,
5499 ("yaffs tragedy: attempting to use non-directory as"
5500 " a directory in scan. Put in lost+found."
5502 parent = dev->lostNFoundDir;
5505 yaffs_AddObjectToDirectory(parent, in);
5507 itsUnlinked = (parent == dev->deletedDir) ||
5508 (parent == dev->unlinkedDir);
5511 /* Mark the block as having a shrinkHeader */
5512 bi->hasShrinkHeader = 1;
5515 /* Note re hardlinks.
5516 * Since we might scan a hardlink before its equivalent object is scanned
5517 * we put them all in a list.
5518 * After scanning is complete, we should have all the objects, so we run
5519 * through this list and fix up all the chains.
5522 switch (in->variantType) {
5523 case YAFFS_OBJECT_TYPE_UNKNOWN:
5524 /* Todo got a problem */
5526 case YAFFS_OBJECT_TYPE_FILE:
5528 if (in->variant.fileVariant.
5529 scannedFileSize < fileSize) {
5530 /* This covers the case where the file size is greater
5531 * than where the data is
5532 * This will happen if the file is resized to be larger
5533 * than its current data extents.
5535 in->variant.fileVariant.fileSize = fileSize;
5536 in->variant.fileVariant.scannedFileSize =
5537 in->variant.fileVariant.fileSize;
5541 in->variant.fileVariant.shrinkSize > fileSize) {
5542 in->variant.fileVariant.shrinkSize = fileSize;
5546 case YAFFS_OBJECT_TYPE_HARDLINK:
5548 in->variant.hardLinkVariant.equivalentObjectId =
5550 in->hardLinks.next =
5551 (struct list_head *) hardList;
5555 case YAFFS_OBJECT_TYPE_DIRECTORY:
5558 case YAFFS_OBJECT_TYPE_SPECIAL:
5561 case YAFFS_OBJECT_TYPE_SYMLINK:
5563 in->variant.symLinkVariant.alias =
5564 yaffs_CloneString(oh->
5573 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5574 /* If we got this far while scanning, then the block is fully allocated. */
5575 state = YAFFS_BLOCK_STATE_FULL;
5578 bi->blockState = state;
5580 /* Now let's see if it was dirty */
5581 if (bi->pagesInUse == 0 &&
5582 !bi->hasShrinkHeader &&
5583 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5584 yaffs_BlockBecameDirty(dev, blk);
5590 YFREE_ALT(blockIndex);
5594 /* Ok, we've done all the scanning.
5595 * Fix up the hard link chains.
5596 * We should now have scanned all the objects, now it's time to add these
5599 yaffs_HardlinkFixup(dev,hardList);
5603 * Sort out state of unlinked and deleted objects.
5606 struct list_head *i;
5607 struct list_head *n;
5611 /* Soft delete all the unlinked files */
5612 list_for_each_safe(i, n,
5613 &dev->unlinkedDir->variant.directoryVariant.
5616 l = list_entry(i, yaffs_Object, siblings);
5617 yaffs_DestroyObject(l);
5621 /* Soft delete all the deletedDir files */
5622 list_for_each_safe(i, n,
5623 &dev->deletedDir->variant.directoryVariant.
5626 l = list_entry(i, yaffs_Object, siblings);
5627 yaffs_DestroyObject(l);
5633 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5635 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5640 /*------------------------------ Directory Functions ----------------------------- */
5642 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5644 yaffs_Device *dev = obj->myDev;
5646 if(dev && dev->removeObjectCallback)
5647 dev->removeObjectCallback(obj);
5649 list_del_init(&obj->siblings);
5654 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5659 T(YAFFS_TRACE_ALWAYS,
5661 ("tragedy: Trying to add an object to a null pointer directory"
5665 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5666 T(YAFFS_TRACE_ALWAYS,
5668 ("tragedy: Trying to add an object to a non-directory"
5673 if (obj->siblings.prev == NULL) {
5674 /* Not initialised */
5675 INIT_LIST_HEAD(&obj->siblings);
5677 } else if (!list_empty(&obj->siblings)) {
5678 /* If it is holed up somewhere else, un hook it */
5679 yaffs_RemoveObjectFromDirectory(obj);
5682 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5683 obj->parent = directory;
5685 if (directory == obj->myDev->unlinkedDir
5686 || directory == obj->myDev->deletedDir) {
5688 obj->myDev->nUnlinkedFiles++;
5689 obj->renameAllowed = 0;
5693 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5698 struct list_head *i;
5699 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5708 T(YAFFS_TRACE_ALWAYS,
5710 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5714 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5715 T(YAFFS_TRACE_ALWAYS,
5717 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5721 sum = yaffs_CalcNameSum(name);
5723 list_for_each(i, &directory->variant.directoryVariant.children) {
5725 l = list_entry(i, yaffs_Object, siblings);
5727 yaffs_CheckObjectDetailsLoaded(l);
5729 /* Special case for lost-n-found */
5730 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5731 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5734 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5736 /* LostnFound cunk called Objxxx
5739 yaffs_GetObjectName(l, buffer,
5740 YAFFS_MAX_NAME_LENGTH);
5741 if (yaffs_strcmp(name, buffer) == 0) {
5754 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5755 int (*fn) (yaffs_Object *))
5757 struct list_head *i;
5761 T(YAFFS_TRACE_ALWAYS,
5763 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5767 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5768 T(YAFFS_TRACE_ALWAYS,
5770 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5774 list_for_each(i, &theDir->variant.directoryVariant.children) {
5776 l = list_entry(i, yaffs_Object, siblings);
5788 /* GetEquivalentObject dereferences any hard links to get to the
5792 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5794 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5795 /* We want the object id of the equivalent object, not this one */
5796 obj = obj->variant.hardLinkVariant.equivalentObject;
5802 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5804 memset(name, 0, buffSize * sizeof(YCHAR));
5806 yaffs_CheckObjectDetailsLoaded(obj);
5808 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5809 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5810 } else if (obj->chunkId <= 0) {
5812 /* make up a name */
5813 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5815 yaffs_strncpy(name, locName, buffSize - 1);
5818 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5819 else if (obj->shortName[0]) {
5820 yaffs_strcpy(name, obj->shortName);
5824 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5826 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5828 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5830 if (obj->chunkId >= 0) {
5831 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5832 obj->chunkId, buffer,
5835 yaffs_strncpy(name, oh->name, buffSize - 1);
5837 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5840 return yaffs_strlen(name);
5843 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5846 /* Dereference any hard linking */
5847 obj = yaffs_GetEquivalentObject(obj);
5849 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5850 return obj->variant.fileVariant.fileSize;
5852 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5853 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5855 /* Only a directory should drop through to here */
5856 return obj->myDev->nBytesPerChunk;
5860 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5863 struct list_head *i;
5865 if (!obj->unlinked) {
5866 count++; /* the object itself */
5868 list_for_each(i, &obj->hardLinks) {
5869 count++; /* add the hard links; */
5875 int yaffs_GetObjectInode(yaffs_Object * obj)
5877 obj = yaffs_GetEquivalentObject(obj);
5879 return obj->objectId;
5882 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5884 obj = yaffs_GetEquivalentObject(obj);
5886 switch (obj->variantType) {
5887 case YAFFS_OBJECT_TYPE_FILE:
5890 case YAFFS_OBJECT_TYPE_DIRECTORY:
5893 case YAFFS_OBJECT_TYPE_SYMLINK:
5896 case YAFFS_OBJECT_TYPE_HARDLINK:
5899 case YAFFS_OBJECT_TYPE_SPECIAL:
5900 if (S_ISFIFO(obj->yst_mode))
5902 if (S_ISCHR(obj->yst_mode))
5904 if (S_ISBLK(obj->yst_mode))
5906 if (S_ISSOCK(obj->yst_mode))
5914 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5916 obj = yaffs_GetEquivalentObject(obj);
5917 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5918 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5920 return yaffs_CloneString(_Y(""));
5924 #ifndef CONFIG_YAFFS_WINCE
5926 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5928 unsigned int valid = attr->ia_valid;
5930 if (valid & ATTR_MODE)
5931 obj->yst_mode = attr->ia_mode;
5932 if (valid & ATTR_UID)
5933 obj->yst_uid = attr->ia_uid;
5934 if (valid & ATTR_GID)
5935 obj->yst_gid = attr->ia_gid;
5937 if (valid & ATTR_ATIME)
5938 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5939 if (valid & ATTR_CTIME)
5940 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5941 if (valid & ATTR_MTIME)
5942 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5944 if (valid & ATTR_SIZE)
5945 yaffs_ResizeFile(obj, attr->ia_size);
5947 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5952 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5954 unsigned int valid = 0;
5956 attr->ia_mode = obj->yst_mode;
5958 attr->ia_uid = obj->yst_uid;
5960 attr->ia_gid = obj->yst_gid;
5963 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5964 valid |= ATTR_ATIME;
5965 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5966 valid |= ATTR_CTIME;
5967 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5968 valid |= ATTR_MTIME;
5970 attr->ia_size = yaffs_GetFileSize(obj);
5973 attr->ia_valid = valid;
5982 int yaffs_DumpObject(yaffs_Object * obj)
5986 yaffs_GetObjectName(obj, name, 256);
5988 T(YAFFS_TRACE_ALWAYS,
5990 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5991 " chunk %d type %d size %d\n"
5992 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5993 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5994 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6000 /*---------------------------- Initialisation code -------------------------------------- */
6002 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6005 /* Common functions, gotta have */
6006 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6009 #ifdef CONFIG_YAFFS_YAFFS2
6011 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6012 if (dev->writeChunkWithTagsToNAND &&
6013 dev->readChunkWithTagsFromNAND &&
6014 !dev->writeChunkToNAND &&
6015 !dev->readChunkFromNAND &&
6016 dev->markNANDBlockBad && dev->queryNANDBlock)
6020 /* Can use the "spare" style interface for yaffs1 */
6021 if (!dev->isYaffs2 &&
6022 !dev->writeChunkWithTagsToNAND &&
6023 !dev->readChunkWithTagsFromNAND &&
6024 dev->writeChunkToNAND &&
6025 dev->readChunkFromNAND &&
6026 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6033 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6035 /* Initialise the unlinked, deleted, root and lost and found directories */
6037 dev->lostNFoundDir = dev->rootDir = NULL;
6038 dev->unlinkedDir = dev->deletedDir = NULL;
6041 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6043 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6046 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6047 YAFFS_ROOT_MODE | S_IFDIR);
6048 dev->lostNFoundDir =
6049 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6050 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6051 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6054 int yaffs_GutsInitialise(yaffs_Device * dev)
6060 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6062 /* Check stuff that must be set */
6065 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6069 dev->internalStartBlock = dev->startBlock;
6070 dev->internalEndBlock = dev->endBlock;
6071 dev->blockOffset = 0;
6072 dev->chunkOffset = 0;
6073 dev->nFreeChunks = 0;
6075 if (dev->startBlock == 0) {
6076 dev->internalStartBlock = dev->startBlock + 1;
6077 dev->internalEndBlock = dev->endBlock + 1;
6078 dev->blockOffset = 1;
6079 dev->chunkOffset = dev->nChunksPerBlock;
6082 /* Check geometry parameters. */
6084 if ((dev->isYaffs2 && dev->nBytesPerChunk < 1024) ||
6085 (!dev->isYaffs2 && dev->nBytesPerChunk != 512) ||
6086 dev->nChunksPerBlock < 2 ||
6087 dev->nReservedBlocks < 2 ||
6088 dev->internalStartBlock <= 0 ||
6089 dev->internalEndBlock <= 0 ||
6090 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6092 T(YAFFS_TRACE_ALWAYS,
6094 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6095 TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6099 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6100 T(YAFFS_TRACE_ALWAYS,
6101 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6105 /* Got the right mix of functions? */
6106 if (!yaffs_CheckDevFunctions(dev)) {
6107 /* Function missing */
6108 T(YAFFS_TRACE_ALWAYS,
6110 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6115 /* This is really a compilation check. */
6116 if (!yaffs_CheckStructures()) {
6117 T(YAFFS_TRACE_ALWAYS,
6118 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6122 if (dev->isMounted) {
6123 T(YAFFS_TRACE_ALWAYS,
6124 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6128 /* Finished with most checks. One or two more checks happen later on too. */
6134 /* OK now calculate a few things for the device
6135 * Calculate chunkGroupBits.
6136 * We need to find the next power of 2 > than internalEndBlock
6139 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6141 for (bits = extraBits = 0; x > 1; bits++) {
6150 /* Set up tnode width if wide tnodes are enabled. */
6151 if(!dev->wideTnodesDisabled){
6152 /* bits must be even so that we end up with 32-bit words */
6156 dev->tnodeWidth = 16;
6158 dev->tnodeWidth = bits;
6161 dev->tnodeWidth = 16;
6163 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6165 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6166 * so if the bitwidth of the
6167 * chunk range we're using is greater than 16 we need
6168 * to figure out chunk shift and chunkGroupSize
6171 if (bits <= dev->tnodeWidth)
6172 dev->chunkGroupBits = 0;
6174 dev->chunkGroupBits = bits - dev->tnodeWidth;
6177 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6179 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6180 /* We have a problem because the soft delete won't work if
6181 * the chunk group size > chunks per block.
6182 * This can be remedied by using larger "virtual blocks".
6184 T(YAFFS_TRACE_ALWAYS,
6185 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6190 /* OK, we've finished verifying the device, lets continue with initialisation */
6192 /* More device initialisation */
6193 dev->garbageCollections = 0;
6194 dev->passiveGarbageCollections = 0;
6195 dev->currentDirtyChecker = 0;
6196 dev->bufferedBlock = -1;
6197 dev->doingBufferedBlockRewrite = 0;
6198 dev->nDeletedFiles = 0;
6199 dev->nBackgroundDeletions = 0;
6200 dev->nUnlinkedFiles = 0;
6202 dev->eccUnfixed = 0;
6203 dev->tagsEccFixed = 0;
6204 dev->tagsEccUnfixed = 0;
6205 dev->nErasureFailures = 0;
6206 dev->nErasedBlocks = 0;
6209 /* Initialise temporary buffers and caches. */
6212 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6213 dev->tempBuffer[i].line = 0; /* not in use */
6214 dev->tempBuffer[i].buffer =
6215 YMALLOC_DMA(dev->nBytesPerChunk);
6219 if (dev->nShortOpCaches > 0) {
6222 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6223 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6227 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6229 for (i = 0; i < dev->nShortOpCaches; i++) {
6230 dev->srCache[i].object = NULL;
6231 dev->srCache[i].lastUse = 0;
6232 dev->srCache[i].dirty = 0;
6233 dev->srCache[i].data = YMALLOC_DMA(dev->nBytesPerChunk);
6240 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6242 if (dev->isYaffs2) {
6243 dev->useHeaderFileSize = 1;
6246 yaffs_InitialiseBlocks(dev);
6247 yaffs_InitialiseTnodes(dev);
6248 yaffs_InitialiseObjects(dev);
6250 yaffs_CreateInitialDirectories(dev);
6253 /* Now scan the flash. */
6254 if (dev->isYaffs2) {
6255 if(yaffs_CheckpointRestore(dev)) {
6256 T(YAFFS_TRACE_ALWAYS,
6257 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6260 /* Clean up the mess caused by an aborted checkpoint load
6261 * and scan backwards.
6263 yaffs_DeinitialiseBlocks(dev);
6264 yaffs_DeinitialiseTnodes(dev);
6265 yaffs_DeinitialiseObjects(dev);
6266 yaffs_InitialiseBlocks(dev);
6267 yaffs_InitialiseTnodes(dev);
6268 yaffs_InitialiseObjects(dev);
6269 yaffs_CreateInitialDirectories(dev);
6271 yaffs_ScanBackwards(dev);
6276 /* Zero out stats */
6277 dev->nPageReads = 0;
6278 dev->nPageWrites = 0;
6279 dev->nBlockErasures = 0;
6281 dev->nRetriedWrites = 0;
6283 dev->nRetiredBlocks = 0;
6285 yaffs_VerifyFreeChunks(dev);
6287 T(YAFFS_TRACE_TRACING,
6288 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6293 void yaffs_Deinitialise(yaffs_Device * dev)
6295 if (dev->isMounted) {
6298 yaffs_DeinitialiseBlocks(dev);
6299 yaffs_DeinitialiseTnodes(dev);
6300 yaffs_DeinitialiseObjects(dev);
6301 if (dev->nShortOpCaches > 0) {
6303 for (i = 0; i < dev->nShortOpCaches; i++) {
6304 YFREE(dev->srCache[i].data);
6307 YFREE(dev->srCache);
6310 YFREE(dev->gcCleanupList);
6312 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6313 YFREE(dev->tempBuffer[i].buffer);
6321 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6326 yaffs_BlockInfo *blk;
6328 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6330 blk = yaffs_GetBlockInfo(dev, b);
6332 switch (blk->blockState) {
6333 case YAFFS_BLOCK_STATE_EMPTY:
6334 case YAFFS_BLOCK_STATE_ALLOCATING:
6335 case YAFFS_BLOCK_STATE_COLLECTING:
6336 case YAFFS_BLOCK_STATE_FULL:
6338 (dev->nChunksPerBlock - blk->pagesInUse +
6339 blk->softDeletions);
6350 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6352 /* This is what we report to the outside world */
6355 int nDirtyCacheChunks;
6356 int blocksForCheckpoint;
6359 nFree = dev->nFreeChunks;
6361 nFree = yaffs_CountFreeChunks(dev);
6364 nFree += dev->nDeletedFiles;
6366 /* Now count the number of dirty chunks in the cache and subtract those */
6370 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6371 if (dev->srCache[i].dirty)
6372 nDirtyCacheChunks++;
6376 nFree -= nDirtyCacheChunks;
6378 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6380 /* Now we figure out how much to reserve for the checkpoint and report that... */
6381 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6382 if(blocksForCheckpoint < 0)
6383 blocksForCheckpoint = 0;
6385 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6394 static int yaffs_freeVerificationFailures;
6396 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6398 int counted = yaffs_CountFreeChunks(dev);
6400 int difference = dev->nFreeChunks - counted;
6403 T(YAFFS_TRACE_ALWAYS,
6404 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6405 dev->nFreeChunks, counted, difference));
6406 yaffs_freeVerificationFailures++;
6410 /*---------------------------------------- YAFFS test code ----------------------*/
6412 #define yaffs_CheckStruct(structure,syze, name) \
6413 if(sizeof(structure) != syze) \
6415 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6416 name,syze,sizeof(structure))); \
6417 return YAFFS_FAIL; \
6420 static int yaffs_CheckStructures(void)
6422 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6423 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6424 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6425 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6426 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6428 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")