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.41 2006-11-07 23:26:52 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"
33 #include "yaffs_packedtags2.h"
36 #ifdef CONFIG_YAFFS_WINCE
37 void yfsd_LockYAFFS(BOOL fsLockOnly);
38 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
41 #define YAFFS_PASSIVE_GC_CHUNKS 2
43 #include "yaffs_ecc.h"
46 /* Robustification (if it ever comes about...) */
47 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
48 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
49 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
51 const yaffs_ExtendedTags * tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
53 const yaffs_ExtendedTags * tags);
55 /* Other local prototypes */
56 static int yaffs_UnlinkObject( yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
61 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
63 yaffs_ExtendedTags * tags,
65 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
66 int chunkInNAND, int inScan);
68 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
69 yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
72 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
73 int force, int isShrink, int shadows);
74 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
75 static int yaffs_CheckStructures(void);
76 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
77 int chunkOffset, int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
82 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
83 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
86 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
89 static int yaffs_UnlinkWorker(yaffs_Object * obj);
90 static void yaffs_DestroyObject(yaffs_Object * obj);
92 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
95 loff_t yaffs_GetFileSize(yaffs_Object * obj);
97 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
99 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
101 #ifdef YAFFS_PARANOID
102 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #define yaffs_CheckFileSanity(in)
107 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
108 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
114 /* Function to calculate chunk and offset */
116 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
119 /* Easy-peasy power of 2 case */
120 *chunk = (__u32)(addr >> dev->chunkShift);
121 *offset = (__u32)(addr & dev->chunkMask);
123 else if(dev->crumbsPerChunk)
125 /* Case where we're using "crumbs" */
126 *offset = (__u32)(addr & dev->crumbMask);
127 addr >>= dev->crumbShift;
128 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
129 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
135 /* Function to return the number of shifts for a power of 2 greater than or equal
136 * to the given number
137 * Note we don't try to cater for all possible numbers and this does not have to
138 * be hellishly efficient.
141 static __u32 ShiftsGE(__u32 x)
146 nShifts = extraBits = 0;
149 if(x & 1) extraBits++;
160 /* Function to return the number of shifts to get a 1 in bit 0
163 static __u32 ShiftDiv(__u32 x)
182 * Temporary buffer manipulations.
185 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
188 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
189 if (dev->tempBuffer[i].line == 0) {
190 dev->tempBuffer[i].line = lineNo;
191 if ((i + 1) > dev->maxTemp) {
192 dev->maxTemp = i + 1;
193 for (j = 0; j <= i; j++)
194 dev->tempBuffer[j].maxLine =
195 dev->tempBuffer[j].line;
198 return dev->tempBuffer[i].buffer;
202 T(YAFFS_TRACE_BUFFERS,
203 (TSTR("Out of temp buffers at line %d, other held by lines:"),
205 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
206 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
208 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
211 * If we got here then we have to allocate an unmanaged one
215 dev->unmanagedTempAllocations++;
216 return YMALLOC(dev->nDataBytesPerChunk);
220 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
224 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
225 if (dev->tempBuffer[i].buffer == buffer) {
226 dev->tempBuffer[i].line = 0;
232 /* assume it is an unmanaged one. */
233 T(YAFFS_TRACE_BUFFERS,
234 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
237 dev->unmanagedTempDeallocations++;
243 * Determine if we have a managed buffer.
245 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
248 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
249 if (dev->tempBuffer[i].buffer == buffer)
254 for (i = 0; i < dev->nShortOpCaches; i++) {
255 if( dev->srCache[i].data == buffer )
260 if (buffer == dev->checkpointBuffer)
263 T(YAFFS_TRACE_ALWAYS,
264 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
269 * Chunk bitmap manipulations
272 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
274 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
276 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
280 return dev->chunkBits +
281 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
284 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
286 __u8 *blkBits = yaffs_BlockBits(dev, blk);
288 memset(blkBits, 0, dev->chunkBitmapStride);
291 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
293 __u8 *blkBits = yaffs_BlockBits(dev, blk);
295 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
298 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
300 __u8 *blkBits = yaffs_BlockBits(dev, blk);
302 blkBits[chunk / 8] |= (1 << (chunk & 7));
305 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
307 __u8 *blkBits = yaffs_BlockBits(dev, blk);
308 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
311 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
313 __u8 *blkBits = yaffs_BlockBits(dev, blk);
315 for (i = 0; i < dev->chunkBitmapStride; i++) {
324 * Simple hash function. Needs to have a reasonable spread
327 static Y_INLINE int yaffs_HashFunction(int n)
330 return (n % YAFFS_NOBJECT_BUCKETS);
334 * Access functions to useful fake objects
337 yaffs_Object *yaffs_Root(yaffs_Device * dev)
342 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
344 return dev->lostNFoundDir;
349 * Erased NAND checking functions
352 int yaffs_CheckFF(__u8 * buffer, int nBytes)
354 /* Horrible, slow implementation */
363 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
367 int retval = YAFFS_OK;
368 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
369 yaffs_ExtendedTags tags;
372 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
374 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
378 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
379 T(YAFFS_TRACE_NANDACCESS,
380 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
384 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
390 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
392 yaffs_ExtendedTags * tags,
402 yaffs_InvalidateCheckpoint(dev);
405 chunk = yaffs_AllocateChunk(dev, useReserve,&bi);
408 /* First check this chunk is erased, if it needs checking.
409 * The checking policy (unless forced always on) is as follows:
410 * Check the first page we try to write in a block.
411 * - If the check passes then we don't need to check any more.
412 * - If the check fails, we check again...
413 * If the block has been erased, we don't need to check.
415 * However, if the block has been prioritised for gc, then
416 * we think there might be something odd about this block
420 * We should only ever see chunks that have not been erased
421 * if there was a partially written chunk due to power loss
422 * This checking policy should catch that case with very
423 * few checks and thus save a lot of checks that are most likely not
427 if(bi->gcPrioritise){
428 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
430 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
432 bi->skipErasedCheck = 0;
435 if(!bi->skipErasedCheck){
436 erasedOk = yaffs_CheckChunkErased(dev, chunk);
437 if(erasedOk && !bi->gcPrioritise)
438 bi->skipErasedCheck = 1;
444 ("**>> yaffs chunk %d was not erased"
448 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
456 * Copy the data into the robustification buffer.
457 * NB We do this at the end to prevent duplicates in the case of a write error.
460 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
463 /* The erased check or write failed */
464 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
469 } while (chunk >= 0 && !writeOk);
473 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
475 dev->nRetriedWrites += (attempts - 1);
482 * Block retiring for handling a broken block.
485 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
488 yaffs_InvalidateCheckpoint(dev);
490 yaffs_MarkBlockBad(dev, blockInNAND);
492 yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
493 YAFFS_BLOCK_STATE_DEAD;
495 dev->nRetiredBlocks++;
499 * Functions for robustisizing TODO
503 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
505 const yaffs_ExtendedTags * tags)
509 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
510 const yaffs_ExtendedTags * tags)
514 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
516 if(!bi->gcPrioritise){
517 bi->gcPrioritise = 1;
518 dev->hasPendingPrioritisedGCs = 1;
519 bi->chunkErrorStrikes ++;
521 if(bi->chunkErrorStrikes > 3){
522 bi->needsRetiring = 1; /* Too many stikes, so retire this */
523 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
530 static void yaffs_ReportOddballBlocks(yaffs_Device *dev)
533 for(i = dev->startBlock; i <= dev->endBlock; i++){
534 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
535 if(bi->needsRetiring || bi->gcPrioritise)
536 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("yaffs block %d%s%s" TENDSTR),
538 bi->needsRetiring ? " needs retiring" : "",
539 bi->gcPrioritise ? " gc prioritised" : ""));
544 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
547 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
548 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
550 yaffs_HandleChunkError(dev,bi);
554 /* Was an actual write failure, so mark the block for retirement */
555 bi->needsRetiring = 1;
556 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
557 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
562 /* Delete the chunk */
563 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
567 /*---------------- Name handling functions ------------*/
569 static __u16 yaffs_CalcNameSum(const YCHAR * name)
574 YUCHAR *bname = (YUCHAR *) name;
576 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
578 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
579 sum += yaffs_toupper(*bname) * i;
590 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
592 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
593 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
594 yaffs_strcpy(obj->shortName, name);
596 obj->shortName[0] = _Y('\0');
599 obj->sum = yaffs_CalcNameSum(name);
602 /*-------------------- TNODES -------------------
604 * List of spare tnodes
605 * The list is hooked together using the first pointer
609 /* yaffs_CreateTnodes creates a bunch more tnodes and
610 * adds them to the tnode free list.
611 * Don't use this function directly
614 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
618 yaffs_Tnode *newTnodes;
622 yaffs_TnodeList *tnl;
627 /* Calculate the tnode size in bytes for variable width tnode support.
628 * Must be a multiple of 32-bits */
629 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
631 /* make these things */
633 newTnodes = YMALLOC(nTnodes * tnodeSize);
634 mem = (__u8 *)newTnodes;
638 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
642 /* Hook them into the free list */
644 for (i = 0; i < nTnodes - 1; i++) {
645 newTnodes[i].internal[0] = &newTnodes[i + 1];
646 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
647 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
651 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
652 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
653 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
655 dev->freeTnodes = newTnodes;
657 /* New hookup for wide tnodes */
658 for(i = 0; i < nTnodes -1; i++) {
659 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
660 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
661 curr->internal[0] = next;
664 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
665 curr->internal[0] = dev->freeTnodes;
666 dev->freeTnodes = (yaffs_Tnode *)mem;
671 dev->nFreeTnodes += nTnodes;
672 dev->nTnodesCreated += nTnodes;
674 /* Now add this bunch of tnodes to a list for freeing up.
675 * NB If we can't add this to the management list it isn't fatal
676 * but it just means we can't free this bunch of tnodes later.
679 tnl = YMALLOC(sizeof(yaffs_TnodeList));
683 ("yaffs: Could not add tnodes to management list" TENDSTR)));
686 tnl->tnodes = newTnodes;
687 tnl->next = dev->allocatedTnodeList;
688 dev->allocatedTnodeList = tnl;
691 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
696 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
698 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
700 yaffs_Tnode *tn = NULL;
702 /* If there are none left make more */
703 if (!dev->freeTnodes) {
704 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
707 if (dev->freeTnodes) {
708 tn = dev->freeTnodes;
709 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
710 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
711 /* Hoosterman, this thing looks like it isn't in the list */
712 T(YAFFS_TRACE_ALWAYS,
713 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
716 dev->freeTnodes = dev->freeTnodes->internal[0];
723 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
725 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
728 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
733 /* FreeTnode frees up a tnode and puts it back on the free list */
734 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
737 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
738 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
739 /* Hoosterman, this thing looks like it is already in the list */
740 T(YAFFS_TRACE_ALWAYS,
741 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
743 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
745 tn->internal[0] = dev->freeTnodes;
746 dev->freeTnodes = tn;
751 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
753 /* Free the list of allocated tnodes */
754 yaffs_TnodeList *tmp;
756 while (dev->allocatedTnodeList) {
757 tmp = dev->allocatedTnodeList->next;
759 YFREE(dev->allocatedTnodeList->tnodes);
760 YFREE(dev->allocatedTnodeList);
761 dev->allocatedTnodeList = tmp;
765 dev->freeTnodes = NULL;
766 dev->nFreeTnodes = 0;
769 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
771 dev->allocatedTnodeList = NULL;
772 dev->freeTnodes = NULL;
773 dev->nFreeTnodes = 0;
774 dev->nTnodesCreated = 0;
779 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
781 __u32 *map = (__u32 *)tn;
787 pos &= YAFFS_TNODES_LEVEL0_MASK;
788 val >>= dev->chunkGroupBits;
790 bitInMap = pos * dev->tnodeWidth;
791 wordInMap = bitInMap /32;
792 bitInWord = bitInMap & (32 -1);
794 mask = dev->tnodeMask << bitInWord;
796 map[wordInMap] &= ~mask;
797 map[wordInMap] |= (mask & (val << bitInWord));
799 if(dev->tnodeWidth > (32-bitInWord)) {
800 bitInWord = (32 - bitInWord);
802 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
803 map[wordInMap] &= ~mask;
804 map[wordInMap] |= (mask & (val >> bitInWord));
808 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
810 __u32 *map = (__u32 *)tn;
816 pos &= YAFFS_TNODES_LEVEL0_MASK;
818 bitInMap = pos * dev->tnodeWidth;
819 wordInMap = bitInMap /32;
820 bitInWord = bitInMap & (32 -1);
822 val = map[wordInMap] >> bitInWord;
824 if(dev->tnodeWidth > (32-bitInWord)) {
825 bitInWord = (32 - bitInWord);
827 val |= (map[wordInMap] << bitInWord);
830 val &= dev->tnodeMask;
831 val <<= dev->chunkGroupBits;
836 /* ------------------- End of individual tnode manipulation -----------------*/
838 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
839 * The look up tree is represented by the top tnode and the number of topLevel
840 * in the tree. 0 means only the level 0 tnode is in the tree.
843 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
844 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
845 yaffs_FileStructure * fStruct,
849 yaffs_Tnode *tn = fStruct->top;
851 int requiredTallness;
852 int level = fStruct->topLevel;
854 /* Check sane level and chunk Id */
855 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
859 if (chunkId > YAFFS_MAX_CHUNK_ID) {
863 /* First check we're tall enough (ie enough topLevel) */
865 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
866 requiredTallness = 0;
868 i >>= YAFFS_TNODES_INTERNAL_BITS;
872 if (requiredTallness > fStruct->topLevel) {
873 /* Not tall enough, so we can't find it, return NULL. */
877 /* Traverse down to level 0 */
878 while (level > 0 && tn) {
881 ( YAFFS_TNODES_LEVEL0_BITS +
883 YAFFS_TNODES_INTERNAL_BITS)
885 YAFFS_TNODES_INTERNAL_MASK];
893 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
894 * This happens in two steps:
895 * 1. If the tree isn't tall enough, then make it taller.
896 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
898 * Used when modifying the tree.
900 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
901 * be plugged into the ttree.
904 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
905 yaffs_FileStructure * fStruct,
907 yaffs_Tnode *passedTn)
910 int requiredTallness;
918 /* Check sane level and page Id */
919 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
923 if (chunkId > YAFFS_MAX_CHUNK_ID) {
927 /* First check we're tall enough (ie enough topLevel) */
929 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
930 requiredTallness = 0;
932 x >>= YAFFS_TNODES_INTERNAL_BITS;
937 if (requiredTallness > fStruct->topLevel) {
938 /* Not tall enough,gotta make the tree taller */
939 for (i = fStruct->topLevel; i < requiredTallness; i++) {
941 tn = yaffs_GetTnode(dev);
944 tn->internal[0] = fStruct->top;
948 (TSTR("yaffs: no more tnodes" TENDSTR)));
952 fStruct->topLevel = requiredTallness;
955 /* Traverse down to level 0, adding anything we need */
957 l = fStruct->topLevel;
961 while (l > 0 && tn) {
963 ( YAFFS_TNODES_LEVEL0_BITS +
964 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
965 YAFFS_TNODES_INTERNAL_MASK;
968 if((l>1) && !tn->internal[x]){
969 /* Add missing non-level-zero tnode */
970 tn->internal[x] = yaffs_GetTnode(dev);
973 /* Looking from level 1 at level 0 */
975 /* If we already have one, then release it.*/
977 yaffs_FreeTnode(dev,tn->internal[x]);
978 tn->internal[x] = passedTn;
980 } else if(!tn->internal[x]) {
981 /* Don't have one, none passed in */
982 tn->internal[x] = yaffs_GetTnode(dev);
986 tn = tn->internal[x];
992 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
993 yaffs_FreeTnode(dev,passedTn);
1000 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1001 yaffs_ExtendedTags * tags, int objectId,
1006 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1007 if (yaffs_CheckChunkBit
1008 (dev, theChunk / dev->nChunksPerBlock,
1009 theChunk % dev->nChunksPerBlock)) {
1010 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1012 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1024 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1025 * chunks and tnodes in the file
1026 * Returns 1 if the tree was deleted.
1027 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1030 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1031 int chunkOffset, int *limit)
1036 yaffs_ExtendedTags tags;
1038 yaffs_Device *dev = in->myDev;
1045 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1047 if (tn->internal[i]) {
1048 if (limit && (*limit) < 0) {
1052 yaffs_DeleteWorker(in,
1060 YAFFS_TNODES_INTERNAL_BITS)
1065 yaffs_FreeTnode(dev,
1068 tn->internal[i] = NULL;
1073 return (allDone) ? 1 : 0;
1074 } else if (level == 0) {
1077 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1079 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1084 YAFFS_TNODES_LEVEL0_BITS) + i;
1087 yaffs_FindChunkInGroup(dev,
1093 if (foundChunk > 0) {
1094 yaffs_DeleteChunk(dev,
1099 *limit = *limit - 1;
1107 yaffs_PutLevel0Tnode(dev,tn,i,0);
1111 return (i < 0) ? 1 : 0;
1121 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1124 yaffs_BlockInfo *theBlock;
1126 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1128 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1130 theBlock->softDeletions++;
1135 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1136 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1138 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1141 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1142 __u32 level, int chunkOffset)
1147 yaffs_Device *dev = in->myDev;
1152 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1154 if (tn->internal[i]) {
1156 yaffs_SoftDeleteWorker(in,
1162 YAFFS_TNODES_INTERNAL_BITS)
1165 yaffs_FreeTnode(dev,
1168 tn->internal[i] = NULL;
1170 /* Hoosterman... how could this happen? */
1174 return (allDone) ? 1 : 0;
1175 } else if (level == 0) {
1177 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1178 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1180 /* Note this does not find the real chunk, only the chunk group.
1181 * We make an assumption that a chunk group is not larger than
1184 yaffs_SoftDeleteChunk(dev, theChunk);
1185 yaffs_PutLevel0Tnode(dev,tn,i,0);
1199 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1202 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1203 if (obj->nDataChunks <= 0) {
1204 /* Empty file with no duplicate object headers, just delete it immediately */
1205 yaffs_FreeTnode(obj->myDev,
1206 obj->variant.fileVariant.top);
1207 obj->variant.fileVariant.top = NULL;
1208 T(YAFFS_TRACE_TRACING,
1209 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1211 yaffs_DoGenericObjectDeletion(obj);
1213 yaffs_SoftDeleteWorker(obj,
1214 obj->variant.fileVariant.top,
1215 obj->variant.fileVariant.
1217 obj->softDeleted = 1;
1222 /* Pruning removes any part of the file structure tree that is beyond the
1223 * bounds of the file (ie that does not point to chunks).
1225 * A file should only get pruned when its size is reduced.
1227 * Before pruning, the chunks must be pulled from the tree and the
1228 * level 0 tnode entries must be zeroed out.
1229 * Could also use this for file deletion, but that's probably better handled
1230 * by a special case.
1233 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1234 __u32 level, int del0)
1242 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1243 if (tn->internal[i] && level > 0) {
1245 yaffs_PruneWorker(dev, tn->internal[i],
1247 (i == 0) ? del0 : 1);
1250 if (tn->internal[i]) {
1255 if (hasData == 0 && del0) {
1256 /* Free and return NULL */
1258 yaffs_FreeTnode(dev, tn);
1268 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1269 yaffs_FileStructure * fStruct)
1276 if (fStruct->topLevel > 0) {
1278 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1280 /* Now we have a tree with all the non-zero branches NULL but the height
1281 * is the same as it was.
1282 * Let's see if we can trim internal tnodes to shorten the tree.
1283 * We can do this if only the 0th element in the tnode is in use
1284 * (ie all the non-zero are NULL)
1287 while (fStruct->topLevel && !done) {
1291 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1292 if (tn->internal[i]) {
1298 fStruct->top = tn->internal[0];
1299 fStruct->topLevel--;
1300 yaffs_FreeTnode(dev, tn);
1310 /*-------------------- End of File Structure functions.-------------------*/
1312 /* yaffs_CreateFreeObjects creates a bunch more objects and
1313 * adds them to the object free list.
1315 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1318 yaffs_Object *newObjects;
1319 yaffs_ObjectList *list;
1324 /* make these things */
1325 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1328 T(YAFFS_TRACE_ALLOCATE,
1329 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1333 /* Hook them into the free list */
1334 for (i = 0; i < nObjects - 1; i++) {
1335 newObjects[i].siblings.next =
1336 (struct list_head *)(&newObjects[i + 1]);
1339 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1340 dev->freeObjects = newObjects;
1341 dev->nFreeObjects += nObjects;
1342 dev->nObjectsCreated += nObjects;
1344 /* Now add this bunch of Objects to a list for freeing up. */
1346 list = YMALLOC(sizeof(yaffs_ObjectList));
1348 T(YAFFS_TRACE_ALLOCATE,
1349 (TSTR("Could not add objects to management list" TENDSTR)));
1351 list->objects = newObjects;
1352 list->next = dev->allocatedObjectList;
1353 dev->allocatedObjectList = list;
1360 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1361 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1363 yaffs_Object *tn = NULL;
1365 /* If there are none left make more */
1366 if (!dev->freeObjects) {
1367 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1370 if (dev->freeObjects) {
1371 tn = dev->freeObjects;
1373 (yaffs_Object *) (dev->freeObjects->siblings.next);
1374 dev->nFreeObjects--;
1376 /* Now sweeten it up... */
1378 memset(tn, 0, sizeof(yaffs_Object));
1381 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1382 INIT_LIST_HEAD(&(tn->hardLinks));
1383 INIT_LIST_HEAD(&(tn->hashLink));
1384 INIT_LIST_HEAD(&tn->siblings);
1386 /* Add it to the lost and found directory.
1387 * NB Can't put root or lostNFound in lostNFound so
1388 * check if lostNFound exists first
1390 if (dev->lostNFoundDir) {
1391 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1398 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1403 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1405 obj->fake = 1; /* it is fake so it has no NAND presence... */
1406 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1407 obj->unlinkAllowed = 0; /* ... or unlink it */
1410 obj->yst_mode = mode;
1412 obj->chunkId = 0; /* Not a valid chunk. */
1419 static void yaffs_UnhashObject(yaffs_Object * tn)
1422 yaffs_Device *dev = tn->myDev;
1424 /* If it is still linked into the bucket list, free from the list */
1425 if (!list_empty(&tn->hashLink)) {
1426 list_del_init(&tn->hashLink);
1427 bucket = yaffs_HashFunction(tn->objectId);
1428 dev->objectBucket[bucket].count--;
1433 /* FreeObject frees up a Object and puts it back on the free list */
1434 static void yaffs_FreeObject(yaffs_Object * tn)
1437 yaffs_Device *dev = tn->myDev;
1441 /* We're still hooked up to a cached inode.
1442 * Don't delete now, but mark for later deletion
1444 tn->deferedFree = 1;
1449 yaffs_UnhashObject(tn);
1451 /* Link into the free list. */
1452 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1453 dev->freeObjects = tn;
1454 dev->nFreeObjects++;
1459 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1461 if (obj->deferedFree) {
1462 yaffs_FreeObject(obj);
1468 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1470 /* Free the list of allocated Objects */
1472 yaffs_ObjectList *tmp;
1474 while (dev->allocatedObjectList) {
1475 tmp = dev->allocatedObjectList->next;
1476 YFREE(dev->allocatedObjectList->objects);
1477 YFREE(dev->allocatedObjectList);
1479 dev->allocatedObjectList = tmp;
1482 dev->freeObjects = NULL;
1483 dev->nFreeObjects = 0;
1486 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1490 dev->allocatedObjectList = NULL;
1491 dev->freeObjects = NULL;
1492 dev->nFreeObjects = 0;
1494 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1495 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1496 dev->objectBucket[i].count = 0;
1501 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1506 int lowest = 999999;
1508 /* First let's see if we can find one that's empty. */
1510 for (i = 0; i < 10 && lowest > 0; i++) {
1512 x %= YAFFS_NOBJECT_BUCKETS;
1513 if (dev->objectBucket[x].count < lowest) {
1514 lowest = dev->objectBucket[x].count;
1520 /* If we didn't find an empty list, then try
1521 * looking a bit further for a short one
1524 for (i = 0; i < 10 && lowest > 3; i++) {
1526 x %= YAFFS_NOBJECT_BUCKETS;
1527 if (dev->objectBucket[x].count < lowest) {
1528 lowest = dev->objectBucket[x].count;
1537 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1539 int bucket = yaffs_FindNiceObjectBucket(dev);
1541 /* Now find an object value that has not already been taken
1542 * by scanning the list.
1546 struct list_head *i;
1548 __u32 n = (__u32) bucket;
1550 /* yaffs_CheckObjectHashSanity(); */
1554 n += YAFFS_NOBJECT_BUCKETS;
1555 if (1 || dev->objectBucket[bucket].count > 0) {
1556 list_for_each(i, &dev->objectBucket[bucket].list) {
1557 /* If there is already one in the list */
1559 && list_entry(i, yaffs_Object,
1560 hashLink)->objectId == n) {
1571 static void yaffs_HashObject(yaffs_Object * in)
1573 int bucket = yaffs_HashFunction(in->objectId);
1574 yaffs_Device *dev = in->myDev;
1576 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1577 dev->objectBucket[bucket].count++;
1581 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1583 int bucket = yaffs_HashFunction(number);
1584 struct list_head *i;
1587 list_for_each(i, &dev->objectBucket[bucket].list) {
1588 /* Look if it is in the list */
1590 in = list_entry(i, yaffs_Object, hashLink);
1591 if (in->objectId == number) {
1593 /* Don't tell the VFS about this one if it is defered free */
1594 if (in->deferedFree)
1606 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1607 yaffs_ObjectType type)
1610 yaffs_Object *theObject;
1613 number = yaffs_CreateNewObjectNumber(dev);
1616 theObject = yaffs_AllocateEmptyObject(dev);
1619 theObject->fake = 0;
1620 theObject->renameAllowed = 1;
1621 theObject->unlinkAllowed = 1;
1622 theObject->objectId = number;
1623 yaffs_HashObject(theObject);
1624 theObject->variantType = type;
1625 #ifdef CONFIG_YAFFS_WINCE
1626 yfsd_WinFileTimeNow(theObject->win_atime);
1627 theObject->win_ctime[0] = theObject->win_mtime[0] =
1628 theObject->win_atime[0];
1629 theObject->win_ctime[1] = theObject->win_mtime[1] =
1630 theObject->win_atime[1];
1634 theObject->yst_atime = theObject->yst_mtime =
1635 theObject->yst_ctime = Y_CURRENT_TIME;
1638 case YAFFS_OBJECT_TYPE_FILE:
1639 theObject->variant.fileVariant.fileSize = 0;
1640 theObject->variant.fileVariant.scannedFileSize = 0;
1641 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1642 theObject->variant.fileVariant.topLevel = 0;
1643 theObject->variant.fileVariant.top =
1644 yaffs_GetTnode(dev);
1646 case YAFFS_OBJECT_TYPE_DIRECTORY:
1647 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1650 case YAFFS_OBJECT_TYPE_SYMLINK:
1651 case YAFFS_OBJECT_TYPE_HARDLINK:
1652 case YAFFS_OBJECT_TYPE_SPECIAL:
1653 /* No action required */
1655 case YAFFS_OBJECT_TYPE_UNKNOWN:
1656 /* todo this should not happen */
1664 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1666 yaffs_ObjectType type)
1668 yaffs_Object *theObject = NULL;
1671 theObject = yaffs_FindObjectByNumber(dev, number);
1675 theObject = yaffs_CreateNewObject(dev, number, type);
1683 static YCHAR *yaffs_CloneString(const YCHAR * str)
1685 YCHAR *newStr = NULL;
1688 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1689 yaffs_strcpy(newStr, str);
1697 * Mknod (create) a new object.
1698 * equivalentObject only has meaning for a hard link;
1699 * aliasString only has meaning for a sumlink.
1700 * rdev only has meaning for devices (a subset of special objects)
1703 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1704 yaffs_Object * parent,
1709 yaffs_Object * equivalentObject,
1710 const YCHAR * aliasString, __u32 rdev)
1714 yaffs_Device *dev = parent->myDev;
1716 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1717 if (yaffs_FindObjectByName(parent, name)) {
1721 in = yaffs_CreateNewObject(dev, -1, type);
1726 in->variantType = type;
1728 in->yst_mode = mode;
1730 #ifdef CONFIG_YAFFS_WINCE
1731 yfsd_WinFileTimeNow(in->win_atime);
1732 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1733 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1736 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1738 in->yst_rdev = rdev;
1742 in->nDataChunks = 0;
1744 yaffs_SetObjectName(in, name);
1747 yaffs_AddObjectToDirectory(parent, in);
1749 in->myDev = parent->myDev;
1752 case YAFFS_OBJECT_TYPE_SYMLINK:
1753 in->variant.symLinkVariant.alias =
1754 yaffs_CloneString(aliasString);
1756 case YAFFS_OBJECT_TYPE_HARDLINK:
1757 in->variant.hardLinkVariant.equivalentObject =
1759 in->variant.hardLinkVariant.equivalentObjectId =
1760 equivalentObject->objectId;
1761 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1763 case YAFFS_OBJECT_TYPE_FILE:
1764 case YAFFS_OBJECT_TYPE_DIRECTORY:
1765 case YAFFS_OBJECT_TYPE_SPECIAL:
1766 case YAFFS_OBJECT_TYPE_UNKNOWN:
1771 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1772 /* Could not create the object header, fail the creation */
1773 yaffs_DestroyObject(in);
1782 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1783 __u32 mode, __u32 uid, __u32 gid)
1785 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1786 uid, gid, NULL, NULL, 0);
1789 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1790 __u32 mode, __u32 uid, __u32 gid)
1792 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1793 mode, uid, gid, NULL, NULL, 0);
1796 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1797 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1799 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1800 uid, gid, NULL, NULL, rdev);
1803 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1804 __u32 mode, __u32 uid, __u32 gid,
1805 const YCHAR * alias)
1807 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1808 uid, gid, NULL, alias, 0);
1811 /* yaffs_Link returns the object id of the equivalent object.*/
1812 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1813 yaffs_Object * equivalentObject)
1815 /* Get the real object in case we were fed a hard link as an equivalent object */
1816 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1818 if (yaffs_MknodObject
1819 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1820 equivalentObject, NULL, 0)) {
1821 return equivalentObject;
1828 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1829 const YCHAR * newName, int force, int shadows)
1834 yaffs_Object *existingTarget;
1836 if (newDir == NULL) {
1837 newDir = obj->parent; /* use the old directory */
1840 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1841 T(YAFFS_TRACE_ALWAYS,
1843 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1848 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1849 if (obj->myDev->isYaffs2) {
1850 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1852 unlinkOp = (newDir == obj->myDev->unlinkedDir
1853 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1856 deleteOp = (newDir == obj->myDev->deletedDir);
1858 existingTarget = yaffs_FindObjectByName(newDir, newName);
1860 /* If the object is a file going into the unlinked directory,
1861 * then it is OK to just stuff it in since duplicate names are allowed.
1862 * else only proceed if the new name does not exist and if we're putting
1863 * it into a directory.
1870 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1871 yaffs_SetObjectName(obj, newName);
1874 yaffs_AddObjectToDirectory(newDir, obj);
1879 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1880 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1887 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1888 yaffs_Object * newDir, const YCHAR * newName)
1891 yaffs_Object *existingTarget;
1894 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1895 /* Special case for case insemsitive systems (eg. WinCE).
1896 * While look-up is case insensitive, the name isn't.
1897 * Therefore we might want to change x.txt to X.txt
1899 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1904 obj = yaffs_FindObjectByName(oldDir, oldName);
1905 /* Check new name to long. */
1906 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1907 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1910 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1911 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1915 if (obj && obj->renameAllowed) {
1917 /* Now do the handling for an existing target, if there is one */
1919 existingTarget = yaffs_FindObjectByName(newDir, newName);
1920 if (existingTarget &&
1921 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1922 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1923 /* There is a target that is a non-empty directory, so we fail */
1924 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1925 } else if (existingTarget && existingTarget != obj) {
1926 /* Nuke the target first, using shadowing,
1927 * but only if it isn't the same object
1929 yaffs_ChangeObjectName(obj, newDir, newName, force,
1930 existingTarget->objectId);
1931 yaffs_UnlinkObject(existingTarget);
1934 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1939 /*------------------------- Block Management and Page Allocation ----------------*/
1941 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1943 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1945 dev->allocationBlock = -1; /* force it to get a new one */
1947 /* Todo we're assuming the malloc will pass. */
1948 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1949 if(!dev->blockInfo){
1950 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1951 dev->blockInfoAlt = 1;
1954 dev->blockInfoAlt = 0;
1956 /* Set up dynamic blockinfo stuff. */
1957 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; // round up bytes
1958 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1959 if(!dev->chunkBits){
1960 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1961 dev->chunkBitsAlt = 1;
1964 dev->chunkBitsAlt = 0;
1966 if (dev->blockInfo && dev->chunkBits) {
1967 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1968 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1976 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1978 if(dev->blockInfoAlt)
1979 YFREE_ALT(dev->blockInfo);
1981 YFREE(dev->blockInfo);
1982 dev->blockInfoAlt = 0;
1984 dev->blockInfo = NULL;
1986 if(dev->chunkBitsAlt)
1987 YFREE_ALT(dev->chunkBits);
1989 YFREE(dev->chunkBits);
1990 dev->chunkBitsAlt = 0;
1991 dev->chunkBits = NULL;
1994 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1995 yaffs_BlockInfo * bi)
2002 return 1; /* disqualification only applies to yaffs2. */
2004 if (!bi->hasShrinkHeader)
2005 return 1; /* can gc */
2007 /* Find the oldest dirty sequence number if we don't know it and save it
2008 * so we don't have to keep recomputing it.
2010 if (!dev->oldestDirtySequence) {
2011 seq = dev->sequenceNumber;
2013 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2015 b = yaffs_GetBlockInfo(dev, i);
2016 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2017 (b->pagesInUse - b->softDeletions) <
2018 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2019 seq = b->sequenceNumber;
2022 dev->oldestDirtySequence = seq;
2025 /* Can't do gc of this block if there are any blocks older than this one that have
2028 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2032 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2033 * for garbage collection.
2036 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2040 int b = dev->currentDirtyChecker;
2047 yaffs_BlockInfo *bi;
2048 static int nonAggressiveSkip = 0;
2049 int pendingPrioritisedExist = 0;
2051 /* First let's see if we need to grab a prioritised block */
2052 if(dev->hasPendingPrioritisedGCs){
2053 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2055 bi = yaffs_GetBlockInfo(dev, i);
2056 if(bi->gcPrioritise)
2057 pendingPrioritisedExist = 1;
2058 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2060 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2061 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2064 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2068 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2069 dev->hasPendingPrioritisedGCs = 0;
2072 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2074 * else (we're doing a leasurely gc), then we only bother to do this if the
2075 * block has only a few pages in use.
2078 nonAggressiveSkip--;
2080 if (!aggressive && (nonAggressiveSkip > 0)) {
2086 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2090 dev->internalEndBlock - dev->internalStartBlock + 1;
2093 dev->internalEndBlock - dev->internalStartBlock + 1;
2094 iterations = iterations / 16;
2095 if (iterations > 200) {
2100 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2102 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2103 b = dev->internalStartBlock;
2106 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2107 T(YAFFS_TRACE_ERROR,
2108 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2112 bi = yaffs_GetBlockInfo(dev, b);
2115 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2122 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2123 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2124 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2126 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2130 dev->currentDirtyChecker = b;
2134 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2135 dev->nChunksPerBlock - pagesInUse,prioritised));
2138 dev->oldestDirtySequence = 0;
2141 nonAggressiveSkip = 4;
2147 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2149 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2153 /* If the block is still healthy erase it and mark as clean.
2154 * If the block has had a data failure, then retire it.
2156 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2158 if (!bi->needsRetiring) {
2159 yaffs_InvalidateCheckpoint(dev);
2160 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2162 dev->nErasureFailures++;
2163 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2164 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2168 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2170 for (i = 0; i < dev->nChunksPerBlock; i++) {
2171 if (!yaffs_CheckChunkErased
2172 (dev, blockNo * dev->nChunksPerBlock + i)) {
2173 T(YAFFS_TRACE_ERROR,
2175 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2176 TENDSTR), blockNo, i));
2182 /* Clean it up... */
2183 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2184 dev->nErasedBlocks++;
2186 bi->softDeletions = 0;
2187 bi->hasShrinkHeader = 0;
2188 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2189 bi->gcPrioritise = 0;
2190 yaffs_ClearChunkBits(dev, blockNo);
2192 T(YAFFS_TRACE_ERASE,
2193 (TSTR("Erased block %d" TENDSTR), blockNo));
2195 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2197 yaffs_RetireBlock(dev, blockNo);
2198 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2199 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2203 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2207 yaffs_BlockInfo *bi;
2209 if (dev->nErasedBlocks < 1) {
2210 /* Hoosterman we've got a problem.
2211 * Can't get space to gc
2213 T(YAFFS_TRACE_ERROR,
2214 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2219 /* Find an empty block. */
2221 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2222 dev->allocationBlockFinder++;
2223 if (dev->allocationBlockFinder < dev->internalStartBlock
2224 || dev->allocationBlockFinder > dev->internalEndBlock) {
2225 dev->allocationBlockFinder = dev->internalStartBlock;
2228 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2230 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2231 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2232 dev->sequenceNumber++;
2233 bi->sequenceNumber = dev->sequenceNumber;
2234 dev->nErasedBlocks--;
2235 T(YAFFS_TRACE_ALLOCATE,
2236 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2237 dev->allocationBlockFinder, dev->sequenceNumber,
2238 dev->nErasedBlocks));
2239 return dev->allocationBlockFinder;
2243 T(YAFFS_TRACE_ALWAYS,
2245 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2246 TENDSTR), dev->nErasedBlocks));
2252 // Check if there's space to allocate...
2253 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2254 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2257 int reservedBlocks = dev->nReservedBlocks;
2258 int checkpointBlocks;
2260 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2261 if(checkpointBlocks < 0)
2262 checkpointBlocks = 0;
2264 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2266 return (dev->nFreeChunks > reservedChunks);
2269 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2272 yaffs_BlockInfo *bi;
2274 if (dev->allocationBlock < 0) {
2275 /* Get next block to allocate off */
2276 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2277 dev->allocationPage = 0;
2280 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2281 /* Not enough space to allocate unless we're allowed to use the reserve. */
2285 if (dev->nErasedBlocks < dev->nReservedBlocks
2286 && dev->allocationPage == 0) {
2287 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2290 /* Next page please.... */
2291 if (dev->allocationBlock >= 0) {
2292 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2294 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2295 dev->allocationPage;
2297 yaffs_SetChunkBit(dev, dev->allocationBlock,
2298 dev->allocationPage);
2300 dev->allocationPage++;
2304 /* If the block is full set the state to full */
2305 if (dev->allocationPage >= dev->nChunksPerBlock) {
2306 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2307 dev->allocationBlock = -1;
2316 T(YAFFS_TRACE_ERROR,
2317 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2322 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2326 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2328 if (dev->allocationBlock > 0) {
2329 n += (dev->nChunksPerBlock - dev->allocationPage);
2336 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2342 int retVal = YAFFS_OK;
2345 int isCheckpointBlock;
2347 int chunksBefore = yaffs_GetErasedChunks(dev);
2350 yaffs_ExtendedTags tags;
2352 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2354 yaffs_Object *object;
2356 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2358 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2360 T(YAFFS_TRACE_TRACING,
2361 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2362 bi->pagesInUse, bi->hasShrinkHeader));
2364 /*yaffs_VerifyFreeChunks(dev); */
2366 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2368 /* Take off the number of soft deleted entries because
2369 * they're going to get really deleted during GC.
2371 dev->nFreeChunks -= bi->softDeletions;
2375 if (isCheckpointBlock ||
2376 !yaffs_StillSomeChunkBits(dev, block)) {
2377 T(YAFFS_TRACE_TRACING,
2379 ("Collecting block %d that has no chunks in use" TENDSTR),
2381 yaffs_BlockBecameDirty(dev, block);
2384 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2386 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2387 chunkInBlock < dev->nChunksPerBlock
2388 && yaffs_StillSomeChunkBits(dev, block);
2389 chunkInBlock++, oldChunk++) {
2390 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2392 /* This page is in use and might need to be copied off */
2396 yaffs_InitialiseTags(&tags);
2398 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2402 yaffs_FindObjectByNumber(dev,
2405 T(YAFFS_TRACE_GC_DETAIL,
2407 ("Collecting page %d, %d %d %d " TENDSTR),
2408 chunkInBlock, tags.objectId, tags.chunkId,
2412 T(YAFFS_TRACE_ERROR,
2414 ("page %d in gc has no object "
2415 TENDSTR), oldChunk));
2418 if (object && object->deleted
2419 && tags.chunkId != 0) {
2420 /* Data chunk in a deleted file, throw it away
2421 * It's a soft deleted data chunk,
2422 * No need to copy this, just forget about it and
2423 * fix up the object.
2426 object->nDataChunks--;
2428 if (object->nDataChunks <= 0) {
2429 /* remeber to clean up the object */
2430 dev->gcCleanupList[cleanups] =
2436 /* Todo object && object->deleted && object->nDataChunks == 0 */
2438 /* Deleted object header with no data chunks.
2439 * Can be discarded and the file deleted.
2441 object->chunkId = 0;
2442 yaffs_FreeTnode(object->myDev,
2445 object->variant.fileVariant.top = NULL;
2446 yaffs_DoGenericObjectDeletion(object);
2448 } else if (object) {
2449 /* It's either a data chunk in a live file or
2450 * an ObjectHeader, so we're interested in it.
2451 * NB Need to keep the ObjectHeaders of deleted files
2452 * until the whole file has been deleted off
2454 tags.serialNumber++;
2458 if (tags.chunkId == 0) {
2459 /* It is an object Id,
2460 * We need to nuke the shrinkheader flags first
2461 * We no longer want the shrinkHeader flag since its work is done
2462 * and if it is left in place it will mess up scanning.
2463 * Also, clear out any shadowing stuff
2466 yaffs_ObjectHeader *oh;
2467 oh = (yaffs_ObjectHeader *)buffer;
2469 oh->shadowsObject = -1;
2470 tags.extraShadows = 0;
2471 tags.extraIsShrinkHeader = 0;
2475 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2478 retVal = YAFFS_FAIL;
2481 /* Ok, now fix up the Tnodes etc. */
2483 if (tags.chunkId == 0) {
2485 object->chunkId = newChunk;
2486 object->serial = tags.serialNumber;
2488 /* It's a data chunk */
2489 yaffs_PutChunkIntoFile
2497 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2502 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2505 /* Do any required cleanups */
2506 for (i = 0; i < cleanups; i++) {
2507 /* Time to delete the file too */
2509 yaffs_FindObjectByNumber(dev,
2510 dev->gcCleanupList[i]);
2512 yaffs_FreeTnode(dev,
2513 object->variant.fileVariant.
2515 object->variant.fileVariant.top = NULL;
2518 ("yaffs: About to finally delete object %d"
2519 TENDSTR), object->objectId));
2520 yaffs_DoGenericObjectDeletion(object);
2521 object->myDev->nDeletedFiles--;
2528 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2531 ("gc did not increase free chunks before %d after %d"
2532 TENDSTR), chunksBefore, chunksAfter));
2540 /* New garbage collector
2541 * If we're very low on erased blocks then we do aggressive garbage collection
2542 * otherwise we do "leasurely" garbage collection.
2543 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2544 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2546 * The idea is to help clear out space in a more spread-out manner.
2547 * Dunno if it really does anything useful.
2549 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2553 int gcOk = YAFFS_OK;
2556 int checkpointBlockAdjust;
2558 if (dev->isDoingGC) {
2559 /* Bail out so we don't get recursive gc */
2563 /* This loop should pass the first time.
2564 * We'll only see looping here if the erase of the collected block fails.
2570 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2571 if(checkpointBlockAdjust < 0)
2572 checkpointBlockAdjust = 0;
2574 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2575 /* We need a block soon...*/
2578 /* We're in no hurry */
2582 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2585 dev->garbageCollections++;
2587 dev->passiveGarbageCollections++;
2592 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2593 dev->nErasedBlocks, aggressive));
2595 gcOk = yaffs_GarbageCollectBlock(dev, block);
2598 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2601 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2602 TENDSTR), dev->nErasedBlocks, maxTries, block));
2604 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2607 return aggressive ? gcOk : YAFFS_OK;
2610 /*------------------------- TAGS --------------------------------*/
2612 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2615 return (tags->chunkId == chunkInObject &&
2616 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2621 /*-------------------- Data file manipulation -----------------*/
2623 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2624 yaffs_ExtendedTags * tags)
2626 /*Get the Tnode, then get the level 0 offset chunk offset */
2629 yaffs_ExtendedTags localTags;
2632 yaffs_Device *dev = in->myDev;
2635 /* Passed a NULL, so use our own tags space */
2639 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2642 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2645 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2651 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2652 yaffs_ExtendedTags * tags)
2654 /* Get the Tnode, then get the level 0 offset chunk offset */
2657 yaffs_ExtendedTags localTags;
2659 yaffs_Device *dev = in->myDev;
2663 /* Passed a NULL, so use our own tags space */
2667 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2671 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2674 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2677 /* Delete the entry in the filestructure (if found) */
2679 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2682 /*T(("No level 0 found for %d\n", chunkInInode)); */
2686 /* T(("Could not find %d to delete\n",chunkInInode)); */
2691 #ifdef YAFFS_PARANOID
2693 static int yaffs_CheckFileSanity(yaffs_Object * in)
2701 yaffs_Tags localTags;
2702 yaffs_Tags *tags = &localTags;
2706 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2707 /* T(("Object not a file\n")); */
2711 objId = in->objectId;
2712 fSize = in->variant.fileVariant.fileSize;
2714 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
2716 for (chunk = 1; chunk <= nChunks; chunk++) {
2717 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2722 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2724 if (yaffs_CheckChunkBits
2725 (dev, theChunk / dev->nChunksPerBlock,
2726 theChunk % dev->nChunksPerBlock)) {
2728 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2732 (tags, in->objectId, chunk, chunkDeleted)) {
2742 /* T(("No level 0 found for %d\n", chunk)); */
2746 return failed ? YAFFS_FAIL : YAFFS_OK;
2751 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2752 int chunkInNAND, int inScan)
2754 /* NB inScan is zero unless scanning.
2755 * For forward scanning, inScan is > 0;
2756 * for backward scanning inScan is < 0
2760 yaffs_Device *dev = in->myDev;
2762 yaffs_ExtendedTags existingTags;
2763 yaffs_ExtendedTags newTags;
2764 unsigned existingSerial, newSerial;
2766 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2767 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2768 * If it is not during Scanning then something went wrong!
2771 T(YAFFS_TRACE_ERROR,
2773 ("yaffs tragedy:attempt to put data chunk into a non-file"
2778 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2782 tn = yaffs_AddOrFindLevel0Tnode(dev,
2783 &in->variant.fileVariant,
2790 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2793 /* If we're scanning then we need to test for duplicates
2794 * NB This does not need to be efficient since it should only ever
2795 * happen when the power fails during a write, then only one
2796 * chunk should ever be affected.
2798 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2799 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2802 if (existingChunk != 0) {
2803 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2804 * thus we have to do a FindChunkInFile to get the real chunk id.
2806 * We have a duplicate now we need to decide which one to use:
2808 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2809 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2810 * YAFFS1: Get both sets of tags and compare serial numbers.
2814 /* Only do this for forward scanning */
2815 yaffs_ReadChunkWithTagsFromNAND(dev,
2819 /* Do a proper find */
2821 yaffs_FindChunkInFile(in, chunkInInode,
2825 if (existingChunk <= 0) {
2826 /*Hoosterman - how did this happen? */
2828 T(YAFFS_TRACE_ERROR,
2830 ("yaffs tragedy: existing chunk < 0 in scan"
2835 /* NB The deleted flags should be false, otherwise the chunks will
2836 * not be loaded during a scan
2839 newSerial = newTags.serialNumber;
2840 existingSerial = existingTags.serialNumber;
2843 (in->myDev->isYaffs2 ||
2844 existingChunk <= 0 ||
2845 ((existingSerial + 1) & 3) == newSerial)) {
2846 /* Forward scanning.
2848 * Delete the old one and drop through to update the tnode
2850 yaffs_DeleteChunk(dev, existingChunk, 1,
2853 /* Backward scanning or we want to use the existing one
2855 * Delete the new one and return early so that the tnode isn't changed
2857 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2865 if (existingChunk == 0) {
2869 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2874 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2877 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2879 if (chunkInNAND >= 0) {
2880 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2883 T(YAFFS_TRACE_NANDACCESS,
2884 (TSTR("Chunk %d not found zero instead" TENDSTR),
2886 /* get sane (zero) data if you read a hole */
2887 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2893 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2897 yaffs_ExtendedTags tags;
2898 yaffs_BlockInfo *bi;
2904 block = chunkId / dev->nChunksPerBlock;
2905 page = chunkId % dev->nChunksPerBlock;
2907 bi = yaffs_GetBlockInfo(dev, block);
2909 T(YAFFS_TRACE_DELETION,
2910 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2913 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2915 yaffs_InitialiseTags(&tags);
2917 tags.chunkDeleted = 1;
2919 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2920 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2922 dev->nUnmarkedDeletions++;
2925 /* Pull out of the management area.
2926 * If the whole block became dirty, this will kick off an erasure.
2928 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2929 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2930 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2931 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2934 yaffs_ClearChunkBit(dev, block, page);
2938 if (bi->pagesInUse == 0 &&
2939 !bi->hasShrinkHeader &&
2940 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2941 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2942 yaffs_BlockBecameDirty(dev, block);
2946 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2951 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2952 const __u8 * buffer, int nBytes,
2955 /* Find old chunk Need to do this to get serial number
2956 * Write new one and patch into tree.
2957 * Invalidate old tags.
2961 yaffs_ExtendedTags prevTags;
2964 yaffs_ExtendedTags newTags;
2966 yaffs_Device *dev = in->myDev;
2968 yaffs_CheckGarbageCollection(dev);
2970 /* Get the previous chunk at this location in the file if it exists */
2971 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2973 /* Set up new tags */
2974 yaffs_InitialiseTags(&newTags);
2976 newTags.chunkId = chunkInInode;
2977 newTags.objectId = in->objectId;
2978 newTags.serialNumber =
2979 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2980 newTags.byteCount = nBytes;
2983 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2986 if (newChunkId >= 0) {
2987 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2989 if (prevChunkId >= 0) {
2990 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2994 yaffs_CheckFileSanity(in);
3000 /* UpdateObjectHeader updates the header on NAND for an object.
3001 * If name is not NULL, then that new name is used.
3003 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3004 int isShrink, int shadows)
3007 yaffs_BlockInfo *bi;
3009 yaffs_Device *dev = in->myDev;
3016 yaffs_ExtendedTags newTags;
3018 __u8 *buffer = NULL;
3019 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3021 yaffs_ObjectHeader *oh = NULL;
3023 if (!in->fake || force) {
3025 yaffs_CheckGarbageCollection(dev);
3027 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3028 oh = (yaffs_ObjectHeader *) buffer;
3030 prevChunkId = in->chunkId;
3032 if (prevChunkId >= 0) {
3033 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3035 memcpy(oldName, oh->name, sizeof(oh->name));
3038 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3040 oh->type = in->variantType;
3041 oh->yst_mode = in->yst_mode;
3042 oh->shadowsObject = shadows;
3044 #ifdef CONFIG_YAFFS_WINCE
3045 oh->win_atime[0] = in->win_atime[0];
3046 oh->win_ctime[0] = in->win_ctime[0];
3047 oh->win_mtime[0] = in->win_mtime[0];
3048 oh->win_atime[1] = in->win_atime[1];
3049 oh->win_ctime[1] = in->win_ctime[1];
3050 oh->win_mtime[1] = in->win_mtime[1];
3052 oh->yst_uid = in->yst_uid;
3053 oh->yst_gid = in->yst_gid;
3054 oh->yst_atime = in->yst_atime;
3055 oh->yst_mtime = in->yst_mtime;
3056 oh->yst_ctime = in->yst_ctime;
3057 oh->yst_rdev = in->yst_rdev;
3060 oh->parentObjectId = in->parent->objectId;
3062 oh->parentObjectId = 0;
3065 if (name && *name) {
3066 memset(oh->name, 0, sizeof(oh->name));
3067 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3068 } else if (prevChunkId) {
3069 memcpy(oh->name, oldName, sizeof(oh->name));
3071 memset(oh->name, 0, sizeof(oh->name));
3074 oh->isShrink = isShrink;
3076 switch (in->variantType) {
3077 case YAFFS_OBJECT_TYPE_UNKNOWN:
3078 /* Should not happen */
3080 case YAFFS_OBJECT_TYPE_FILE:
3082 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3083 || oh->parentObjectId ==
3084 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3085 fileVariant.fileSize;
3087 case YAFFS_OBJECT_TYPE_HARDLINK:
3088 oh->equivalentObjectId =
3089 in->variant.hardLinkVariant.equivalentObjectId;
3091 case YAFFS_OBJECT_TYPE_SPECIAL:
3094 case YAFFS_OBJECT_TYPE_DIRECTORY:
3097 case YAFFS_OBJECT_TYPE_SYMLINK:
3098 yaffs_strncpy(oh->alias,
3099 in->variant.symLinkVariant.alias,
3100 YAFFS_MAX_ALIAS_LENGTH);
3101 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3106 yaffs_InitialiseTags(&newTags);
3108 newTags.chunkId = 0;
3109 newTags.objectId = in->objectId;
3110 newTags.serialNumber = in->serial;
3112 /* Add extra info for file header */
3114 newTags.extraHeaderInfoAvailable = 1;
3115 newTags.extraParentObjectId = oh->parentObjectId;
3116 newTags.extraFileLength = oh->fileSize;
3117 newTags.extraIsShrinkHeader = oh->isShrink;
3118 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3119 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3120 newTags.extraObjectType = in->variantType;
3122 /* Create new chunk in NAND */
3124 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3125 (prevChunkId >= 0) ? 1 : 0);
3127 if (newChunkId >= 0) {
3129 in->chunkId = newChunkId;
3131 if (prevChunkId >= 0) {
3132 yaffs_DeleteChunk(dev, prevChunkId, 1,
3136 if(!yaffs_ObjectHasCachedWriteData(in))
3139 /* If this was a shrink, then mark the block that the chunk lives on */
3141 bi = yaffs_GetBlockInfo(in->myDev,
3142 newChunkId /in->myDev-> nChunksPerBlock);
3143 bi->hasShrinkHeader = 1;
3148 retVal = newChunkId;
3153 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3158 /*------------------------ Short Operations Cache ----------------------------------------
3159 * In many situations where there is no high level buffering (eg WinCE) a lot of
3160 * reads might be short sequential reads, and a lot of writes may be short
3161 * sequential writes. eg. scanning/writing a jpeg file.
3162 * In these cases, a short read/write cache can provide a huge perfomance benefit
3163 * with dumb-as-a-rock code.
3164 * In Linux, the page cache provides read buffering aand the short op cache provides write
3167 * There are a limited number (~10) of cache chunks per device so that we don't
3168 * need a very intelligent search.
3171 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3173 yaffs_Device *dev = obj->myDev;
3175 yaffs_ChunkCache *cache;
3176 int nCaches = obj->myDev->nShortOpCaches;
3178 for(i = 0; i < nCaches; i++){
3179 cache = &dev->srCache[i];
3180 if (cache->object == obj &&
3189 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3191 yaffs_Device *dev = obj->myDev;
3192 int lowest = -99; /* Stop compiler whining. */
3194 yaffs_ChunkCache *cache;
3195 int chunkWritten = 0;
3196 int nCaches = obj->myDev->nShortOpCaches;
3202 /* Find the dirty cache for this object with the lowest chunk id. */
3203 for (i = 0; i < nCaches; i++) {
3204 if (dev->srCache[i].object == obj &&
3205 dev->srCache[i].dirty) {
3207 || dev->srCache[i].chunkId <
3209 cache = &dev->srCache[i];
3210 lowest = cache->chunkId;
3215 if (cache && !cache->locked) {
3216 /* Write it out and free it up */
3219 yaffs_WriteChunkDataToObject(cache->object,
3225 cache->object = NULL;
3228 } while (cache && chunkWritten > 0);
3231 /* Hoosterman, disk full while writing cache out. */
3232 T(YAFFS_TRACE_ERROR,
3233 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3240 /*yaffs_FlushEntireDeviceCache(dev)
3245 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3248 int nCaches = dev->nShortOpCaches;
3251 /* Find a dirty object in the cache and flush it...
3252 * until there are no further dirty objects.
3256 for( i = 0; i < nCaches && !obj; i++) {
3257 if (dev->srCache[i].object &&
3258 dev->srCache[i].dirty)
3259 obj = dev->srCache[i].object;
3263 yaffs_FlushFilesChunkCache(obj);
3270 /* Grab us a cache chunk for use.
3271 * First look for an empty one.
3272 * Then look for the least recently used non-dirty one.
3273 * Then look for the least recently used dirty one...., flush and look again.
3275 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3281 if (dev->nShortOpCaches > 0) {
3282 for (i = 0; i < dev->nShortOpCaches; i++) {
3283 if (!dev->srCache[i].object)
3284 return &dev->srCache[i];
3290 usage = 0; /* just to stop the compiler grizzling */
3292 for (i = 0; i < dev->nShortOpCaches; i++) {
3293 if (!dev->srCache[i].dirty &&
3294 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3296 usage = dev->srCache[i].lastUse;
3302 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3309 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3311 yaffs_ChunkCache *cache;
3312 yaffs_Object *theObj;
3317 if (dev->nShortOpCaches > 0) {
3318 /* Try find a non-dirty one... */
3320 cache = yaffs_GrabChunkCacheWorker(dev);
3323 /* They were all dirty, find the last recently used object and flush
3324 * its cache, then find again.
3325 * NB what's here is not very accurate, we actually flush the object
3326 * the last recently used page.
3329 /* With locking we can't assume we can use entry zero */
3336 for (i = 0; i < dev->nShortOpCaches; i++) {
3337 if (dev->srCache[i].object &&
3338 !dev->srCache[i].locked &&
3339 (dev->srCache[i].lastUse < usage || !cache))
3341 usage = dev->srCache[i].lastUse;
3342 theObj = dev->srCache[i].object;
3343 cache = &dev->srCache[i];
3348 if (!cache || cache->dirty) {
3349 /* Flush and try again */
3350 yaffs_FlushFilesChunkCache(theObj);
3351 cache = yaffs_GrabChunkCacheWorker(dev);
3361 /* Find a cached chunk */
3362 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3365 yaffs_Device *dev = obj->myDev;
3367 if (dev->nShortOpCaches > 0) {
3368 for (i = 0; i < dev->nShortOpCaches; i++) {
3369 if (dev->srCache[i].object == obj &&
3370 dev->srCache[i].chunkId == chunkId) {
3373 return &dev->srCache[i];
3380 /* Mark the chunk for the least recently used algorithym */
3381 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3385 if (dev->nShortOpCaches > 0) {
3386 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3387 /* Reset the cache usages */
3389 for (i = 1; i < dev->nShortOpCaches; i++) {
3390 dev->srCache[i].lastUse = 0;
3397 cache->lastUse = dev->srLastUse;
3405 /* Invalidate a single cache page.
3406 * Do this when a whole page gets written,
3407 * ie the short cache for this page is no longer valid.
3409 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3411 if (object->myDev->nShortOpCaches > 0) {
3412 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3415 cache->object = NULL;
3420 /* Invalidate all the cache pages associated with this object
3421 * Do this whenever ther file is deleted or resized.
3423 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3426 yaffs_Device *dev = in->myDev;
3428 if (dev->nShortOpCaches > 0) {
3429 /* Invalidate it. */
3430 for (i = 0; i < dev->nShortOpCaches; i++) {
3431 if (dev->srCache[i].object == in) {
3432 dev->srCache[i].object = NULL;
3438 /*--------------------- Checkpointing --------------------*/
3441 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3443 yaffs_CheckpointValidity cp;
3444 cp.structType = sizeof(cp);
3445 cp.magic = YAFFS_MAGIC;
3446 cp.version = YAFFS_CHECKPOINT_VERSION;
3447 cp.head = (head) ? 1 : 0;
3449 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3453 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3455 yaffs_CheckpointValidity cp;
3458 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3461 ok = (cp.structType == sizeof(cp)) &&
3462 (cp.magic == YAFFS_MAGIC) &&
3463 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
3464 (cp.head == ((head) ? 1 : 0));
3468 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3471 cp->nErasedBlocks = dev->nErasedBlocks;
3472 cp->allocationBlock = dev->allocationBlock;
3473 cp->allocationPage = dev->allocationPage;
3474 cp->nFreeChunks = dev->nFreeChunks;
3476 cp->nDeletedFiles = dev->nDeletedFiles;
3477 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3478 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3479 cp->sequenceNumber = dev->sequenceNumber;
3480 cp->oldestDirtySequence = dev->oldestDirtySequence;
3484 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3485 yaffs_CheckpointDevice *cp)
3487 dev->nErasedBlocks = cp->nErasedBlocks;
3488 dev->allocationBlock = cp->allocationBlock;
3489 dev->allocationPage = cp->allocationPage;
3490 dev->nFreeChunks = cp->nFreeChunks;
3492 dev->nDeletedFiles = cp->nDeletedFiles;
3493 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3494 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3495 dev->sequenceNumber = cp->sequenceNumber;
3496 dev->oldestDirtySequence = cp->oldestDirtySequence;
3500 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3502 yaffs_CheckpointDevice cp;
3504 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3508 /* Write device runtime values*/
3509 yaffs_DeviceToCheckpointDevice(&cp,dev);
3510 cp.structType = sizeof(cp);
3512 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3514 /* Write block info */
3516 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3517 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3520 /* Write chunk bits */
3522 nBytes = nBlocks * dev->chunkBitmapStride;
3523 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3529 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3531 yaffs_CheckpointDevice cp;
3533 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3537 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3541 if(cp.structType != sizeof(cp))
3545 yaffs_CheckpointDeviceToDevice(dev,&cp);
3547 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3549 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3553 nBytes = nBlocks * dev->chunkBitmapStride;
3555 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3560 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3564 cp->objectId = obj->objectId;
3565 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3566 cp->chunkId = obj->chunkId;
3567 cp->variantType = obj->variantType;
3568 cp->deleted = obj->deleted;
3569 cp->softDeleted = obj->softDeleted;
3570 cp->unlinked = obj->unlinked;
3571 cp->fake = obj->fake;
3572 cp->renameAllowed = obj->renameAllowed;
3573 cp->unlinkAllowed = obj->unlinkAllowed;
3574 cp->serial = obj->serial;
3575 cp->nDataChunks = obj->nDataChunks;
3577 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3578 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3579 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3580 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3583 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3586 yaffs_Object *parent;
3588 obj->objectId = cp->objectId;
3591 parent = yaffs_FindOrCreateObjectByNumber(
3594 YAFFS_OBJECT_TYPE_DIRECTORY);
3599 yaffs_AddObjectToDirectory(parent, obj);
3601 obj->chunkId = cp->chunkId;
3602 obj->variantType = cp->variantType;
3603 obj->deleted = cp->deleted;
3604 obj->softDeleted = cp->softDeleted;
3605 obj->unlinked = cp->unlinked;
3606 obj->fake = cp->fake;
3607 obj->renameAllowed = cp->renameAllowed;
3608 obj->unlinkAllowed = cp->unlinkAllowed;
3609 obj->serial = cp->serial;
3610 obj->nDataChunks = cp->nDataChunks;
3612 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3613 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3614 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3615 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3617 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3618 obj->lazyLoaded = 1;
3623 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3624 __u32 level, int chunkOffset)
3627 yaffs_Device *dev = in->myDev;
3629 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3634 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3635 if (tn->internal[i]) {
3636 ok = yaffs_CheckpointTnodeWorker(in,
3639 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3642 } else if (level == 0) {
3643 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3644 /* printf("write tnode at %d\n",baseOffset); */
3645 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3647 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3655 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3657 __u32 endMarker = ~0;
3660 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3661 ok = yaffs_CheckpointTnodeWorker(obj,
3662 obj->variant.fileVariant.top,
3663 obj->variant.fileVariant.topLevel,
3666 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3673 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3677 yaffs_Device *dev = obj->myDev;
3678 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3681 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3683 while(ok && (~baseChunk)){
3684 /* Read level 0 tnode */
3686 /* printf("read tnode at %d\n",baseChunk); */
3687 tn = yaffs_GetTnodeRaw(dev);
3689 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3690 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3695 ok = yaffs_AddOrFindLevel0Tnode(dev,
3702 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3710 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3713 yaffs_CheckpointObject cp;
3716 struct list_head *lh;
3719 /* Iterate through the objects in each hash entry,
3720 * dumping them to the checkpointing stream.
3723 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3724 list_for_each(lh, &dev->objectBucket[i].list) {
3726 obj = list_entry(lh, yaffs_Object, hashLink);
3727 if (!obj->deferedFree) {
3728 yaffs_ObjectToCheckpointObject(&cp,obj);
3729 cp.structType = sizeof(cp);
3731 T(YAFFS_TRACE_CHECKPOINT,(
3732 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3733 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3735 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3737 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3738 ok = yaffs_WriteCheckpointTnodes(obj);
3745 /* Dump end of list */
3746 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3747 cp.structType = sizeof(cp);
3750 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3755 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3758 yaffs_CheckpointObject cp;
3761 yaffs_Object *hardList = NULL;
3763 while(ok && !done) {
3764 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3765 if(cp.structType != sizeof(cp)) {
3766 /* printf("structure parsing failed\n"); */
3770 if(ok && cp.objectId == ~0)
3773 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3774 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3775 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3777 yaffs_CheckpointObjectToObject(obj,&cp);
3778 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3779 ok = yaffs_ReadCheckpointTnodes(obj);
3780 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3781 obj->hardLinks.next =
3782 (struct list_head *)
3792 yaffs_HardlinkFixup(dev,hardList);
3797 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3802 ok = yaffs_CheckpointOpen(dev,1);
3805 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3807 ok = yaffs_WriteCheckpointDevice(dev);
3809 ok = yaffs_WriteCheckpointObjects(dev);
3811 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3813 if(!yaffs_CheckpointClose(dev))
3817 dev->isCheckpointed = 1;
3819 dev->isCheckpointed = 0;
3821 return dev->isCheckpointed;
3824 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3828 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3831 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3833 ok = yaffs_ReadCheckpointDevice(dev);
3835 ok = yaffs_ReadCheckpointObjects(dev);
3837 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3841 if(!yaffs_CheckpointClose(dev))
3845 dev->isCheckpointed = 1;
3847 dev->isCheckpointed = 0;
3853 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3855 if(dev->isCheckpointed ||
3856 dev->blocksInCheckpoint > 0){
3857 dev->isCheckpointed = 0;
3858 yaffs_CheckpointInvalidateStream(dev);
3859 if(dev->superBlock && dev->markSuperBlockDirty)
3860 dev->markSuperBlockDirty(dev->superBlock);
3865 int yaffs_CheckpointSave(yaffs_Device *dev)
3867 yaffs_ReportOddballBlocks(dev);
3868 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3870 if(!dev->isCheckpointed)
3871 yaffs_WriteCheckpointData(dev);
3873 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3875 return dev->isCheckpointed;
3878 int yaffs_CheckpointRestore(yaffs_Device *dev)
3881 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3883 retval = yaffs_ReadCheckpointData(dev);
3885 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3887 yaffs_ReportOddballBlocks(dev);
3892 /*--------------------- File read/write ------------------------
3893 * Read and write have very similar structures.
3894 * In general the read/write has three parts to it
3895 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3896 * Some complete chunks
3897 * An incomplete chunk to end off with
3899 * Curve-balls: the first chunk might also be the last chunk.
3902 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
3911 yaffs_ChunkCache *cache;
3918 //chunk = offset / dev->nDataBytesPerChunk + 1;
3919 //start = offset % dev->nDataBytesPerChunk;
3920 yaffs_AddrToChunk(dev,offset,&chunk,&start);
3923 /* OK now check for the curveball where the start and end are in
3926 if ((start + n) < dev->nDataBytesPerChunk) {
3929 nToCopy = dev->nDataBytesPerChunk - start;
3932 cache = yaffs_FindChunkCache(in, chunk);
3934 /* If the chunk is already in the cache or it is less than a whole chunk
3935 * then use the cache (if there is caching)
3936 * else bypass the cache.
3938 if (cache || nToCopy != dev->nDataBytesPerChunk) {
3939 if (dev->nShortOpCaches > 0) {
3941 /* If we can't find the data in the cache, then load it up. */
3944 cache = yaffs_GrabChunkCache(in->myDev);
3946 cache->chunkId = chunk;
3949 yaffs_ReadChunkDataFromObject(in, chunk,
3955 yaffs_UseChunkCache(dev, cache, 0);
3959 #ifdef CONFIG_YAFFS_WINCE
3960 yfsd_UnlockYAFFS(TRUE);
3962 memcpy(buffer, &cache->data[start], nToCopy);
3964 #ifdef CONFIG_YAFFS_WINCE
3965 yfsd_LockYAFFS(TRUE);
3969 /* Read into the local buffer then copy..*/
3972 yaffs_GetTempBuffer(dev, __LINE__);
3973 yaffs_ReadChunkDataFromObject(in, chunk,
3975 #ifdef CONFIG_YAFFS_WINCE
3976 yfsd_UnlockYAFFS(TRUE);
3978 memcpy(buffer, &localBuffer[start], nToCopy);
3980 #ifdef CONFIG_YAFFS_WINCE
3981 yfsd_LockYAFFS(TRUE);
3983 yaffs_ReleaseTempBuffer(dev, localBuffer,
3988 #ifdef CONFIG_YAFFS_WINCE
3989 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3991 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3992 * This is because we otherwise screw up WinCE's memory mapper
3994 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3996 #ifdef CONFIG_YAFFS_WINCE
3997 yfsd_UnlockYAFFS(TRUE);
3999 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4001 #ifdef CONFIG_YAFFS_WINCE
4002 yfsd_LockYAFFS(TRUE);
4003 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4007 /* A full chunk. Read directly into the supplied buffer. */
4008 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4022 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4023 int nBytes, int writeThrough)
4032 int startOfWrite = offset;
4033 int chunkWritten = 0;
4040 while (n > 0 && chunkWritten >= 0) {
4041 //chunk = offset / dev->nDataBytesPerChunk + 1;
4042 //start = offset % dev->nDataBytesPerChunk;
4043 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4046 /* OK now check for the curveball where the start and end are in
4050 if ((start + n) < dev->nDataBytesPerChunk) {
4053 /* Now folks, to calculate how many bytes to write back....
4054 * If we're overwriting and not writing to then end of file then
4055 * we need to write back as much as was there before.
4059 in->variant.fileVariant.fileSize -
4060 ((chunk - 1) * dev->nDataBytesPerChunk);
4062 if (nBytesRead > dev->nDataBytesPerChunk) {
4063 nBytesRead = dev->nDataBytesPerChunk;
4068 (start + n)) ? nBytesRead : (start + n);
4071 nToCopy = dev->nDataBytesPerChunk - start;
4072 nToWriteBack = dev->nDataBytesPerChunk;
4075 if (nToCopy != dev->nDataBytesPerChunk) {
4076 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4077 if (dev->nShortOpCaches > 0) {
4078 yaffs_ChunkCache *cache;
4079 /* If we can't find the data in the cache, then load the cache */
4080 cache = yaffs_FindChunkCache(in, chunk);
4083 && yaffs_CheckSpaceForAllocation(in->
4085 cache = yaffs_GrabChunkCache(in->myDev);
4087 cache->chunkId = chunk;
4090 yaffs_ReadChunkDataFromObject(in, chunk,
4096 !yaffs_CheckSpaceForAllocation(in->myDev)){
4097 /* Drop the cache if it was a read cache item and
4098 * no space check has been made for it.
4104 yaffs_UseChunkCache(dev, cache, 1);
4106 #ifdef CONFIG_YAFFS_WINCE
4107 yfsd_UnlockYAFFS(TRUE);
4110 memcpy(&cache->data[start], buffer,
4113 #ifdef CONFIG_YAFFS_WINCE
4114 yfsd_LockYAFFS(TRUE);
4117 cache->nBytes = nToWriteBack;
4121 yaffs_WriteChunkDataToObject
4124 cache->data, cache->nBytes,
4130 chunkWritten = -1; /* fail the write */
4133 /* An incomplete start or end chunk (or maybe both start and end chunk)
4134 * Read into the local buffer then copy, then copy over and write back.
4138 yaffs_GetTempBuffer(dev, __LINE__);
4140 yaffs_ReadChunkDataFromObject(in, chunk,
4143 #ifdef CONFIG_YAFFS_WINCE
4144 yfsd_UnlockYAFFS(TRUE);
4147 memcpy(&localBuffer[start], buffer, nToCopy);
4149 #ifdef CONFIG_YAFFS_WINCE
4150 yfsd_LockYAFFS(TRUE);
4153 yaffs_WriteChunkDataToObject(in, chunk,
4158 yaffs_ReleaseTempBuffer(dev, localBuffer,
4165 #ifdef CONFIG_YAFFS_WINCE
4166 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4167 * This is because we otherwise screw up WinCE's memory mapper
4169 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4170 #ifdef CONFIG_YAFFS_WINCE
4171 yfsd_UnlockYAFFS(TRUE);
4173 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4174 #ifdef CONFIG_YAFFS_WINCE
4175 yfsd_LockYAFFS(TRUE);
4178 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4179 dev->nDataBytesPerChunk,
4181 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4183 /* A full chunk. Write directly from the supplied buffer. */
4185 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4186 dev->nDataBytesPerChunk,
4189 /* Since we've overwritten the cached data, we better invalidate it. */
4190 yaffs_InvalidateChunkCache(in, chunk);
4193 if (chunkWritten >= 0) {
4202 /* Update file object */
4204 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4205 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4214 /* ---------------------- File resizing stuff ------------------ */
4216 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4219 yaffs_Device *dev = in->myDev;
4220 int oldFileSize = in->variant.fileVariant.fileSize;
4222 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4224 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4225 dev->nDataBytesPerChunk;
4229 /* Delete backwards so that we don't end up with holes if
4230 * power is lost part-way through the operation.
4232 for (i = lastDel; i >= startDel; i--) {
4233 /* NB this could be optimised somewhat,
4234 * eg. could retrieve the tags and write them without
4235 * using yaffs_DeleteChunk
4238 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4241 (dev->internalStartBlock * dev->nChunksPerBlock)
4243 ((dev->internalEndBlock +
4244 1) * dev->nChunksPerBlock)) {
4245 T(YAFFS_TRACE_ALWAYS,
4246 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4250 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4257 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4260 int oldFileSize = in->variant.fileVariant.fileSize;
4261 int newSizeOfPartialChunk;
4264 yaffs_Device *dev = in->myDev;
4266 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4268 yaffs_FlushFilesChunkCache(in);
4269 yaffs_InvalidateWholeChunkCache(in);
4271 yaffs_CheckGarbageCollection(dev);
4273 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4274 return yaffs_GetFileSize(in);
4277 if (newSize == oldFileSize) {
4281 if (newSize < oldFileSize) {
4283 yaffs_PruneResizedChunks(in, newSize);
4285 if (newSizeOfPartialChunk != 0) {
4286 int lastChunk = 1 + newFullChunks;
4288 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4290 /* Got to read and rewrite the last chunk with its new size and zero pad */
4291 yaffs_ReadChunkDataFromObject(in, lastChunk,
4294 memset(localBuffer + newSizeOfPartialChunk, 0,
4295 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4297 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4298 newSizeOfPartialChunk, 1);
4300 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4303 in->variant.fileVariant.fileSize = newSize;
4305 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4307 /* Write a new object header.
4308 * show we've shrunk the file, if need be
4309 * Do this only if the file is not in the deleted directories.
4311 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4312 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4313 yaffs_UpdateObjectHeader(in, NULL, 0,
4314 (newSize < oldFileSize) ? 1 : 0, 0);
4320 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4322 obj = yaffs_GetEquivalentObject(obj);
4324 switch (obj->variantType) {
4325 case YAFFS_OBJECT_TYPE_FILE:
4326 return obj->variant.fileVariant.fileSize;
4327 case YAFFS_OBJECT_TYPE_SYMLINK:
4328 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4336 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4340 yaffs_FlushFilesChunkCache(in);
4342 #ifdef CONFIG_YAFFS_WINCE
4343 yfsd_WinFileTimeNow(in->win_mtime);
4346 in->yst_mtime = Y_CURRENT_TIME;
4352 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4353 0) ? YAFFS_OK : YAFFS_FAIL;
4362 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4365 /* First off, invalidate the file's data in the cache, without flushing. */
4366 yaffs_InvalidateWholeChunkCache(in);
4368 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4369 /* Move to the unlinked directory so we have a record that it was deleted. */
4370 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4374 yaffs_RemoveObjectFromDirectory(in);
4375 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4378 yaffs_FreeObject(in);
4383 /* yaffs_DeleteFile deletes the whole file data
4384 * and the inode associated with the file.
4385 * It does not delete the links associated with the file.
4387 static int yaffs_UnlinkFile(yaffs_Object * in)
4391 int immediateDeletion = 0;
4396 immediateDeletion = 1;
4400 if (in->inUse <= 0) {
4401 immediateDeletion = 1;
4405 if (immediateDeletion) {
4407 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4409 T(YAFFS_TRACE_TRACING,
4410 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4413 in->myDev->nDeletedFiles++;
4414 if (0 && in->myDev->isYaffs2) {
4415 yaffs_ResizeFile(in, 0);
4417 yaffs_SoftDeleteFile(in);
4420 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4428 int yaffs_DeleteFile(yaffs_Object * in)
4430 int retVal = YAFFS_OK;
4432 if (in->nDataChunks > 0) {
4433 /* Use soft deletion if there is data in the file */
4434 if (!in->unlinked) {
4435 retVal = yaffs_UnlinkFile(in);
4437 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4439 in->myDev->nDeletedFiles++;
4440 yaffs_SoftDeleteFile(in);
4442 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4444 /* The file has no data chunks so we toss it immediately */
4445 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4446 in->variant.fileVariant.top = NULL;
4447 yaffs_DoGenericObjectDeletion(in);
4453 static int yaffs_DeleteDirectory(yaffs_Object * in)
4455 /* First check that the directory is empty. */
4456 if (list_empty(&in->variant.directoryVariant.children)) {
4457 return yaffs_DoGenericObjectDeletion(in);
4464 static int yaffs_DeleteSymLink(yaffs_Object * in)
4466 YFREE(in->variant.symLinkVariant.alias);
4468 return yaffs_DoGenericObjectDeletion(in);
4471 static int yaffs_DeleteHardLink(yaffs_Object * in)
4473 /* remove this hardlink from the list assocaited with the equivalent
4476 list_del(&in->hardLinks);
4477 return yaffs_DoGenericObjectDeletion(in);
4480 static void yaffs_DestroyObject(yaffs_Object * obj)
4482 switch (obj->variantType) {
4483 case YAFFS_OBJECT_TYPE_FILE:
4484 yaffs_DeleteFile(obj);
4486 case YAFFS_OBJECT_TYPE_DIRECTORY:
4487 yaffs_DeleteDirectory(obj);
4489 case YAFFS_OBJECT_TYPE_SYMLINK:
4490 yaffs_DeleteSymLink(obj);
4492 case YAFFS_OBJECT_TYPE_HARDLINK:
4493 yaffs_DeleteHardLink(obj);
4495 case YAFFS_OBJECT_TYPE_SPECIAL:
4496 yaffs_DoGenericObjectDeletion(obj);
4498 case YAFFS_OBJECT_TYPE_UNKNOWN:
4499 break; /* should not happen. */
4503 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4506 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4507 return yaffs_DeleteHardLink(obj);
4508 } else if (!list_empty(&obj->hardLinks)) {
4509 /* Curve ball: We're unlinking an object that has a hardlink.
4511 * This problem arises because we are not strictly following
4512 * The Linux link/inode model.
4514 * We can't really delete the object.
4515 * Instead, we do the following:
4516 * - Select a hardlink.
4517 * - Unhook it from the hard links
4518 * - Unhook it from its parent directory (so that the rename can work)
4519 * - Rename the object to the hardlink's name.
4520 * - Delete the hardlink
4525 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4527 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4529 list_del_init(&hl->hardLinks);
4530 list_del_init(&hl->siblings);
4532 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4534 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4536 if (retVal == YAFFS_OK) {
4537 retVal = yaffs_DoGenericObjectDeletion(hl);
4542 switch (obj->variantType) {
4543 case YAFFS_OBJECT_TYPE_FILE:
4544 return yaffs_UnlinkFile(obj);
4546 case YAFFS_OBJECT_TYPE_DIRECTORY:
4547 return yaffs_DeleteDirectory(obj);
4549 case YAFFS_OBJECT_TYPE_SYMLINK:
4550 return yaffs_DeleteSymLink(obj);
4552 case YAFFS_OBJECT_TYPE_SPECIAL:
4553 return yaffs_DoGenericObjectDeletion(obj);
4555 case YAFFS_OBJECT_TYPE_HARDLINK:
4556 case YAFFS_OBJECT_TYPE_UNKNOWN:
4564 static int yaffs_UnlinkObject( yaffs_Object *obj)
4567 if (obj && obj->unlinkAllowed) {
4568 return yaffs_UnlinkWorker(obj);
4574 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4578 obj = yaffs_FindObjectByName(dir, name);
4579 return yaffs_UnlinkObject(obj);
4582 /*----------------------- Initialisation Scanning ---------------------- */
4584 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4585 int backwardScanning)
4589 if (!backwardScanning) {
4590 /* Handle YAFFS1 forward scanning case
4591 * For YAFFS1 we always do the deletion
4595 /* Handle YAFFS2 case (backward scanning)
4596 * If the shadowed object exists then ignore.
4598 if (yaffs_FindObjectByNumber(dev, objId)) {
4603 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4604 * We put it in unlinked dir to be cleaned up after the scanning
4607 yaffs_FindOrCreateObjectByNumber(dev, objId,
4608 YAFFS_OBJECT_TYPE_FILE);
4609 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4610 obj->variant.fileVariant.shrinkSize = 0;
4611 obj->valid = 1; /* So that we don't read any other info for this file */
4621 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4628 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4630 in = yaffs_FindObjectByNumber(dev,
4631 hl->variant.hardLinkVariant.
4632 equivalentObjectId);
4635 /* Add the hardlink pointers */
4636 hl->variant.hardLinkVariant.equivalentObject = in;
4637 list_add(&hl->hardLinks, &in->hardLinks);
4639 /* Todo Need to report/handle this better.
4640 * Got a problem... hardlink to a non-existant object
4642 hl->variant.hardLinkVariant.equivalentObject = NULL;
4643 INIT_LIST_HEAD(&hl->hardLinks);
4655 static int ybicmp(const void *a, const void *b){
4656 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4657 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4658 register int ablock = ((yaffs_BlockIndex *)a)->block;
4659 register int bblock = ((yaffs_BlockIndex *)b)->block;
4661 return ablock - bblock;
4667 static int yaffs_Scan(yaffs_Device * dev)
4669 yaffs_ExtendedTags tags;
4674 int nBlocksToScan = 0;
4680 yaffs_BlockState state;
4681 yaffs_Object *hardList = NULL;
4683 yaffs_BlockInfo *bi;
4685 yaffs_ObjectHeader *oh;
4687 yaffs_Object *parent;
4688 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4692 yaffs_BlockIndex *blockIndex = NULL;
4694 if (dev->isYaffs2) {
4696 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4700 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4703 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4704 dev->internalStartBlock, dev->internalEndBlock));
4706 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4708 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4710 if (dev->isYaffs2) {
4711 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4714 /* Scan all the blocks to determine their state */
4715 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4716 bi = yaffs_GetBlockInfo(dev, blk);
4717 yaffs_ClearChunkBits(dev, blk);
4719 bi->softDeletions = 0;
4721 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4723 bi->blockState = state;
4724 bi->sequenceNumber = sequenceNumber;
4726 T(YAFFS_TRACE_SCAN_DEBUG,
4727 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4728 state, sequenceNumber));
4730 if (state == YAFFS_BLOCK_STATE_DEAD) {
4731 T(YAFFS_TRACE_BAD_BLOCKS,
4732 (TSTR("block %d is bad" TENDSTR), blk));
4733 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4734 T(YAFFS_TRACE_SCAN_DEBUG,
4735 (TSTR("Block empty " TENDSTR)));
4736 dev->nErasedBlocks++;
4737 dev->nFreeChunks += dev->nChunksPerBlock;
4738 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4740 /* Determine the highest sequence number */
4741 if (dev->isYaffs2 &&
4742 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4743 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4745 blockIndex[nBlocksToScan].seq = sequenceNumber;
4746 blockIndex[nBlocksToScan].block = blk;
4750 if (sequenceNumber >= dev->sequenceNumber) {
4751 dev->sequenceNumber = sequenceNumber;
4753 } else if (dev->isYaffs2) {
4754 /* TODO: Nasty sequence number! */
4757 ("Block scanning block %d has bad sequence number %d"
4758 TENDSTR), blk, sequenceNumber));
4765 * Dungy old bubble sort for now...
4767 if (dev->isYaffs2) {
4768 yaffs_BlockIndex temp;
4772 for (i = 0; i < nBlocksToScan; i++)
4773 for (j = i + 1; j < nBlocksToScan; j++)
4774 if (blockIndex[i].seq > blockIndex[j].seq) {
4775 temp = blockIndex[j];
4776 blockIndex[j] = blockIndex[i];
4777 blockIndex[i] = temp;
4781 /* Now scan the blocks looking at the data. */
4782 if (dev->isYaffs2) {
4784 endIterator = nBlocksToScan - 1;
4785 T(YAFFS_TRACE_SCAN_DEBUG,
4786 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4788 startIterator = dev->internalStartBlock;
4789 endIterator = dev->internalEndBlock;
4792 /* For each block.... */
4793 for (blockIterator = startIterator; blockIterator <= endIterator;
4796 if (dev->isYaffs2) {
4797 /* get the block to scan in the correct order */
4798 blk = blockIndex[blockIterator].block;
4800 blk = blockIterator;
4803 bi = yaffs_GetBlockInfo(dev, blk);
4804 state = bi->blockState;
4808 /* For each chunk in each block that needs scanning....*/
4809 for (c = 0; c < dev->nChunksPerBlock &&
4810 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4811 /* Read the tags and decide what to do */
4812 chunk = blk * dev->nChunksPerBlock + c;
4814 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4817 /* Let's have a good look at this chunk... */
4819 if (!dev->isYaffs2 && tags.chunkDeleted) {
4825 /*T((" %d %d deleted\n",blk,c)); */
4826 } else if (!tags.chunkUsed) {
4827 /* An unassigned chunk in the block
4828 * This means that either the block is empty or
4829 * this is the one being allocated from
4833 /* We're looking at the first chunk in the block so the block is unused */
4834 state = YAFFS_BLOCK_STATE_EMPTY;
4835 dev->nErasedBlocks++;
4837 /* this is the block being allocated from */
4840 (" Allocating from %d %d" TENDSTR),
4842 state = YAFFS_BLOCK_STATE_ALLOCATING;
4843 dev->allocationBlock = blk;
4844 dev->allocationPage = c;
4845 dev->allocationBlockFinder = blk;
4846 /* Set it to here to encourage the allocator to go forth from here. */
4848 /* Yaffs2 sanity check:
4849 * This should be the one with the highest sequence number
4852 && (dev->sequenceNumber !=
4853 bi->sequenceNumber)) {
4854 T(YAFFS_TRACE_ALWAYS,
4856 ("yaffs: Allocation block %d was not highest sequence id:"
4857 " block seq = %d, dev seq = %d"
4858 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4862 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4863 } else if (tags.chunkId > 0) {
4864 /* chunkId > 0 so it is a data chunk... */
4865 unsigned int endpos;
4867 yaffs_SetChunkBit(dev, blk, c);
4870 in = yaffs_FindOrCreateObjectByNumber(dev,
4873 YAFFS_OBJECT_TYPE_FILE);
4874 /* PutChunkIntoFile checks for a clash (two data chunks with
4875 * the same chunkId).
4877 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4880 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
4882 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4883 && in->variant.fileVariant.scannedFileSize <
4885 in->variant.fileVariant.
4886 scannedFileSize = endpos;
4887 if (!dev->useHeaderFileSize) {
4888 in->variant.fileVariant.
4890 in->variant.fileVariant.
4895 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4897 /* chunkId == 0, so it is an ObjectHeader.
4898 * Thus, we read in the object header and make the object
4900 yaffs_SetChunkBit(dev, blk, c);
4903 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4907 oh = (yaffs_ObjectHeader *) chunkData;
4909 in = yaffs_FindObjectByNumber(dev,
4911 if (in && in->variantType != oh->type) {
4912 /* This should not happen, but somehow
4913 * Wev'e ended up with an objectId that has been reused but not yet
4914 * deleted, and worse still it has changed type. Delete the old object.
4917 yaffs_DestroyObject(in);
4922 in = yaffs_FindOrCreateObjectByNumber(dev,
4927 if (oh->shadowsObject > 0) {
4928 yaffs_HandleShadowedObject(dev,
4935 /* We have already filled this one. We have a duplicate and need to resolve it. */
4937 unsigned existingSerial = in->serial;
4938 unsigned newSerial = tags.serialNumber;
4940 if (dev->isYaffs2 ||
4941 ((existingSerial + 1) & 3) ==
4943 /* Use new one - destroy the exisiting one */
4944 yaffs_DeleteChunk(dev,
4949 /* Use existing - destroy this one. */
4950 yaffs_DeleteChunk(dev, chunk, 1,
4956 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4957 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4958 /* We only load some info, don't fiddle with directory structure */
4960 in->variantType = oh->type;
4962 in->yst_mode = oh->yst_mode;
4963 #ifdef CONFIG_YAFFS_WINCE
4964 in->win_atime[0] = oh->win_atime[0];
4965 in->win_ctime[0] = oh->win_ctime[0];
4966 in->win_mtime[0] = oh->win_mtime[0];
4967 in->win_atime[1] = oh->win_atime[1];
4968 in->win_ctime[1] = oh->win_ctime[1];
4969 in->win_mtime[1] = oh->win_mtime[1];
4971 in->yst_uid = oh->yst_uid;
4972 in->yst_gid = oh->yst_gid;
4973 in->yst_atime = oh->yst_atime;
4974 in->yst_mtime = oh->yst_mtime;
4975 in->yst_ctime = oh->yst_ctime;
4976 in->yst_rdev = oh->yst_rdev;
4978 in->chunkId = chunk;
4980 } else if (!in->valid) {
4981 /* we need to load this info */
4984 in->variantType = oh->type;
4986 in->yst_mode = oh->yst_mode;
4987 #ifdef CONFIG_YAFFS_WINCE
4988 in->win_atime[0] = oh->win_atime[0];
4989 in->win_ctime[0] = oh->win_ctime[0];
4990 in->win_mtime[0] = oh->win_mtime[0];
4991 in->win_atime[1] = oh->win_atime[1];
4992 in->win_ctime[1] = oh->win_ctime[1];
4993 in->win_mtime[1] = oh->win_mtime[1];
4995 in->yst_uid = oh->yst_uid;
4996 in->yst_gid = oh->yst_gid;
4997 in->yst_atime = oh->yst_atime;
4998 in->yst_mtime = oh->yst_mtime;
4999 in->yst_ctime = oh->yst_ctime;
5000 in->yst_rdev = oh->yst_rdev;
5002 in->chunkId = chunk;
5004 yaffs_SetObjectName(in, oh->name);
5007 /* directory stuff...
5012 yaffs_FindOrCreateObjectByNumber
5013 (dev, oh->parentObjectId,
5014 YAFFS_OBJECT_TYPE_DIRECTORY);
5015 if (parent->variantType ==
5016 YAFFS_OBJECT_TYPE_UNKNOWN) {
5017 /* Set up as a directory */
5018 parent->variantType =
5019 YAFFS_OBJECT_TYPE_DIRECTORY;
5020 INIT_LIST_HEAD(&parent->variant.
5023 } else if (parent->variantType !=
5024 YAFFS_OBJECT_TYPE_DIRECTORY)
5026 /* Hoosterman, another problem....
5027 * We're trying to use a non-directory as a directory
5030 T(YAFFS_TRACE_ERROR,
5032 ("yaffs tragedy: attempting to use non-directory as"
5033 " a directory in scan. Put in lost+found."
5035 parent = dev->lostNFoundDir;
5038 yaffs_AddObjectToDirectory(parent, in);
5040 if (0 && (parent == dev->deletedDir ||
5041 parent == dev->unlinkedDir)) {
5042 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5043 dev->nDeletedFiles++;
5045 /* Note re hardlinks.
5046 * Since we might scan a hardlink before its equivalent object is scanned
5047 * we put them all in a list.
5048 * After scanning is complete, we should have all the objects, so we run through this
5049 * list and fix up all the chains.
5052 switch (in->variantType) {
5053 case YAFFS_OBJECT_TYPE_UNKNOWN:
5054 /* Todo got a problem */
5056 case YAFFS_OBJECT_TYPE_FILE:
5059 /* Prune back the shrunken chunks */
5060 yaffs_PruneResizedChunks
5062 /* Mark the block as having a shrinkHeader */
5063 bi->hasShrinkHeader = 1;
5066 if (dev->useHeaderFileSize)
5068 in->variant.fileVariant.
5073 case YAFFS_OBJECT_TYPE_HARDLINK:
5074 in->variant.hardLinkVariant.
5075 equivalentObjectId =
5076 oh->equivalentObjectId;
5077 in->hardLinks.next =
5078 (struct list_head *)
5082 case YAFFS_OBJECT_TYPE_DIRECTORY:
5085 case YAFFS_OBJECT_TYPE_SPECIAL:
5088 case YAFFS_OBJECT_TYPE_SYMLINK:
5089 in->variant.symLinkVariant.
5091 yaffs_CloneString(oh->alias);
5095 if (parent == dev->deletedDir) {
5096 yaffs_DestroyObject(in);
5097 bi->hasShrinkHeader = 1;
5103 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5104 /* If we got this far while scanning, then the block is fully allocated.*/
5105 state = YAFFS_BLOCK_STATE_FULL;
5108 bi->blockState = state;
5110 /* Now let's see if it was dirty */
5111 if (bi->pagesInUse == 0 &&
5112 !bi->hasShrinkHeader &&
5113 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5114 yaffs_BlockBecameDirty(dev, blk);
5124 /* Ok, we've done all the scanning.
5125 * Fix up the hard link chains.
5126 * We should now have scanned all the objects, now it's time to add these
5130 yaffs_HardlinkFixup(dev,hardList);
5132 /* Handle the unlinked files. Since they were left in an unlinked state we should
5136 struct list_head *i;
5137 struct list_head *n;
5140 /* Soft delete all the unlinked files */
5141 list_for_each_safe(i, n,
5142 &dev->unlinkedDir->variant.directoryVariant.
5145 l = list_entry(i, yaffs_Object, siblings);
5146 yaffs_DestroyObject(l);
5151 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5153 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5158 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5161 yaffs_ObjectHeader *oh;
5162 yaffs_Device *dev = in->myDev;
5163 yaffs_ExtendedTags tags;
5167 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5169 in->lazyLoaded ? "not yet" : "already"));
5174 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5176 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5177 oh = (yaffs_ObjectHeader *) chunkData;
5179 in->yst_mode = oh->yst_mode;
5180 #ifdef CONFIG_YAFFS_WINCE
5181 in->win_atime[0] = oh->win_atime[0];
5182 in->win_ctime[0] = oh->win_ctime[0];
5183 in->win_mtime[0] = oh->win_mtime[0];
5184 in->win_atime[1] = oh->win_atime[1];
5185 in->win_ctime[1] = oh->win_ctime[1];
5186 in->win_mtime[1] = oh->win_mtime[1];
5188 in->yst_uid = oh->yst_uid;
5189 in->yst_gid = oh->yst_gid;
5190 in->yst_atime = oh->yst_atime;
5191 in->yst_mtime = oh->yst_mtime;
5192 in->yst_ctime = oh->yst_ctime;
5193 in->yst_rdev = oh->yst_rdev;
5196 yaffs_SetObjectName(in, oh->name);
5198 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5199 in->variant.symLinkVariant.alias =
5200 yaffs_CloneString(oh->alias);
5202 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5206 static int yaffs_ScanBackwards(yaffs_Device * dev)
5208 yaffs_ExtendedTags tags;
5213 int nBlocksToScan = 0;
5219 yaffs_BlockState state;
5220 yaffs_Object *hardList = NULL;
5221 yaffs_BlockInfo *bi;
5223 yaffs_ObjectHeader *oh;
5225 yaffs_Object *parent;
5226 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5232 int foundChunksInBlock;
5233 int equivalentObjectId;
5236 yaffs_BlockIndex *blockIndex = NULL;
5237 int altBlockIndex = 0;
5239 if (!dev->isYaffs2) {
5241 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5247 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5248 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5251 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5253 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5256 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5262 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5266 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5268 /* Scan all the blocks to determine their state */
5269 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5270 bi = yaffs_GetBlockInfo(dev, blk);
5271 yaffs_ClearChunkBits(dev, blk);
5273 bi->softDeletions = 0;
5275 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5277 bi->blockState = state;
5278 bi->sequenceNumber = sequenceNumber;
5280 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5281 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5283 T(YAFFS_TRACE_SCAN_DEBUG,
5284 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5285 state, sequenceNumber));
5288 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5289 /* todo .. fix free space ? */
5291 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5292 T(YAFFS_TRACE_BAD_BLOCKS,
5293 (TSTR("block %d is bad" TENDSTR), blk));
5294 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5295 T(YAFFS_TRACE_SCAN_DEBUG,
5296 (TSTR("Block empty " TENDSTR)));
5297 dev->nErasedBlocks++;
5298 dev->nFreeChunks += dev->nChunksPerBlock;
5299 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5301 /* Determine the highest sequence number */
5302 if (dev->isYaffs2 &&
5303 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5304 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5306 blockIndex[nBlocksToScan].seq = sequenceNumber;
5307 blockIndex[nBlocksToScan].block = blk;
5311 if (sequenceNumber >= dev->sequenceNumber) {
5312 dev->sequenceNumber = sequenceNumber;
5314 } else if (dev->isYaffs2) {
5315 /* TODO: Nasty sequence number! */
5318 ("Block scanning block %d has bad sequence number %d"
5319 TENDSTR), blk, sequenceNumber));
5326 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5332 /* Sort the blocks */
5333 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5335 /* Use qsort now. */
5336 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5340 /* Dungy old bubble sort... */
5342 yaffs_BlockIndex temp;
5346 for (i = 0; i < nBlocksToScan; i++)
5347 for (j = i + 1; j < nBlocksToScan; j++)
5348 if (blockIndex[i].seq > blockIndex[j].seq) {
5349 temp = blockIndex[j];
5350 blockIndex[j] = blockIndex[i];
5351 blockIndex[i] = temp;
5358 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5360 /* Now scan the blocks looking at the data. */
5362 endIterator = nBlocksToScan - 1;
5363 T(YAFFS_TRACE_SCAN_DEBUG,
5364 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5366 /* For each block.... backwards */
5367 for (blockIterator = endIterator; blockIterator >= startIterator;
5369 /* Cooperative multitasking! This loop can run for so
5370 long that watchdog timers expire. */
5373 /* get the block to scan in the correct order */
5374 blk = blockIndex[blockIterator].block;
5376 bi = yaffs_GetBlockInfo(dev, blk);
5377 state = bi->blockState;
5381 /* For each chunk in each block that needs scanning.... */
5382 foundChunksInBlock = 0;
5383 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5384 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5385 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5386 /* Scan backwards...
5387 * Read the tags and decide what to do
5389 chunk = blk * dev->nChunksPerBlock + c;
5391 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5394 /* Let's have a good look at this chunk... */
5396 if (!tags.chunkUsed) {
5397 /* An unassigned chunk in the block.
5398 * If there are used chunks after this one, then
5399 * it is a chunk that was skipped due to failing the erased
5400 * check. Just skip it so that it can be deleted.
5401 * But, more typically, We get here when this is an unallocated
5402 * chunk and his means that either the block is empty or
5403 * this is the one being allocated from
5406 if(foundChunksInBlock)
5408 /* This is a chunk that was skipped due to failing the erased check */
5410 } else if (c == 0) {
5411 /* We're looking at the first chunk in the block so the block is unused */
5412 state = YAFFS_BLOCK_STATE_EMPTY;
5413 dev->nErasedBlocks++;
5415 /* this is the block being allocated from */
5417 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5420 (" Allocating from %d %d"
5423 state = YAFFS_BLOCK_STATE_ALLOCATING;
5424 dev->allocationBlock = blk;
5425 dev->allocationPage = c;
5426 dev->allocationBlockFinder = blk;
5427 /* Set it to here to encourage the allocator to
5428 * go forth from here.
5431 /* Yaffs2 sanity check:
5432 * This should be the one with the highest sequence number
5435 && (dev->sequenceNumber !=
5436 bi->sequenceNumber)) {
5437 T(YAFFS_TRACE_ALWAYS,
5439 ("yaffs: Allocation block %d was not highest sequence "
5440 "id: block seq = %d, dev seq = %d"
5443 dev->sequenceNumber));
5448 } else if (tags.chunkId > 0) {
5449 /* chunkId > 0 so it is a data chunk... */
5450 unsigned int endpos;
5452 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
5454 foundChunksInBlock = 1;
5457 yaffs_SetChunkBit(dev, blk, c);
5460 in = yaffs_FindOrCreateObjectByNumber(dev,
5463 YAFFS_OBJECT_TYPE_FILE);
5464 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5466 in->variant.fileVariant.shrinkSize) {
5467 /* This has not been invalidated by a resize */
5468 yaffs_PutChunkIntoFile(in, tags.chunkId,
5471 /* File size is calculated by looking at the data chunks if we have not
5472 * seen an object header yet. Stop this practice once we find an object header.
5476 1) * dev->nDataBytesPerChunk +
5479 if (!in->valid && /* have not got an object header yet */
5480 in->variant.fileVariant.
5481 scannedFileSize < endpos) {
5482 in->variant.fileVariant.
5483 scannedFileSize = endpos;
5484 in->variant.fileVariant.
5486 in->variant.fileVariant.
5491 /* This chunk has been invalidated by a resize, so delete */
5492 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5496 /* chunkId == 0, so it is an ObjectHeader.
5497 * Thus, we read in the object header and make the object
5499 foundChunksInBlock = 1;
5501 yaffs_SetChunkBit(dev, blk, c);
5507 if (tags.extraHeaderInfoAvailable) {
5508 in = yaffs_FindOrCreateObjectByNumber
5509 (dev, tags.objectId,
5510 tags.extraObjectType);
5514 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5517 tags.extraShadows ||
5519 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5520 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5523 /* If we don't have valid info then we need to read the chunk
5524 * TODO In future we can probably defer reading the chunk and
5525 * living with invalid data until needed.
5528 result = yaffs_ReadChunkWithTagsFromNAND(dev,
5533 oh = (yaffs_ObjectHeader *) chunkData;
5536 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5541 /* TODO Hoosterman we have a problem! */
5542 T(YAFFS_TRACE_ERROR,
5544 ("yaffs tragedy: Could not make object for object %d "
5545 "at chunk %d during scan"
5546 TENDSTR), tags.objectId, chunk));
5551 /* We have already filled this one.
5552 * We have a duplicate that will be discarded, but
5553 * we first have to suck out resize info if it is a file.
5556 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5558 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5559 (tags.extraHeaderInfoAvailable &&
5560 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5563 (oh) ? oh->fileSize : tags.
5565 __u32 parentObjectId =
5567 parentObjectId : tags.
5568 extraParentObjectId;
5570 (oh) ? oh->isShrink : tags.
5571 extraIsShrinkHeader;
5573 /* If it is deleted (unlinked at start also means deleted)
5574 * we treat the file size as being zeroed at this point.
5576 if (parentObjectId ==
5577 YAFFS_OBJECTID_DELETED
5578 || parentObjectId ==
5579 YAFFS_OBJECTID_UNLINKED) {
5585 in->variant.fileVariant.
5586 shrinkSize > thisSize) {
5587 in->variant.fileVariant.
5593 bi->hasShrinkHeader = 1;
5597 /* Use existing - destroy this one. */
5598 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5603 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5605 YAFFS_OBJECTID_LOSTNFOUND)) {
5606 /* We only load some info, don't fiddle with directory structure */
5610 in->variantType = oh->type;
5612 in->yst_mode = oh->yst_mode;
5613 #ifdef CONFIG_YAFFS_WINCE
5614 in->win_atime[0] = oh->win_atime[0];
5615 in->win_ctime[0] = oh->win_ctime[0];
5616 in->win_mtime[0] = oh->win_mtime[0];
5617 in->win_atime[1] = oh->win_atime[1];
5618 in->win_ctime[1] = oh->win_ctime[1];
5619 in->win_mtime[1] = oh->win_mtime[1];
5621 in->yst_uid = oh->yst_uid;
5622 in->yst_gid = oh->yst_gid;
5623 in->yst_atime = oh->yst_atime;
5624 in->yst_mtime = oh->yst_mtime;
5625 in->yst_ctime = oh->yst_ctime;
5626 in->yst_rdev = oh->yst_rdev;
5630 in->variantType = tags.extraObjectType;
5634 in->chunkId = chunk;
5636 } else if (!in->valid) {
5637 /* we need to load this info */
5640 in->chunkId = chunk;
5643 in->variantType = oh->type;
5645 in->yst_mode = oh->yst_mode;
5646 #ifdef CONFIG_YAFFS_WINCE
5647 in->win_atime[0] = oh->win_atime[0];
5648 in->win_ctime[0] = oh->win_ctime[0];
5649 in->win_mtime[0] = oh->win_mtime[0];
5650 in->win_atime[1] = oh->win_atime[1];
5651 in->win_ctime[1] = oh->win_ctime[1];
5652 in->win_mtime[1] = oh->win_mtime[1];
5654 in->yst_uid = oh->yst_uid;
5655 in->yst_gid = oh->yst_gid;
5656 in->yst_atime = oh->yst_atime;
5657 in->yst_mtime = oh->yst_mtime;
5658 in->yst_ctime = oh->yst_ctime;
5659 in->yst_rdev = oh->yst_rdev;
5662 if (oh->shadowsObject > 0)
5663 yaffs_HandleShadowedObject(dev,
5669 yaffs_SetObjectName(in, oh->name);
5671 yaffs_FindOrCreateObjectByNumber
5672 (dev, oh->parentObjectId,
5673 YAFFS_OBJECT_TYPE_DIRECTORY);
5675 fileSize = oh->fileSize;
5676 isShrink = oh->isShrink;
5677 equivalentObjectId = oh->equivalentObjectId;
5681 in->variantType = tags.extraObjectType;
5683 yaffs_FindOrCreateObjectByNumber
5684 (dev, tags.extraParentObjectId,
5685 YAFFS_OBJECT_TYPE_DIRECTORY);
5686 fileSize = tags.extraFileLength;
5687 isShrink = tags.extraIsShrinkHeader;
5688 equivalentObjectId = tags.extraEquivalentObjectId;
5694 /* directory stuff...
5698 if (parent->variantType ==
5699 YAFFS_OBJECT_TYPE_UNKNOWN) {
5700 /* Set up as a directory */
5701 parent->variantType =
5702 YAFFS_OBJECT_TYPE_DIRECTORY;
5703 INIT_LIST_HEAD(&parent->variant.
5706 } else if (parent->variantType !=
5707 YAFFS_OBJECT_TYPE_DIRECTORY)
5709 /* Hoosterman, another problem....
5710 * We're trying to use a non-directory as a directory
5713 T(YAFFS_TRACE_ERROR,
5715 ("yaffs tragedy: attempting to use non-directory as"
5716 " a directory in scan. Put in lost+found."
5718 parent = dev->lostNFoundDir;
5721 yaffs_AddObjectToDirectory(parent, in);
5723 itsUnlinked = (parent == dev->deletedDir) ||
5724 (parent == dev->unlinkedDir);
5727 /* Mark the block as having a shrinkHeader */
5728 bi->hasShrinkHeader = 1;
5731 /* Note re hardlinks.
5732 * Since we might scan a hardlink before its equivalent object is scanned
5733 * we put them all in a list.
5734 * After scanning is complete, we should have all the objects, so we run
5735 * through this list and fix up all the chains.
5738 switch (in->variantType) {
5739 case YAFFS_OBJECT_TYPE_UNKNOWN:
5740 /* Todo got a problem */
5742 case YAFFS_OBJECT_TYPE_FILE:
5744 if (in->variant.fileVariant.
5745 scannedFileSize < fileSize) {
5746 /* This covers the case where the file size is greater
5747 * than where the data is
5748 * This will happen if the file is resized to be larger
5749 * than its current data extents.
5751 in->variant.fileVariant.fileSize = fileSize;
5752 in->variant.fileVariant.scannedFileSize =
5753 in->variant.fileVariant.fileSize;
5757 in->variant.fileVariant.shrinkSize > fileSize) {
5758 in->variant.fileVariant.shrinkSize = fileSize;
5762 case YAFFS_OBJECT_TYPE_HARDLINK:
5764 in->variant.hardLinkVariant.equivalentObjectId =
5766 in->hardLinks.next =
5767 (struct list_head *) hardList;
5771 case YAFFS_OBJECT_TYPE_DIRECTORY:
5774 case YAFFS_OBJECT_TYPE_SPECIAL:
5777 case YAFFS_OBJECT_TYPE_SYMLINK:
5779 in->variant.symLinkVariant.alias =
5780 yaffs_CloneString(oh->
5789 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5790 /* If we got this far while scanning, then the block is fully allocated. */
5791 state = YAFFS_BLOCK_STATE_FULL;
5794 bi->blockState = state;
5796 /* Now let's see if it was dirty */
5797 if (bi->pagesInUse == 0 &&
5798 !bi->hasShrinkHeader &&
5799 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5800 yaffs_BlockBecameDirty(dev, blk);
5806 YFREE_ALT(blockIndex);
5810 /* Ok, we've done all the scanning.
5811 * Fix up the hard link chains.
5812 * We should now have scanned all the objects, now it's time to add these
5815 yaffs_HardlinkFixup(dev,hardList);
5819 * Sort out state of unlinked and deleted objects.
5822 struct list_head *i;
5823 struct list_head *n;
5827 /* Soft delete all the unlinked files */
5828 list_for_each_safe(i, n,
5829 &dev->unlinkedDir->variant.directoryVariant.
5832 l = list_entry(i, yaffs_Object, siblings);
5833 yaffs_DestroyObject(l);
5837 /* Soft delete all the deletedDir files */
5838 list_for_each_safe(i, n,
5839 &dev->deletedDir->variant.directoryVariant.
5842 l = list_entry(i, yaffs_Object, siblings);
5843 yaffs_DestroyObject(l);
5849 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5851 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5856 /*------------------------------ Directory Functions ----------------------------- */
5858 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5860 yaffs_Device *dev = obj->myDev;
5862 if(dev && dev->removeObjectCallback)
5863 dev->removeObjectCallback(obj);
5865 list_del_init(&obj->siblings);
5870 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5875 T(YAFFS_TRACE_ALWAYS,
5877 ("tragedy: Trying to add an object to a null pointer directory"
5881 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5882 T(YAFFS_TRACE_ALWAYS,
5884 ("tragedy: Trying to add an object to a non-directory"
5889 if (obj->siblings.prev == NULL) {
5890 /* Not initialised */
5891 INIT_LIST_HEAD(&obj->siblings);
5893 } else if (!list_empty(&obj->siblings)) {
5894 /* If it is holed up somewhere else, un hook it */
5895 yaffs_RemoveObjectFromDirectory(obj);
5898 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5899 obj->parent = directory;
5901 if (directory == obj->myDev->unlinkedDir
5902 || directory == obj->myDev->deletedDir) {
5904 obj->myDev->nUnlinkedFiles++;
5905 obj->renameAllowed = 0;
5909 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5914 struct list_head *i;
5915 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5924 T(YAFFS_TRACE_ALWAYS,
5926 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5930 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5931 T(YAFFS_TRACE_ALWAYS,
5933 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5937 sum = yaffs_CalcNameSum(name);
5939 list_for_each(i, &directory->variant.directoryVariant.children) {
5941 l = list_entry(i, yaffs_Object, siblings);
5943 yaffs_CheckObjectDetailsLoaded(l);
5945 /* Special case for lost-n-found */
5946 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5947 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5950 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5952 /* LostnFound cunk called Objxxx
5955 yaffs_GetObjectName(l, buffer,
5956 YAFFS_MAX_NAME_LENGTH);
5957 if (yaffs_strcmp(name, buffer) == 0) {
5970 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5971 int (*fn) (yaffs_Object *))
5973 struct list_head *i;
5977 T(YAFFS_TRACE_ALWAYS,
5979 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5983 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5984 T(YAFFS_TRACE_ALWAYS,
5986 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5990 list_for_each(i, &theDir->variant.directoryVariant.children) {
5992 l = list_entry(i, yaffs_Object, siblings);
6004 /* GetEquivalentObject dereferences any hard links to get to the
6008 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6010 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6011 /* We want the object id of the equivalent object, not this one */
6012 obj = obj->variant.hardLinkVariant.equivalentObject;
6018 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6020 memset(name, 0, buffSize * sizeof(YCHAR));
6022 yaffs_CheckObjectDetailsLoaded(obj);
6024 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6025 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6026 } else if (obj->chunkId <= 0) {
6028 /* make up a name */
6029 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6031 yaffs_strncpy(name, locName, buffSize - 1);
6034 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6035 else if (obj->shortName[0]) {
6036 yaffs_strcpy(name, obj->shortName);
6041 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6043 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6045 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6047 if (obj->chunkId >= 0) {
6048 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6049 obj->chunkId, buffer,
6052 yaffs_strncpy(name, oh->name, buffSize - 1);
6054 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6057 return yaffs_strlen(name);
6060 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6063 /* Dereference any hard linking */
6064 obj = yaffs_GetEquivalentObject(obj);
6066 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6067 return obj->variant.fileVariant.fileSize;
6069 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6070 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6072 /* Only a directory should drop through to here */
6073 return obj->myDev->nDataBytesPerChunk;
6077 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6080 struct list_head *i;
6082 if (!obj->unlinked) {
6083 count++; /* the object itself */
6085 list_for_each(i, &obj->hardLinks) {
6086 count++; /* add the hard links; */
6092 int yaffs_GetObjectInode(yaffs_Object * obj)
6094 obj = yaffs_GetEquivalentObject(obj);
6096 return obj->objectId;
6099 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6101 obj = yaffs_GetEquivalentObject(obj);
6103 switch (obj->variantType) {
6104 case YAFFS_OBJECT_TYPE_FILE:
6107 case YAFFS_OBJECT_TYPE_DIRECTORY:
6110 case YAFFS_OBJECT_TYPE_SYMLINK:
6113 case YAFFS_OBJECT_TYPE_HARDLINK:
6116 case YAFFS_OBJECT_TYPE_SPECIAL:
6117 if (S_ISFIFO(obj->yst_mode))
6119 if (S_ISCHR(obj->yst_mode))
6121 if (S_ISBLK(obj->yst_mode))
6123 if (S_ISSOCK(obj->yst_mode))
6131 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6133 obj = yaffs_GetEquivalentObject(obj);
6134 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6135 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6137 return yaffs_CloneString(_Y(""));
6141 #ifndef CONFIG_YAFFS_WINCE
6143 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6145 unsigned int valid = attr->ia_valid;
6147 if (valid & ATTR_MODE)
6148 obj->yst_mode = attr->ia_mode;
6149 if (valid & ATTR_UID)
6150 obj->yst_uid = attr->ia_uid;
6151 if (valid & ATTR_GID)
6152 obj->yst_gid = attr->ia_gid;
6154 if (valid & ATTR_ATIME)
6155 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6156 if (valid & ATTR_CTIME)
6157 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6158 if (valid & ATTR_MTIME)
6159 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6161 if (valid & ATTR_SIZE)
6162 yaffs_ResizeFile(obj, attr->ia_size);
6164 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6169 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6171 unsigned int valid = 0;
6173 attr->ia_mode = obj->yst_mode;
6175 attr->ia_uid = obj->yst_uid;
6177 attr->ia_gid = obj->yst_gid;
6180 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6181 valid |= ATTR_ATIME;
6182 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6183 valid |= ATTR_CTIME;
6184 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6185 valid |= ATTR_MTIME;
6187 attr->ia_size = yaffs_GetFileSize(obj);
6190 attr->ia_valid = valid;
6199 int yaffs_DumpObject(yaffs_Object * obj)
6203 yaffs_GetObjectName(obj, name, 256);
6205 T(YAFFS_TRACE_ALWAYS,
6207 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6208 " chunk %d type %d size %d\n"
6209 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6210 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6211 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6217 /*---------------------------- Initialisation code -------------------------------------- */
6219 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6222 /* Common functions, gotta have */
6223 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6226 #ifdef CONFIG_YAFFS_YAFFS2
6228 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6229 if (dev->writeChunkWithTagsToNAND &&
6230 dev->readChunkWithTagsFromNAND &&
6231 !dev->writeChunkToNAND &&
6232 !dev->readChunkFromNAND &&
6233 dev->markNANDBlockBad && dev->queryNANDBlock)
6237 /* Can use the "spare" style interface for yaffs1 */
6238 if (!dev->isYaffs2 &&
6239 !dev->writeChunkWithTagsToNAND &&
6240 !dev->readChunkWithTagsFromNAND &&
6241 dev->writeChunkToNAND &&
6242 dev->readChunkFromNAND &&
6243 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6250 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6252 /* Initialise the unlinked, deleted, root and lost and found directories */
6254 dev->lostNFoundDir = dev->rootDir = NULL;
6255 dev->unlinkedDir = dev->deletedDir = NULL;
6258 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6260 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6263 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6264 YAFFS_ROOT_MODE | S_IFDIR);
6265 dev->lostNFoundDir =
6266 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6267 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6268 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6271 int yaffs_GutsInitialise(yaffs_Device * dev)
6276 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6278 /* Check stuff that must be set */
6281 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6285 dev->internalStartBlock = dev->startBlock;
6286 dev->internalEndBlock = dev->endBlock;
6287 dev->blockOffset = 0;
6288 dev->chunkOffset = 0;
6289 dev->nFreeChunks = 0;
6291 if (dev->startBlock == 0) {
6292 dev->internalStartBlock = dev->startBlock + 1;
6293 dev->internalEndBlock = dev->endBlock + 1;
6294 dev->blockOffset = 1;
6295 dev->chunkOffset = dev->nChunksPerBlock;
6298 /* Check geometry parameters. */
6300 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
6301 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
6302 dev->nChunksPerBlock < 2 ||
6303 dev->nReservedBlocks < 2 ||
6304 dev->internalStartBlock <= 0 ||
6305 dev->internalEndBlock <= 0 ||
6306 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6308 T(YAFFS_TRACE_ALWAYS,
6310 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6311 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6315 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6316 T(YAFFS_TRACE_ALWAYS,
6317 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6321 /* Got the right mix of functions? */
6322 if (!yaffs_CheckDevFunctions(dev)) {
6323 /* Function missing */
6324 T(YAFFS_TRACE_ALWAYS,
6326 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6331 /* This is really a compilation check. */
6332 if (!yaffs_CheckStructures()) {
6333 T(YAFFS_TRACE_ALWAYS,
6334 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6338 if (dev->isMounted) {
6339 T(YAFFS_TRACE_ALWAYS,
6340 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6344 /* Finished with most checks. One or two more checks happen later on too. */
6350 /* OK now calculate a few things for the device */
6353 * Calculate all the chunk size manipulation numbers:
6355 /* Start off assuming it is a power of 2 */
6356 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
6357 dev->chunkMask = (1<<dev->chunkShift) - 1;
6359 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
6360 /* Yes it is a power of 2, disable crumbs */
6362 dev->crumbShift = 0;
6363 dev->crumbsPerChunk = 0;
6365 /* Not a power of 2, use crumbs instead */
6366 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
6367 dev->crumbMask = (1<<dev->crumbShift)-1;
6368 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
6369 dev->chunkShift = 0;
6375 * Calculate chunkGroupBits.
6376 * We need to find the next power of 2 > than internalEndBlock
6379 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6383 /* Set up tnode width if wide tnodes are enabled. */
6384 if(!dev->wideTnodesDisabled){
6385 /* bits must be even so that we end up with 32-bit words */
6389 dev->tnodeWidth = 16;
6391 dev->tnodeWidth = bits;
6394 dev->tnodeWidth = 16;
6396 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6398 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6399 * so if the bitwidth of the
6400 * chunk range we're using is greater than 16 we need
6401 * to figure out chunk shift and chunkGroupSize
6404 if (bits <= dev->tnodeWidth)
6405 dev->chunkGroupBits = 0;
6407 dev->chunkGroupBits = bits - dev->tnodeWidth;
6410 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6412 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6413 /* We have a problem because the soft delete won't work if
6414 * the chunk group size > chunks per block.
6415 * This can be remedied by using larger "virtual blocks".
6417 T(YAFFS_TRACE_ALWAYS,
6418 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6423 /* OK, we've finished verifying the device, lets continue with initialisation */
6425 /* More device initialisation */
6426 dev->garbageCollections = 0;
6427 dev->passiveGarbageCollections = 0;
6428 dev->currentDirtyChecker = 0;
6429 dev->bufferedBlock = -1;
6430 dev->doingBufferedBlockRewrite = 0;
6431 dev->nDeletedFiles = 0;
6432 dev->nBackgroundDeletions = 0;
6433 dev->nUnlinkedFiles = 0;
6435 dev->eccUnfixed = 0;
6436 dev->tagsEccFixed = 0;
6437 dev->tagsEccUnfixed = 0;
6438 dev->nErasureFailures = 0;
6439 dev->nErasedBlocks = 0;
6441 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
6443 /* Initialise temporary buffers and caches. */
6446 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6447 dev->tempBuffer[i].line = 0; /* not in use */
6448 dev->tempBuffer[i].buffer =
6449 YMALLOC_DMA(dev->nDataBytesPerChunk);
6453 if (dev->nShortOpCaches > 0) {
6456 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6457 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6461 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6463 for (i = 0; i < dev->nShortOpCaches; i++) {
6464 dev->srCache[i].object = NULL;
6465 dev->srCache[i].lastUse = 0;
6466 dev->srCache[i].dirty = 0;
6467 dev->srCache[i].data = YMALLOC_DMA(dev->nDataBytesPerChunk);
6474 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6476 if (dev->isYaffs2) {
6477 dev->useHeaderFileSize = 1;
6480 yaffs_InitialiseBlocks(dev);
6481 yaffs_InitialiseTnodes(dev);
6482 yaffs_InitialiseObjects(dev);
6484 yaffs_CreateInitialDirectories(dev);
6487 /* Now scan the flash. */
6488 if (dev->isYaffs2) {
6489 if(yaffs_CheckpointRestore(dev)) {
6490 T(YAFFS_TRACE_ALWAYS,
6491 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6494 /* Clean up the mess caused by an aborted checkpoint load
6495 * and scan backwards.
6497 yaffs_DeinitialiseBlocks(dev);
6498 yaffs_DeinitialiseTnodes(dev);
6499 yaffs_DeinitialiseObjects(dev);
6500 yaffs_InitialiseBlocks(dev);
6501 yaffs_InitialiseTnodes(dev);
6502 yaffs_InitialiseObjects(dev);
6503 yaffs_CreateInitialDirectories(dev);
6505 yaffs_ScanBackwards(dev);
6510 /* Zero out stats */
6511 dev->nPageReads = 0;
6512 dev->nPageWrites = 0;
6513 dev->nBlockErasures = 0;
6515 dev->nRetriedWrites = 0;
6517 dev->nRetiredBlocks = 0;
6519 yaffs_VerifyFreeChunks(dev);
6521 T(YAFFS_TRACE_TRACING,
6522 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6527 void yaffs_Deinitialise(yaffs_Device * dev)
6529 if (dev->isMounted) {
6532 yaffs_DeinitialiseBlocks(dev);
6533 yaffs_DeinitialiseTnodes(dev);
6534 yaffs_DeinitialiseObjects(dev);
6535 if (dev->nShortOpCaches > 0) {
6537 for (i = 0; i < dev->nShortOpCaches; i++) {
6538 YFREE(dev->srCache[i].data);
6541 YFREE(dev->srCache);
6544 YFREE(dev->gcCleanupList);
6546 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6547 YFREE(dev->tempBuffer[i].buffer);
6555 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6560 yaffs_BlockInfo *blk;
6562 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6564 blk = yaffs_GetBlockInfo(dev, b);
6566 switch (blk->blockState) {
6567 case YAFFS_BLOCK_STATE_EMPTY:
6568 case YAFFS_BLOCK_STATE_ALLOCATING:
6569 case YAFFS_BLOCK_STATE_COLLECTING:
6570 case YAFFS_BLOCK_STATE_FULL:
6572 (dev->nChunksPerBlock - blk->pagesInUse +
6573 blk->softDeletions);
6584 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6586 /* This is what we report to the outside world */
6589 int nDirtyCacheChunks;
6590 int blocksForCheckpoint;
6593 nFree = dev->nFreeChunks;
6595 nFree = yaffs_CountFreeChunks(dev);
6598 nFree += dev->nDeletedFiles;
6600 /* Now count the number of dirty chunks in the cache and subtract those */
6604 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6605 if (dev->srCache[i].dirty)
6606 nDirtyCacheChunks++;
6610 nFree -= nDirtyCacheChunks;
6612 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6614 /* Now we figure out how much to reserve for the checkpoint and report that... */
6615 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6616 if(blocksForCheckpoint < 0)
6617 blocksForCheckpoint = 0;
6619 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6628 static int yaffs_freeVerificationFailures;
6630 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6632 int counted = yaffs_CountFreeChunks(dev);
6634 int difference = dev->nFreeChunks - counted;
6637 T(YAFFS_TRACE_ALWAYS,
6638 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6639 dev->nFreeChunks, counted, difference));
6640 yaffs_freeVerificationFailures++;
6644 /*---------------------------------------- YAFFS test code ----------------------*/
6646 #define yaffs_CheckStruct(structure,syze, name) \
6647 if(sizeof(structure) != syze) \
6649 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6650 name,syze,sizeof(structure))); \
6651 return YAFFS_FAIL; \
6654 static int yaffs_CheckStructures(void)
6656 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6657 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6658 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6659 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6660 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6662 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")