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.42 2006-11-08 00:33:29 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)
534 for(i = dev->internalStartBlock; i <= dev->internalEndBlock && (yaffs_traceMask & YAFFS_TRACE_BAD_BLOCKS); i++){
535 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
536 if(bi->needsRetiring || bi->gcPrioritise)
537 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("yaffs block %d%s%s" TENDSTR),
539 bi->needsRetiring ? " needs retiring" : "",
540 bi->gcPrioritise ? " gc prioritised" : ""));
545 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
548 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
549 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
551 yaffs_HandleChunkError(dev,bi);
555 /* Was an actual write failure, so mark the block for retirement */
556 bi->needsRetiring = 1;
557 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
558 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
563 /* Delete the chunk */
564 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
568 /*---------------- Name handling functions ------------*/
570 static __u16 yaffs_CalcNameSum(const YCHAR * name)
575 YUCHAR *bname = (YUCHAR *) name;
577 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
579 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
580 sum += yaffs_toupper(*bname) * i;
591 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
593 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
594 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
595 yaffs_strcpy(obj->shortName, name);
597 obj->shortName[0] = _Y('\0');
600 obj->sum = yaffs_CalcNameSum(name);
603 /*-------------------- TNODES -------------------
605 * List of spare tnodes
606 * The list is hooked together using the first pointer
610 /* yaffs_CreateTnodes creates a bunch more tnodes and
611 * adds them to the tnode free list.
612 * Don't use this function directly
615 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
619 yaffs_Tnode *newTnodes;
623 yaffs_TnodeList *tnl;
628 /* Calculate the tnode size in bytes for variable width tnode support.
629 * Must be a multiple of 32-bits */
630 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
632 /* make these things */
634 newTnodes = YMALLOC(nTnodes * tnodeSize);
635 mem = (__u8 *)newTnodes;
639 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
643 /* Hook them into the free list */
645 for (i = 0; i < nTnodes - 1; i++) {
646 newTnodes[i].internal[0] = &newTnodes[i + 1];
647 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
648 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
652 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
653 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
654 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
656 dev->freeTnodes = newTnodes;
658 /* New hookup for wide tnodes */
659 for(i = 0; i < nTnodes -1; i++) {
660 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
661 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
662 curr->internal[0] = next;
665 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
666 curr->internal[0] = dev->freeTnodes;
667 dev->freeTnodes = (yaffs_Tnode *)mem;
672 dev->nFreeTnodes += nTnodes;
673 dev->nTnodesCreated += nTnodes;
675 /* Now add this bunch of tnodes to a list for freeing up.
676 * NB If we can't add this to the management list it isn't fatal
677 * but it just means we can't free this bunch of tnodes later.
680 tnl = YMALLOC(sizeof(yaffs_TnodeList));
684 ("yaffs: Could not add tnodes to management list" TENDSTR)));
687 tnl->tnodes = newTnodes;
688 tnl->next = dev->allocatedTnodeList;
689 dev->allocatedTnodeList = tnl;
692 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
697 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
699 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
701 yaffs_Tnode *tn = NULL;
703 /* If there are none left make more */
704 if (!dev->freeTnodes) {
705 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
708 if (dev->freeTnodes) {
709 tn = dev->freeTnodes;
710 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
711 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
712 /* Hoosterman, this thing looks like it isn't in the list */
713 T(YAFFS_TRACE_ALWAYS,
714 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
717 dev->freeTnodes = dev->freeTnodes->internal[0];
724 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
726 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
729 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
734 /* FreeTnode frees up a tnode and puts it back on the free list */
735 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
738 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
739 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
740 /* Hoosterman, this thing looks like it is already in the list */
741 T(YAFFS_TRACE_ALWAYS,
742 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
744 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
746 tn->internal[0] = dev->freeTnodes;
747 dev->freeTnodes = tn;
752 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
754 /* Free the list of allocated tnodes */
755 yaffs_TnodeList *tmp;
757 while (dev->allocatedTnodeList) {
758 tmp = dev->allocatedTnodeList->next;
760 YFREE(dev->allocatedTnodeList->tnodes);
761 YFREE(dev->allocatedTnodeList);
762 dev->allocatedTnodeList = tmp;
766 dev->freeTnodes = NULL;
767 dev->nFreeTnodes = 0;
770 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
772 dev->allocatedTnodeList = NULL;
773 dev->freeTnodes = NULL;
774 dev->nFreeTnodes = 0;
775 dev->nTnodesCreated = 0;
780 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
782 __u32 *map = (__u32 *)tn;
788 pos &= YAFFS_TNODES_LEVEL0_MASK;
789 val >>= dev->chunkGroupBits;
791 bitInMap = pos * dev->tnodeWidth;
792 wordInMap = bitInMap /32;
793 bitInWord = bitInMap & (32 -1);
795 mask = dev->tnodeMask << bitInWord;
797 map[wordInMap] &= ~mask;
798 map[wordInMap] |= (mask & (val << bitInWord));
800 if(dev->tnodeWidth > (32-bitInWord)) {
801 bitInWord = (32 - bitInWord);
803 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
804 map[wordInMap] &= ~mask;
805 map[wordInMap] |= (mask & (val >> bitInWord));
809 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
811 __u32 *map = (__u32 *)tn;
817 pos &= YAFFS_TNODES_LEVEL0_MASK;
819 bitInMap = pos * dev->tnodeWidth;
820 wordInMap = bitInMap /32;
821 bitInWord = bitInMap & (32 -1);
823 val = map[wordInMap] >> bitInWord;
825 if(dev->tnodeWidth > (32-bitInWord)) {
826 bitInWord = (32 - bitInWord);
828 val |= (map[wordInMap] << bitInWord);
831 val &= dev->tnodeMask;
832 val <<= dev->chunkGroupBits;
837 /* ------------------- End of individual tnode manipulation -----------------*/
839 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
840 * The look up tree is represented by the top tnode and the number of topLevel
841 * in the tree. 0 means only the level 0 tnode is in the tree.
844 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
845 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
846 yaffs_FileStructure * fStruct,
850 yaffs_Tnode *tn = fStruct->top;
852 int requiredTallness;
853 int level = fStruct->topLevel;
855 /* Check sane level and chunk Id */
856 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
860 if (chunkId > YAFFS_MAX_CHUNK_ID) {
864 /* First check we're tall enough (ie enough topLevel) */
866 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
867 requiredTallness = 0;
869 i >>= YAFFS_TNODES_INTERNAL_BITS;
873 if (requiredTallness > fStruct->topLevel) {
874 /* Not tall enough, so we can't find it, return NULL. */
878 /* Traverse down to level 0 */
879 while (level > 0 && tn) {
882 ( YAFFS_TNODES_LEVEL0_BITS +
884 YAFFS_TNODES_INTERNAL_BITS)
886 YAFFS_TNODES_INTERNAL_MASK];
894 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
895 * This happens in two steps:
896 * 1. If the tree isn't tall enough, then make it taller.
897 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
899 * Used when modifying the tree.
901 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
902 * be plugged into the ttree.
905 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
906 yaffs_FileStructure * fStruct,
908 yaffs_Tnode *passedTn)
911 int requiredTallness;
919 /* Check sane level and page Id */
920 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
924 if (chunkId > YAFFS_MAX_CHUNK_ID) {
928 /* First check we're tall enough (ie enough topLevel) */
930 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
931 requiredTallness = 0;
933 x >>= YAFFS_TNODES_INTERNAL_BITS;
938 if (requiredTallness > fStruct->topLevel) {
939 /* Not tall enough,gotta make the tree taller */
940 for (i = fStruct->topLevel; i < requiredTallness; i++) {
942 tn = yaffs_GetTnode(dev);
945 tn->internal[0] = fStruct->top;
949 (TSTR("yaffs: no more tnodes" TENDSTR)));
953 fStruct->topLevel = requiredTallness;
956 /* Traverse down to level 0, adding anything we need */
958 l = fStruct->topLevel;
962 while (l > 0 && tn) {
964 ( YAFFS_TNODES_LEVEL0_BITS +
965 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
966 YAFFS_TNODES_INTERNAL_MASK;
969 if((l>1) && !tn->internal[x]){
970 /* Add missing non-level-zero tnode */
971 tn->internal[x] = yaffs_GetTnode(dev);
974 /* Looking from level 1 at level 0 */
976 /* If we already have one, then release it.*/
978 yaffs_FreeTnode(dev,tn->internal[x]);
979 tn->internal[x] = passedTn;
981 } else if(!tn->internal[x]) {
982 /* Don't have one, none passed in */
983 tn->internal[x] = yaffs_GetTnode(dev);
987 tn = tn->internal[x];
993 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
994 yaffs_FreeTnode(dev,passedTn);
1001 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1002 yaffs_ExtendedTags * tags, int objectId,
1007 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1008 if (yaffs_CheckChunkBit
1009 (dev, theChunk / dev->nChunksPerBlock,
1010 theChunk % dev->nChunksPerBlock)) {
1011 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1013 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1025 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1026 * chunks and tnodes in the file
1027 * Returns 1 if the tree was deleted.
1028 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1031 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1032 int chunkOffset, int *limit)
1037 yaffs_ExtendedTags tags;
1039 yaffs_Device *dev = in->myDev;
1046 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1048 if (tn->internal[i]) {
1049 if (limit && (*limit) < 0) {
1053 yaffs_DeleteWorker(in,
1061 YAFFS_TNODES_INTERNAL_BITS)
1066 yaffs_FreeTnode(dev,
1069 tn->internal[i] = NULL;
1074 return (allDone) ? 1 : 0;
1075 } else if (level == 0) {
1078 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1080 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1085 YAFFS_TNODES_LEVEL0_BITS) + i;
1088 yaffs_FindChunkInGroup(dev,
1094 if (foundChunk > 0) {
1095 yaffs_DeleteChunk(dev,
1100 *limit = *limit - 1;
1108 yaffs_PutLevel0Tnode(dev,tn,i,0);
1112 return (i < 0) ? 1 : 0;
1122 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1125 yaffs_BlockInfo *theBlock;
1127 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1129 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1131 theBlock->softDeletions++;
1136 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1137 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1139 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1142 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1143 __u32 level, int chunkOffset)
1148 yaffs_Device *dev = in->myDev;
1153 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1155 if (tn->internal[i]) {
1157 yaffs_SoftDeleteWorker(in,
1163 YAFFS_TNODES_INTERNAL_BITS)
1166 yaffs_FreeTnode(dev,
1169 tn->internal[i] = NULL;
1171 /* Hoosterman... how could this happen? */
1175 return (allDone) ? 1 : 0;
1176 } else if (level == 0) {
1178 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1179 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1181 /* Note this does not find the real chunk, only the chunk group.
1182 * We make an assumption that a chunk group is not larger than
1185 yaffs_SoftDeleteChunk(dev, theChunk);
1186 yaffs_PutLevel0Tnode(dev,tn,i,0);
1200 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1203 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1204 if (obj->nDataChunks <= 0) {
1205 /* Empty file with no duplicate object headers, just delete it immediately */
1206 yaffs_FreeTnode(obj->myDev,
1207 obj->variant.fileVariant.top);
1208 obj->variant.fileVariant.top = NULL;
1209 T(YAFFS_TRACE_TRACING,
1210 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1212 yaffs_DoGenericObjectDeletion(obj);
1214 yaffs_SoftDeleteWorker(obj,
1215 obj->variant.fileVariant.top,
1216 obj->variant.fileVariant.
1218 obj->softDeleted = 1;
1223 /* Pruning removes any part of the file structure tree that is beyond the
1224 * bounds of the file (ie that does not point to chunks).
1226 * A file should only get pruned when its size is reduced.
1228 * Before pruning, the chunks must be pulled from the tree and the
1229 * level 0 tnode entries must be zeroed out.
1230 * Could also use this for file deletion, but that's probably better handled
1231 * by a special case.
1234 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1235 __u32 level, int del0)
1243 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1244 if (tn->internal[i] && level > 0) {
1246 yaffs_PruneWorker(dev, tn->internal[i],
1248 (i == 0) ? del0 : 1);
1251 if (tn->internal[i]) {
1256 if (hasData == 0 && del0) {
1257 /* Free and return NULL */
1259 yaffs_FreeTnode(dev, tn);
1269 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1270 yaffs_FileStructure * fStruct)
1277 if (fStruct->topLevel > 0) {
1279 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1281 /* Now we have a tree with all the non-zero branches NULL but the height
1282 * is the same as it was.
1283 * Let's see if we can trim internal tnodes to shorten the tree.
1284 * We can do this if only the 0th element in the tnode is in use
1285 * (ie all the non-zero are NULL)
1288 while (fStruct->topLevel && !done) {
1292 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1293 if (tn->internal[i]) {
1299 fStruct->top = tn->internal[0];
1300 fStruct->topLevel--;
1301 yaffs_FreeTnode(dev, tn);
1311 /*-------------------- End of File Structure functions.-------------------*/
1313 /* yaffs_CreateFreeObjects creates a bunch more objects and
1314 * adds them to the object free list.
1316 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1319 yaffs_Object *newObjects;
1320 yaffs_ObjectList *list;
1325 /* make these things */
1326 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1329 T(YAFFS_TRACE_ALLOCATE,
1330 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1334 /* Hook them into the free list */
1335 for (i = 0; i < nObjects - 1; i++) {
1336 newObjects[i].siblings.next =
1337 (struct list_head *)(&newObjects[i + 1]);
1340 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1341 dev->freeObjects = newObjects;
1342 dev->nFreeObjects += nObjects;
1343 dev->nObjectsCreated += nObjects;
1345 /* Now add this bunch of Objects to a list for freeing up. */
1347 list = YMALLOC(sizeof(yaffs_ObjectList));
1349 T(YAFFS_TRACE_ALLOCATE,
1350 (TSTR("Could not add objects to management list" TENDSTR)));
1352 list->objects = newObjects;
1353 list->next = dev->allocatedObjectList;
1354 dev->allocatedObjectList = list;
1361 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1362 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1364 yaffs_Object *tn = NULL;
1366 /* If there are none left make more */
1367 if (!dev->freeObjects) {
1368 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1371 if (dev->freeObjects) {
1372 tn = dev->freeObjects;
1374 (yaffs_Object *) (dev->freeObjects->siblings.next);
1375 dev->nFreeObjects--;
1377 /* Now sweeten it up... */
1379 memset(tn, 0, sizeof(yaffs_Object));
1382 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1383 INIT_LIST_HEAD(&(tn->hardLinks));
1384 INIT_LIST_HEAD(&(tn->hashLink));
1385 INIT_LIST_HEAD(&tn->siblings);
1387 /* Add it to the lost and found directory.
1388 * NB Can't put root or lostNFound in lostNFound so
1389 * check if lostNFound exists first
1391 if (dev->lostNFoundDir) {
1392 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1399 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1404 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1406 obj->fake = 1; /* it is fake so it has no NAND presence... */
1407 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1408 obj->unlinkAllowed = 0; /* ... or unlink it */
1411 obj->yst_mode = mode;
1413 obj->chunkId = 0; /* Not a valid chunk. */
1420 static void yaffs_UnhashObject(yaffs_Object * tn)
1423 yaffs_Device *dev = tn->myDev;
1425 /* If it is still linked into the bucket list, free from the list */
1426 if (!list_empty(&tn->hashLink)) {
1427 list_del_init(&tn->hashLink);
1428 bucket = yaffs_HashFunction(tn->objectId);
1429 dev->objectBucket[bucket].count--;
1434 /* FreeObject frees up a Object and puts it back on the free list */
1435 static void yaffs_FreeObject(yaffs_Object * tn)
1438 yaffs_Device *dev = tn->myDev;
1442 /* We're still hooked up to a cached inode.
1443 * Don't delete now, but mark for later deletion
1445 tn->deferedFree = 1;
1450 yaffs_UnhashObject(tn);
1452 /* Link into the free list. */
1453 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1454 dev->freeObjects = tn;
1455 dev->nFreeObjects++;
1460 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1462 if (obj->deferedFree) {
1463 yaffs_FreeObject(obj);
1469 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1471 /* Free the list of allocated Objects */
1473 yaffs_ObjectList *tmp;
1475 while (dev->allocatedObjectList) {
1476 tmp = dev->allocatedObjectList->next;
1477 YFREE(dev->allocatedObjectList->objects);
1478 YFREE(dev->allocatedObjectList);
1480 dev->allocatedObjectList = tmp;
1483 dev->freeObjects = NULL;
1484 dev->nFreeObjects = 0;
1487 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1491 dev->allocatedObjectList = NULL;
1492 dev->freeObjects = NULL;
1493 dev->nFreeObjects = 0;
1495 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1496 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1497 dev->objectBucket[i].count = 0;
1502 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1507 int lowest = 999999;
1509 /* First let's see if we can find one that's empty. */
1511 for (i = 0; i < 10 && lowest > 0; i++) {
1513 x %= YAFFS_NOBJECT_BUCKETS;
1514 if (dev->objectBucket[x].count < lowest) {
1515 lowest = dev->objectBucket[x].count;
1521 /* If we didn't find an empty list, then try
1522 * looking a bit further for a short one
1525 for (i = 0; i < 10 && lowest > 3; i++) {
1527 x %= YAFFS_NOBJECT_BUCKETS;
1528 if (dev->objectBucket[x].count < lowest) {
1529 lowest = dev->objectBucket[x].count;
1538 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1540 int bucket = yaffs_FindNiceObjectBucket(dev);
1542 /* Now find an object value that has not already been taken
1543 * by scanning the list.
1547 struct list_head *i;
1549 __u32 n = (__u32) bucket;
1551 /* yaffs_CheckObjectHashSanity(); */
1555 n += YAFFS_NOBJECT_BUCKETS;
1556 if (1 || dev->objectBucket[bucket].count > 0) {
1557 list_for_each(i, &dev->objectBucket[bucket].list) {
1558 /* If there is already one in the list */
1560 && list_entry(i, yaffs_Object,
1561 hashLink)->objectId == n) {
1572 static void yaffs_HashObject(yaffs_Object * in)
1574 int bucket = yaffs_HashFunction(in->objectId);
1575 yaffs_Device *dev = in->myDev;
1577 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1578 dev->objectBucket[bucket].count++;
1582 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1584 int bucket = yaffs_HashFunction(number);
1585 struct list_head *i;
1588 list_for_each(i, &dev->objectBucket[bucket].list) {
1589 /* Look if it is in the list */
1591 in = list_entry(i, yaffs_Object, hashLink);
1592 if (in->objectId == number) {
1594 /* Don't tell the VFS about this one if it is defered free */
1595 if (in->deferedFree)
1607 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1608 yaffs_ObjectType type)
1611 yaffs_Object *theObject;
1614 number = yaffs_CreateNewObjectNumber(dev);
1617 theObject = yaffs_AllocateEmptyObject(dev);
1620 theObject->fake = 0;
1621 theObject->renameAllowed = 1;
1622 theObject->unlinkAllowed = 1;
1623 theObject->objectId = number;
1624 yaffs_HashObject(theObject);
1625 theObject->variantType = type;
1626 #ifdef CONFIG_YAFFS_WINCE
1627 yfsd_WinFileTimeNow(theObject->win_atime);
1628 theObject->win_ctime[0] = theObject->win_mtime[0] =
1629 theObject->win_atime[0];
1630 theObject->win_ctime[1] = theObject->win_mtime[1] =
1631 theObject->win_atime[1];
1635 theObject->yst_atime = theObject->yst_mtime =
1636 theObject->yst_ctime = Y_CURRENT_TIME;
1639 case YAFFS_OBJECT_TYPE_FILE:
1640 theObject->variant.fileVariant.fileSize = 0;
1641 theObject->variant.fileVariant.scannedFileSize = 0;
1642 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1643 theObject->variant.fileVariant.topLevel = 0;
1644 theObject->variant.fileVariant.top =
1645 yaffs_GetTnode(dev);
1647 case YAFFS_OBJECT_TYPE_DIRECTORY:
1648 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1651 case YAFFS_OBJECT_TYPE_SYMLINK:
1652 case YAFFS_OBJECT_TYPE_HARDLINK:
1653 case YAFFS_OBJECT_TYPE_SPECIAL:
1654 /* No action required */
1656 case YAFFS_OBJECT_TYPE_UNKNOWN:
1657 /* todo this should not happen */
1665 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1667 yaffs_ObjectType type)
1669 yaffs_Object *theObject = NULL;
1672 theObject = yaffs_FindObjectByNumber(dev, number);
1676 theObject = yaffs_CreateNewObject(dev, number, type);
1684 static YCHAR *yaffs_CloneString(const YCHAR * str)
1686 YCHAR *newStr = NULL;
1689 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1690 yaffs_strcpy(newStr, str);
1698 * Mknod (create) a new object.
1699 * equivalentObject only has meaning for a hard link;
1700 * aliasString only has meaning for a sumlink.
1701 * rdev only has meaning for devices (a subset of special objects)
1704 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1705 yaffs_Object * parent,
1710 yaffs_Object * equivalentObject,
1711 const YCHAR * aliasString, __u32 rdev)
1715 yaffs_Device *dev = parent->myDev;
1717 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1718 if (yaffs_FindObjectByName(parent, name)) {
1722 in = yaffs_CreateNewObject(dev, -1, type);
1727 in->variantType = type;
1729 in->yst_mode = mode;
1731 #ifdef CONFIG_YAFFS_WINCE
1732 yfsd_WinFileTimeNow(in->win_atime);
1733 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1734 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1737 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1739 in->yst_rdev = rdev;
1743 in->nDataChunks = 0;
1745 yaffs_SetObjectName(in, name);
1748 yaffs_AddObjectToDirectory(parent, in);
1750 in->myDev = parent->myDev;
1753 case YAFFS_OBJECT_TYPE_SYMLINK:
1754 in->variant.symLinkVariant.alias =
1755 yaffs_CloneString(aliasString);
1757 case YAFFS_OBJECT_TYPE_HARDLINK:
1758 in->variant.hardLinkVariant.equivalentObject =
1760 in->variant.hardLinkVariant.equivalentObjectId =
1761 equivalentObject->objectId;
1762 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1764 case YAFFS_OBJECT_TYPE_FILE:
1765 case YAFFS_OBJECT_TYPE_DIRECTORY:
1766 case YAFFS_OBJECT_TYPE_SPECIAL:
1767 case YAFFS_OBJECT_TYPE_UNKNOWN:
1772 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1773 /* Could not create the object header, fail the creation */
1774 yaffs_DestroyObject(in);
1783 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1784 __u32 mode, __u32 uid, __u32 gid)
1786 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1787 uid, gid, NULL, NULL, 0);
1790 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1791 __u32 mode, __u32 uid, __u32 gid)
1793 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1794 mode, uid, gid, NULL, NULL, 0);
1797 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1798 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1800 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1801 uid, gid, NULL, NULL, rdev);
1804 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1805 __u32 mode, __u32 uid, __u32 gid,
1806 const YCHAR * alias)
1808 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1809 uid, gid, NULL, alias, 0);
1812 /* yaffs_Link returns the object id of the equivalent object.*/
1813 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1814 yaffs_Object * equivalentObject)
1816 /* Get the real object in case we were fed a hard link as an equivalent object */
1817 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1819 if (yaffs_MknodObject
1820 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1821 equivalentObject, NULL, 0)) {
1822 return equivalentObject;
1829 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1830 const YCHAR * newName, int force, int shadows)
1835 yaffs_Object *existingTarget;
1837 if (newDir == NULL) {
1838 newDir = obj->parent; /* use the old directory */
1841 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1842 T(YAFFS_TRACE_ALWAYS,
1844 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1849 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1850 if (obj->myDev->isYaffs2) {
1851 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1853 unlinkOp = (newDir == obj->myDev->unlinkedDir
1854 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1857 deleteOp = (newDir == obj->myDev->deletedDir);
1859 existingTarget = yaffs_FindObjectByName(newDir, newName);
1861 /* If the object is a file going into the unlinked directory,
1862 * then it is OK to just stuff it in since duplicate names are allowed.
1863 * else only proceed if the new name does not exist and if we're putting
1864 * it into a directory.
1871 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1872 yaffs_SetObjectName(obj, newName);
1875 yaffs_AddObjectToDirectory(newDir, obj);
1880 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1881 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1888 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1889 yaffs_Object * newDir, const YCHAR * newName)
1892 yaffs_Object *existingTarget;
1895 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1896 /* Special case for case insemsitive systems (eg. WinCE).
1897 * While look-up is case insensitive, the name isn't.
1898 * Therefore we might want to change x.txt to X.txt
1900 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1905 obj = yaffs_FindObjectByName(oldDir, oldName);
1906 /* Check new name to long. */
1907 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1908 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1911 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1912 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1916 if (obj && obj->renameAllowed) {
1918 /* Now do the handling for an existing target, if there is one */
1920 existingTarget = yaffs_FindObjectByName(newDir, newName);
1921 if (existingTarget &&
1922 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1923 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1924 /* There is a target that is a non-empty directory, so we fail */
1925 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1926 } else if (existingTarget && existingTarget != obj) {
1927 /* Nuke the target first, using shadowing,
1928 * but only if it isn't the same object
1930 yaffs_ChangeObjectName(obj, newDir, newName, force,
1931 existingTarget->objectId);
1932 yaffs_UnlinkObject(existingTarget);
1935 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1940 /*------------------------- Block Management and Page Allocation ----------------*/
1942 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1944 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1946 dev->allocationBlock = -1; /* force it to get a new one */
1948 /* Todo we're assuming the malloc will pass. */
1949 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1950 if(!dev->blockInfo){
1951 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1952 dev->blockInfoAlt = 1;
1955 dev->blockInfoAlt = 0;
1957 /* Set up dynamic blockinfo stuff. */
1958 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
1959 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1960 if(!dev->chunkBits){
1961 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1962 dev->chunkBitsAlt = 1;
1965 dev->chunkBitsAlt = 0;
1967 if (dev->blockInfo && dev->chunkBits) {
1968 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1969 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1977 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1979 if(dev->blockInfoAlt)
1980 YFREE_ALT(dev->blockInfo);
1982 YFREE(dev->blockInfo);
1983 dev->blockInfoAlt = 0;
1985 dev->blockInfo = NULL;
1987 if(dev->chunkBitsAlt)
1988 YFREE_ALT(dev->chunkBits);
1990 YFREE(dev->chunkBits);
1991 dev->chunkBitsAlt = 0;
1992 dev->chunkBits = NULL;
1995 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1996 yaffs_BlockInfo * bi)
2003 return 1; /* disqualification only applies to yaffs2. */
2005 if (!bi->hasShrinkHeader)
2006 return 1; /* can gc */
2008 /* Find the oldest dirty sequence number if we don't know it and save it
2009 * so we don't have to keep recomputing it.
2011 if (!dev->oldestDirtySequence) {
2012 seq = dev->sequenceNumber;
2014 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2016 b = yaffs_GetBlockInfo(dev, i);
2017 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2018 (b->pagesInUse - b->softDeletions) <
2019 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2020 seq = b->sequenceNumber;
2023 dev->oldestDirtySequence = seq;
2026 /* Can't do gc of this block if there are any blocks older than this one that have
2029 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2033 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2034 * for garbage collection.
2037 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2041 int b = dev->currentDirtyChecker;
2048 yaffs_BlockInfo *bi;
2049 static int nonAggressiveSkip = 0;
2050 int pendingPrioritisedExist = 0;
2052 /* First let's see if we need to grab a prioritised block */
2053 if(dev->hasPendingPrioritisedGCs){
2054 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2056 bi = yaffs_GetBlockInfo(dev, i);
2057 if(bi->gcPrioritise)
2058 pendingPrioritisedExist = 1;
2059 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2061 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2062 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2065 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2069 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2070 dev->hasPendingPrioritisedGCs = 0;
2073 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2075 * else (we're doing a leasurely gc), then we only bother to do this if the
2076 * block has only a few pages in use.
2079 nonAggressiveSkip--;
2081 if (!aggressive && (nonAggressiveSkip > 0)) {
2087 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2091 dev->internalEndBlock - dev->internalStartBlock + 1;
2094 dev->internalEndBlock - dev->internalStartBlock + 1;
2095 iterations = iterations / 16;
2096 if (iterations > 200) {
2101 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2103 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2104 b = dev->internalStartBlock;
2107 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2108 T(YAFFS_TRACE_ERROR,
2109 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2113 bi = yaffs_GetBlockInfo(dev, b);
2116 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2123 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2124 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2125 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2127 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2131 dev->currentDirtyChecker = b;
2135 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2136 dev->nChunksPerBlock - pagesInUse,prioritised));
2139 dev->oldestDirtySequence = 0;
2142 nonAggressiveSkip = 4;
2148 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2150 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2154 /* If the block is still healthy erase it and mark as clean.
2155 * If the block has had a data failure, then retire it.
2157 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2159 if (!bi->needsRetiring) {
2160 yaffs_InvalidateCheckpoint(dev);
2161 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2163 dev->nErasureFailures++;
2164 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2165 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2169 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2171 for (i = 0; i < dev->nChunksPerBlock; i++) {
2172 if (!yaffs_CheckChunkErased
2173 (dev, blockNo * dev->nChunksPerBlock + i)) {
2174 T(YAFFS_TRACE_ERROR,
2176 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2177 TENDSTR), blockNo, i));
2183 /* Clean it up... */
2184 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2185 dev->nErasedBlocks++;
2187 bi->softDeletions = 0;
2188 bi->hasShrinkHeader = 0;
2189 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2190 bi->gcPrioritise = 0;
2191 yaffs_ClearChunkBits(dev, blockNo);
2193 T(YAFFS_TRACE_ERASE,
2194 (TSTR("Erased block %d" TENDSTR), blockNo));
2196 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2198 yaffs_RetireBlock(dev, blockNo);
2199 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2200 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2204 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2208 yaffs_BlockInfo *bi;
2210 if (dev->nErasedBlocks < 1) {
2211 /* Hoosterman we've got a problem.
2212 * Can't get space to gc
2214 T(YAFFS_TRACE_ERROR,
2215 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2220 /* Find an empty block. */
2222 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2223 dev->allocationBlockFinder++;
2224 if (dev->allocationBlockFinder < dev->internalStartBlock
2225 || dev->allocationBlockFinder > dev->internalEndBlock) {
2226 dev->allocationBlockFinder = dev->internalStartBlock;
2229 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2231 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2232 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2233 dev->sequenceNumber++;
2234 bi->sequenceNumber = dev->sequenceNumber;
2235 dev->nErasedBlocks--;
2236 T(YAFFS_TRACE_ALLOCATE,
2237 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2238 dev->allocationBlockFinder, dev->sequenceNumber,
2239 dev->nErasedBlocks));
2240 return dev->allocationBlockFinder;
2244 T(YAFFS_TRACE_ALWAYS,
2246 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2247 TENDSTR), dev->nErasedBlocks));
2253 // Check if there's space to allocate...
2254 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2255 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2258 int reservedBlocks = dev->nReservedBlocks;
2259 int checkpointBlocks;
2261 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2262 if(checkpointBlocks < 0)
2263 checkpointBlocks = 0;
2265 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2267 return (dev->nFreeChunks > reservedChunks);
2270 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2273 yaffs_BlockInfo *bi;
2275 if (dev->allocationBlock < 0) {
2276 /* Get next block to allocate off */
2277 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2278 dev->allocationPage = 0;
2281 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2282 /* Not enough space to allocate unless we're allowed to use the reserve. */
2286 if (dev->nErasedBlocks < dev->nReservedBlocks
2287 && dev->allocationPage == 0) {
2288 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2291 /* Next page please.... */
2292 if (dev->allocationBlock >= 0) {
2293 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2295 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2296 dev->allocationPage;
2298 yaffs_SetChunkBit(dev, dev->allocationBlock,
2299 dev->allocationPage);
2301 dev->allocationPage++;
2305 /* If the block is full set the state to full */
2306 if (dev->allocationPage >= dev->nChunksPerBlock) {
2307 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2308 dev->allocationBlock = -1;
2317 T(YAFFS_TRACE_ERROR,
2318 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2323 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2327 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2329 if (dev->allocationBlock > 0) {
2330 n += (dev->nChunksPerBlock - dev->allocationPage);
2337 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2343 int retVal = YAFFS_OK;
2346 int isCheckpointBlock;
2348 int chunksBefore = yaffs_GetErasedChunks(dev);
2351 yaffs_ExtendedTags tags;
2353 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2355 yaffs_Object *object;
2357 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2359 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2361 T(YAFFS_TRACE_TRACING,
2362 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2363 bi->pagesInUse, bi->hasShrinkHeader));
2365 /*yaffs_VerifyFreeChunks(dev); */
2367 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2369 /* Take off the number of soft deleted entries because
2370 * they're going to get really deleted during GC.
2372 dev->nFreeChunks -= bi->softDeletions;
2376 if (isCheckpointBlock ||
2377 !yaffs_StillSomeChunkBits(dev, block)) {
2378 T(YAFFS_TRACE_TRACING,
2380 ("Collecting block %d that has no chunks in use" TENDSTR),
2382 yaffs_BlockBecameDirty(dev, block);
2385 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2387 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2388 chunkInBlock < dev->nChunksPerBlock
2389 && yaffs_StillSomeChunkBits(dev, block);
2390 chunkInBlock++, oldChunk++) {
2391 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2393 /* This page is in use and might need to be copied off */
2397 yaffs_InitialiseTags(&tags);
2399 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2403 yaffs_FindObjectByNumber(dev,
2406 T(YAFFS_TRACE_GC_DETAIL,
2408 ("Collecting page %d, %d %d %d " TENDSTR),
2409 chunkInBlock, tags.objectId, tags.chunkId,
2413 T(YAFFS_TRACE_ERROR,
2415 ("page %d in gc has no object "
2416 TENDSTR), oldChunk));
2419 if (object && object->deleted
2420 && tags.chunkId != 0) {
2421 /* Data chunk in a deleted file, throw it away
2422 * It's a soft deleted data chunk,
2423 * No need to copy this, just forget about it and
2424 * fix up the object.
2427 object->nDataChunks--;
2429 if (object->nDataChunks <= 0) {
2430 /* remeber to clean up the object */
2431 dev->gcCleanupList[cleanups] =
2437 /* Todo object && object->deleted && object->nDataChunks == 0 */
2439 /* Deleted object header with no data chunks.
2440 * Can be discarded and the file deleted.
2442 object->chunkId = 0;
2443 yaffs_FreeTnode(object->myDev,
2446 object->variant.fileVariant.top = NULL;
2447 yaffs_DoGenericObjectDeletion(object);
2449 } else if (object) {
2450 /* It's either a data chunk in a live file or
2451 * an ObjectHeader, so we're interested in it.
2452 * NB Need to keep the ObjectHeaders of deleted files
2453 * until the whole file has been deleted off
2455 tags.serialNumber++;
2459 if (tags.chunkId == 0) {
2460 /* It is an object Id,
2461 * We need to nuke the shrinkheader flags first
2462 * We no longer want the shrinkHeader flag since its work is done
2463 * and if it is left in place it will mess up scanning.
2464 * Also, clear out any shadowing stuff
2467 yaffs_ObjectHeader *oh;
2468 oh = (yaffs_ObjectHeader *)buffer;
2470 oh->shadowsObject = -1;
2471 tags.extraShadows = 0;
2472 tags.extraIsShrinkHeader = 0;
2476 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2479 retVal = YAFFS_FAIL;
2482 /* Ok, now fix up the Tnodes etc. */
2484 if (tags.chunkId == 0) {
2486 object->chunkId = newChunk;
2487 object->serial = tags.serialNumber;
2489 /* It's a data chunk */
2490 yaffs_PutChunkIntoFile
2498 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2503 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2506 /* Do any required cleanups */
2507 for (i = 0; i < cleanups; i++) {
2508 /* Time to delete the file too */
2510 yaffs_FindObjectByNumber(dev,
2511 dev->gcCleanupList[i]);
2513 yaffs_FreeTnode(dev,
2514 object->variant.fileVariant.
2516 object->variant.fileVariant.top = NULL;
2519 ("yaffs: About to finally delete object %d"
2520 TENDSTR), object->objectId));
2521 yaffs_DoGenericObjectDeletion(object);
2522 object->myDev->nDeletedFiles--;
2529 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2532 ("gc did not increase free chunks before %d after %d"
2533 TENDSTR), chunksBefore, chunksAfter));
2541 /* New garbage collector
2542 * If we're very low on erased blocks then we do aggressive garbage collection
2543 * otherwise we do "leasurely" garbage collection.
2544 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2545 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2547 * The idea is to help clear out space in a more spread-out manner.
2548 * Dunno if it really does anything useful.
2550 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2554 int gcOk = YAFFS_OK;
2557 int checkpointBlockAdjust;
2559 if (dev->isDoingGC) {
2560 /* Bail out so we don't get recursive gc */
2564 /* This loop should pass the first time.
2565 * We'll only see looping here if the erase of the collected block fails.
2571 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2572 if(checkpointBlockAdjust < 0)
2573 checkpointBlockAdjust = 0;
2575 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2576 /* We need a block soon...*/
2579 /* We're in no hurry */
2583 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2586 dev->garbageCollections++;
2588 dev->passiveGarbageCollections++;
2593 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2594 dev->nErasedBlocks, aggressive));
2596 gcOk = yaffs_GarbageCollectBlock(dev, block);
2599 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2602 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2603 TENDSTR), dev->nErasedBlocks, maxTries, block));
2605 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2608 return aggressive ? gcOk : YAFFS_OK;
2611 /*------------------------- TAGS --------------------------------*/
2613 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2616 return (tags->chunkId == chunkInObject &&
2617 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2622 /*-------------------- Data file manipulation -----------------*/
2624 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2625 yaffs_ExtendedTags * tags)
2627 /*Get the Tnode, then get the level 0 offset chunk offset */
2630 yaffs_ExtendedTags localTags;
2633 yaffs_Device *dev = in->myDev;
2636 /* Passed a NULL, so use our own tags space */
2640 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2643 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2646 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2652 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2653 yaffs_ExtendedTags * tags)
2655 /* Get the Tnode, then get the level 0 offset chunk offset */
2658 yaffs_ExtendedTags localTags;
2660 yaffs_Device *dev = in->myDev;
2664 /* Passed a NULL, so use our own tags space */
2668 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2672 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2675 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2678 /* Delete the entry in the filestructure (if found) */
2680 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2683 /*T(("No level 0 found for %d\n", chunkInInode)); */
2687 /* T(("Could not find %d to delete\n",chunkInInode)); */
2692 #ifdef YAFFS_PARANOID
2694 static int yaffs_CheckFileSanity(yaffs_Object * in)
2702 yaffs_Tags localTags;
2703 yaffs_Tags *tags = &localTags;
2707 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2708 /* T(("Object not a file\n")); */
2712 objId = in->objectId;
2713 fSize = in->variant.fileVariant.fileSize;
2715 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
2717 for (chunk = 1; chunk <= nChunks; chunk++) {
2718 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2723 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2725 if (yaffs_CheckChunkBits
2726 (dev, theChunk / dev->nChunksPerBlock,
2727 theChunk % dev->nChunksPerBlock)) {
2729 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2733 (tags, in->objectId, chunk, chunkDeleted)) {
2743 /* T(("No level 0 found for %d\n", chunk)); */
2747 return failed ? YAFFS_FAIL : YAFFS_OK;
2752 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2753 int chunkInNAND, int inScan)
2755 /* NB inScan is zero unless scanning.
2756 * For forward scanning, inScan is > 0;
2757 * for backward scanning inScan is < 0
2761 yaffs_Device *dev = in->myDev;
2763 yaffs_ExtendedTags existingTags;
2764 yaffs_ExtendedTags newTags;
2765 unsigned existingSerial, newSerial;
2767 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2768 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2769 * If it is not during Scanning then something went wrong!
2772 T(YAFFS_TRACE_ERROR,
2774 ("yaffs tragedy:attempt to put data chunk into a non-file"
2779 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2783 tn = yaffs_AddOrFindLevel0Tnode(dev,
2784 &in->variant.fileVariant,
2791 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2794 /* If we're scanning then we need to test for duplicates
2795 * NB This does not need to be efficient since it should only ever
2796 * happen when the power fails during a write, then only one
2797 * chunk should ever be affected.
2799 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2800 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2803 if (existingChunk != 0) {
2804 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2805 * thus we have to do a FindChunkInFile to get the real chunk id.
2807 * We have a duplicate now we need to decide which one to use:
2809 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2810 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2811 * YAFFS1: Get both sets of tags and compare serial numbers.
2815 /* Only do this for forward scanning */
2816 yaffs_ReadChunkWithTagsFromNAND(dev,
2820 /* Do a proper find */
2822 yaffs_FindChunkInFile(in, chunkInInode,
2826 if (existingChunk <= 0) {
2827 /*Hoosterman - how did this happen? */
2829 T(YAFFS_TRACE_ERROR,
2831 ("yaffs tragedy: existing chunk < 0 in scan"
2836 /* NB The deleted flags should be false, otherwise the chunks will
2837 * not be loaded during a scan
2840 newSerial = newTags.serialNumber;
2841 existingSerial = existingTags.serialNumber;
2844 (in->myDev->isYaffs2 ||
2845 existingChunk <= 0 ||
2846 ((existingSerial + 1) & 3) == newSerial)) {
2847 /* Forward scanning.
2849 * Delete the old one and drop through to update the tnode
2851 yaffs_DeleteChunk(dev, existingChunk, 1,
2854 /* Backward scanning or we want to use the existing one
2856 * Delete the new one and return early so that the tnode isn't changed
2858 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2866 if (existingChunk == 0) {
2870 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2875 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2878 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2880 if (chunkInNAND >= 0) {
2881 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2884 T(YAFFS_TRACE_NANDACCESS,
2885 (TSTR("Chunk %d not found zero instead" TENDSTR),
2887 /* get sane (zero) data if you read a hole */
2888 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2894 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2898 yaffs_ExtendedTags tags;
2899 yaffs_BlockInfo *bi;
2905 block = chunkId / dev->nChunksPerBlock;
2906 page = chunkId % dev->nChunksPerBlock;
2908 bi = yaffs_GetBlockInfo(dev, block);
2910 T(YAFFS_TRACE_DELETION,
2911 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2914 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2916 yaffs_InitialiseTags(&tags);
2918 tags.chunkDeleted = 1;
2920 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2921 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2923 dev->nUnmarkedDeletions++;
2926 /* Pull out of the management area.
2927 * If the whole block became dirty, this will kick off an erasure.
2929 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2930 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2931 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2932 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2935 yaffs_ClearChunkBit(dev, block, page);
2939 if (bi->pagesInUse == 0 &&
2940 !bi->hasShrinkHeader &&
2941 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2942 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2943 yaffs_BlockBecameDirty(dev, block);
2947 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2952 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2953 const __u8 * buffer, int nBytes,
2956 /* Find old chunk Need to do this to get serial number
2957 * Write new one and patch into tree.
2958 * Invalidate old tags.
2962 yaffs_ExtendedTags prevTags;
2965 yaffs_ExtendedTags newTags;
2967 yaffs_Device *dev = in->myDev;
2969 yaffs_CheckGarbageCollection(dev);
2971 /* Get the previous chunk at this location in the file if it exists */
2972 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2974 /* Set up new tags */
2975 yaffs_InitialiseTags(&newTags);
2977 newTags.chunkId = chunkInInode;
2978 newTags.objectId = in->objectId;
2979 newTags.serialNumber =
2980 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2981 newTags.byteCount = nBytes;
2984 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2987 if (newChunkId >= 0) {
2988 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2990 if (prevChunkId >= 0) {
2991 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2995 yaffs_CheckFileSanity(in);
3001 /* UpdateObjectHeader updates the header on NAND for an object.
3002 * If name is not NULL, then that new name is used.
3004 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3005 int isShrink, int shadows)
3008 yaffs_BlockInfo *bi;
3010 yaffs_Device *dev = in->myDev;
3017 yaffs_ExtendedTags newTags;
3019 __u8 *buffer = NULL;
3020 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3022 yaffs_ObjectHeader *oh = NULL;
3024 if (!in->fake || force) {
3026 yaffs_CheckGarbageCollection(dev);
3028 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3029 oh = (yaffs_ObjectHeader *) buffer;
3031 prevChunkId = in->chunkId;
3033 if (prevChunkId >= 0) {
3034 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3036 memcpy(oldName, oh->name, sizeof(oh->name));
3039 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3041 oh->type = in->variantType;
3042 oh->yst_mode = in->yst_mode;
3043 oh->shadowsObject = shadows;
3045 #ifdef CONFIG_YAFFS_WINCE
3046 oh->win_atime[0] = in->win_atime[0];
3047 oh->win_ctime[0] = in->win_ctime[0];
3048 oh->win_mtime[0] = in->win_mtime[0];
3049 oh->win_atime[1] = in->win_atime[1];
3050 oh->win_ctime[1] = in->win_ctime[1];
3051 oh->win_mtime[1] = in->win_mtime[1];
3053 oh->yst_uid = in->yst_uid;
3054 oh->yst_gid = in->yst_gid;
3055 oh->yst_atime = in->yst_atime;
3056 oh->yst_mtime = in->yst_mtime;
3057 oh->yst_ctime = in->yst_ctime;
3058 oh->yst_rdev = in->yst_rdev;
3061 oh->parentObjectId = in->parent->objectId;
3063 oh->parentObjectId = 0;
3066 if (name && *name) {
3067 memset(oh->name, 0, sizeof(oh->name));
3068 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3069 } else if (prevChunkId) {
3070 memcpy(oh->name, oldName, sizeof(oh->name));
3072 memset(oh->name, 0, sizeof(oh->name));
3075 oh->isShrink = isShrink;
3077 switch (in->variantType) {
3078 case YAFFS_OBJECT_TYPE_UNKNOWN:
3079 /* Should not happen */
3081 case YAFFS_OBJECT_TYPE_FILE:
3083 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3084 || oh->parentObjectId ==
3085 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3086 fileVariant.fileSize;
3088 case YAFFS_OBJECT_TYPE_HARDLINK:
3089 oh->equivalentObjectId =
3090 in->variant.hardLinkVariant.equivalentObjectId;
3092 case YAFFS_OBJECT_TYPE_SPECIAL:
3095 case YAFFS_OBJECT_TYPE_DIRECTORY:
3098 case YAFFS_OBJECT_TYPE_SYMLINK:
3099 yaffs_strncpy(oh->alias,
3100 in->variant.symLinkVariant.alias,
3101 YAFFS_MAX_ALIAS_LENGTH);
3102 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3107 yaffs_InitialiseTags(&newTags);
3109 newTags.chunkId = 0;
3110 newTags.objectId = in->objectId;
3111 newTags.serialNumber = in->serial;
3113 /* Add extra info for file header */
3115 newTags.extraHeaderInfoAvailable = 1;
3116 newTags.extraParentObjectId = oh->parentObjectId;
3117 newTags.extraFileLength = oh->fileSize;
3118 newTags.extraIsShrinkHeader = oh->isShrink;
3119 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3120 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3121 newTags.extraObjectType = in->variantType;
3123 /* Create new chunk in NAND */
3125 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3126 (prevChunkId >= 0) ? 1 : 0);
3128 if (newChunkId >= 0) {
3130 in->chunkId = newChunkId;
3132 if (prevChunkId >= 0) {
3133 yaffs_DeleteChunk(dev, prevChunkId, 1,
3137 if(!yaffs_ObjectHasCachedWriteData(in))
3140 /* If this was a shrink, then mark the block that the chunk lives on */
3142 bi = yaffs_GetBlockInfo(in->myDev,
3143 newChunkId /in->myDev-> nChunksPerBlock);
3144 bi->hasShrinkHeader = 1;
3149 retVal = newChunkId;
3154 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3159 /*------------------------ Short Operations Cache ----------------------------------------
3160 * In many situations where there is no high level buffering (eg WinCE) a lot of
3161 * reads might be short sequential reads, and a lot of writes may be short
3162 * sequential writes. eg. scanning/writing a jpeg file.
3163 * In these cases, a short read/write cache can provide a huge perfomance benefit
3164 * with dumb-as-a-rock code.
3165 * In Linux, the page cache provides read buffering aand the short op cache provides write
3168 * There are a limited number (~10) of cache chunks per device so that we don't
3169 * need a very intelligent search.
3172 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3174 yaffs_Device *dev = obj->myDev;
3176 yaffs_ChunkCache *cache;
3177 int nCaches = obj->myDev->nShortOpCaches;
3179 for(i = 0; i < nCaches; i++){
3180 cache = &dev->srCache[i];
3181 if (cache->object == obj &&
3190 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3192 yaffs_Device *dev = obj->myDev;
3193 int lowest = -99; /* Stop compiler whining. */
3195 yaffs_ChunkCache *cache;
3196 int chunkWritten = 0;
3197 int nCaches = obj->myDev->nShortOpCaches;
3203 /* Find the dirty cache for this object with the lowest chunk id. */
3204 for (i = 0; i < nCaches; i++) {
3205 if (dev->srCache[i].object == obj &&
3206 dev->srCache[i].dirty) {
3208 || dev->srCache[i].chunkId <
3210 cache = &dev->srCache[i];
3211 lowest = cache->chunkId;
3216 if (cache && !cache->locked) {
3217 /* Write it out and free it up */
3220 yaffs_WriteChunkDataToObject(cache->object,
3226 cache->object = NULL;
3229 } while (cache && chunkWritten > 0);
3232 /* Hoosterman, disk full while writing cache out. */
3233 T(YAFFS_TRACE_ERROR,
3234 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3241 /*yaffs_FlushEntireDeviceCache(dev)
3246 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3249 int nCaches = dev->nShortOpCaches;
3252 /* Find a dirty object in the cache and flush it...
3253 * until there are no further dirty objects.
3257 for( i = 0; i < nCaches && !obj; i++) {
3258 if (dev->srCache[i].object &&
3259 dev->srCache[i].dirty)
3260 obj = dev->srCache[i].object;
3264 yaffs_FlushFilesChunkCache(obj);
3271 /* Grab us a cache chunk for use.
3272 * First look for an empty one.
3273 * Then look for the least recently used non-dirty one.
3274 * Then look for the least recently used dirty one...., flush and look again.
3276 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3282 if (dev->nShortOpCaches > 0) {
3283 for (i = 0; i < dev->nShortOpCaches; i++) {
3284 if (!dev->srCache[i].object)
3285 return &dev->srCache[i];
3291 usage = 0; /* just to stop the compiler grizzling */
3293 for (i = 0; i < dev->nShortOpCaches; i++) {
3294 if (!dev->srCache[i].dirty &&
3295 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3297 usage = dev->srCache[i].lastUse;
3303 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3310 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3312 yaffs_ChunkCache *cache;
3313 yaffs_Object *theObj;
3318 if (dev->nShortOpCaches > 0) {
3319 /* Try find a non-dirty one... */
3321 cache = yaffs_GrabChunkCacheWorker(dev);
3324 /* They were all dirty, find the last recently used object and flush
3325 * its cache, then find again.
3326 * NB what's here is not very accurate, we actually flush the object
3327 * the last recently used page.
3330 /* With locking we can't assume we can use entry zero */
3337 for (i = 0; i < dev->nShortOpCaches; i++) {
3338 if (dev->srCache[i].object &&
3339 !dev->srCache[i].locked &&
3340 (dev->srCache[i].lastUse < usage || !cache))
3342 usage = dev->srCache[i].lastUse;
3343 theObj = dev->srCache[i].object;
3344 cache = &dev->srCache[i];
3349 if (!cache || cache->dirty) {
3350 /* Flush and try again */
3351 yaffs_FlushFilesChunkCache(theObj);
3352 cache = yaffs_GrabChunkCacheWorker(dev);
3362 /* Find a cached chunk */
3363 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3366 yaffs_Device *dev = obj->myDev;
3368 if (dev->nShortOpCaches > 0) {
3369 for (i = 0; i < dev->nShortOpCaches; i++) {
3370 if (dev->srCache[i].object == obj &&
3371 dev->srCache[i].chunkId == chunkId) {
3374 return &dev->srCache[i];
3381 /* Mark the chunk for the least recently used algorithym */
3382 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3386 if (dev->nShortOpCaches > 0) {
3387 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3388 /* Reset the cache usages */
3390 for (i = 1; i < dev->nShortOpCaches; i++) {
3391 dev->srCache[i].lastUse = 0;
3398 cache->lastUse = dev->srLastUse;
3406 /* Invalidate a single cache page.
3407 * Do this when a whole page gets written,
3408 * ie the short cache for this page is no longer valid.
3410 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3412 if (object->myDev->nShortOpCaches > 0) {
3413 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3416 cache->object = NULL;
3421 /* Invalidate all the cache pages associated with this object
3422 * Do this whenever ther file is deleted or resized.
3424 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3427 yaffs_Device *dev = in->myDev;
3429 if (dev->nShortOpCaches > 0) {
3430 /* Invalidate it. */
3431 for (i = 0; i < dev->nShortOpCaches; i++) {
3432 if (dev->srCache[i].object == in) {
3433 dev->srCache[i].object = NULL;
3439 /*--------------------- Checkpointing --------------------*/
3442 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3444 yaffs_CheckpointValidity cp;
3445 cp.structType = sizeof(cp);
3446 cp.magic = YAFFS_MAGIC;
3447 cp.version = YAFFS_CHECKPOINT_VERSION;
3448 cp.head = (head) ? 1 : 0;
3450 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3454 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3456 yaffs_CheckpointValidity cp;
3459 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3462 ok = (cp.structType == sizeof(cp)) &&
3463 (cp.magic == YAFFS_MAGIC) &&
3464 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
3465 (cp.head == ((head) ? 1 : 0));
3469 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3472 cp->nErasedBlocks = dev->nErasedBlocks;
3473 cp->allocationBlock = dev->allocationBlock;
3474 cp->allocationPage = dev->allocationPage;
3475 cp->nFreeChunks = dev->nFreeChunks;
3477 cp->nDeletedFiles = dev->nDeletedFiles;
3478 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3479 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3480 cp->sequenceNumber = dev->sequenceNumber;
3481 cp->oldestDirtySequence = dev->oldestDirtySequence;
3485 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3486 yaffs_CheckpointDevice *cp)
3488 dev->nErasedBlocks = cp->nErasedBlocks;
3489 dev->allocationBlock = cp->allocationBlock;
3490 dev->allocationPage = cp->allocationPage;
3491 dev->nFreeChunks = cp->nFreeChunks;
3493 dev->nDeletedFiles = cp->nDeletedFiles;
3494 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3495 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3496 dev->sequenceNumber = cp->sequenceNumber;
3497 dev->oldestDirtySequence = cp->oldestDirtySequence;
3501 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3503 yaffs_CheckpointDevice cp;
3505 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3509 /* Write device runtime values*/
3510 yaffs_DeviceToCheckpointDevice(&cp,dev);
3511 cp.structType = sizeof(cp);
3513 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3515 /* Write block info */
3517 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3518 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3521 /* Write chunk bits */
3523 nBytes = nBlocks * dev->chunkBitmapStride;
3524 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3530 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3532 yaffs_CheckpointDevice cp;
3534 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3538 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3542 if(cp.structType != sizeof(cp))
3546 yaffs_CheckpointDeviceToDevice(dev,&cp);
3548 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3550 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3554 nBytes = nBlocks * dev->chunkBitmapStride;
3556 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3561 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3565 cp->objectId = obj->objectId;
3566 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3567 cp->chunkId = obj->chunkId;
3568 cp->variantType = obj->variantType;
3569 cp->deleted = obj->deleted;
3570 cp->softDeleted = obj->softDeleted;
3571 cp->unlinked = obj->unlinked;
3572 cp->fake = obj->fake;
3573 cp->renameAllowed = obj->renameAllowed;
3574 cp->unlinkAllowed = obj->unlinkAllowed;
3575 cp->serial = obj->serial;
3576 cp->nDataChunks = obj->nDataChunks;
3578 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3579 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3580 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3581 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3584 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3587 yaffs_Object *parent;
3589 obj->objectId = cp->objectId;
3592 parent = yaffs_FindOrCreateObjectByNumber(
3595 YAFFS_OBJECT_TYPE_DIRECTORY);
3600 yaffs_AddObjectToDirectory(parent, obj);
3602 obj->chunkId = cp->chunkId;
3603 obj->variantType = cp->variantType;
3604 obj->deleted = cp->deleted;
3605 obj->softDeleted = cp->softDeleted;
3606 obj->unlinked = cp->unlinked;
3607 obj->fake = cp->fake;
3608 obj->renameAllowed = cp->renameAllowed;
3609 obj->unlinkAllowed = cp->unlinkAllowed;
3610 obj->serial = cp->serial;
3611 obj->nDataChunks = cp->nDataChunks;
3613 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3614 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3615 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3616 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3618 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3619 obj->lazyLoaded = 1;
3624 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3625 __u32 level, int chunkOffset)
3628 yaffs_Device *dev = in->myDev;
3630 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3635 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3636 if (tn->internal[i]) {
3637 ok = yaffs_CheckpointTnodeWorker(in,
3640 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3643 } else if (level == 0) {
3644 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3645 /* printf("write tnode at %d\n",baseOffset); */
3646 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3648 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3656 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3658 __u32 endMarker = ~0;
3661 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3662 ok = yaffs_CheckpointTnodeWorker(obj,
3663 obj->variant.fileVariant.top,
3664 obj->variant.fileVariant.topLevel,
3667 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3674 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3678 yaffs_Device *dev = obj->myDev;
3679 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3682 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3684 while(ok && (~baseChunk)){
3685 /* Read level 0 tnode */
3687 /* printf("read tnode at %d\n",baseChunk); */
3688 tn = yaffs_GetTnodeRaw(dev);
3690 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3691 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3696 ok = yaffs_AddOrFindLevel0Tnode(dev,
3703 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3711 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3714 yaffs_CheckpointObject cp;
3717 struct list_head *lh;
3720 /* Iterate through the objects in each hash entry,
3721 * dumping them to the checkpointing stream.
3724 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3725 list_for_each(lh, &dev->objectBucket[i].list) {
3727 obj = list_entry(lh, yaffs_Object, hashLink);
3728 if (!obj->deferedFree) {
3729 yaffs_ObjectToCheckpointObject(&cp,obj);
3730 cp.structType = sizeof(cp);
3732 T(YAFFS_TRACE_CHECKPOINT,(
3733 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3734 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3736 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3738 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3739 ok = yaffs_WriteCheckpointTnodes(obj);
3746 /* Dump end of list */
3747 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3748 cp.structType = sizeof(cp);
3751 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3756 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3759 yaffs_CheckpointObject cp;
3762 yaffs_Object *hardList = NULL;
3764 while(ok && !done) {
3765 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3766 if(cp.structType != sizeof(cp)) {
3767 /* printf("structure parsing failed\n"); */
3771 if(ok && cp.objectId == ~0)
3774 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3775 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3776 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3778 yaffs_CheckpointObjectToObject(obj,&cp);
3779 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3780 ok = yaffs_ReadCheckpointTnodes(obj);
3781 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3782 obj->hardLinks.next =
3783 (struct list_head *)
3793 yaffs_HardlinkFixup(dev,hardList);
3798 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3803 ok = yaffs_CheckpointOpen(dev,1);
3806 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3808 ok = yaffs_WriteCheckpointDevice(dev);
3810 ok = yaffs_WriteCheckpointObjects(dev);
3812 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3814 if(!yaffs_CheckpointClose(dev))
3818 dev->isCheckpointed = 1;
3820 dev->isCheckpointed = 0;
3822 return dev->isCheckpointed;
3825 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3829 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3832 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3834 ok = yaffs_ReadCheckpointDevice(dev);
3836 ok = yaffs_ReadCheckpointObjects(dev);
3838 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3842 if(!yaffs_CheckpointClose(dev))
3846 dev->isCheckpointed = 1;
3848 dev->isCheckpointed = 0;
3854 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3856 if(dev->isCheckpointed ||
3857 dev->blocksInCheckpoint > 0){
3858 dev->isCheckpointed = 0;
3859 yaffs_CheckpointInvalidateStream(dev);
3860 if(dev->superBlock && dev->markSuperBlockDirty)
3861 dev->markSuperBlockDirty(dev->superBlock);
3866 int yaffs_CheckpointSave(yaffs_Device *dev)
3868 yaffs_ReportOddballBlocks(dev);
3869 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3871 if(!dev->isCheckpointed)
3872 yaffs_WriteCheckpointData(dev);
3874 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3876 return dev->isCheckpointed;
3879 int yaffs_CheckpointRestore(yaffs_Device *dev)
3882 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3884 retval = yaffs_ReadCheckpointData(dev);
3886 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3888 yaffs_ReportOddballBlocks(dev);
3893 /*--------------------- File read/write ------------------------
3894 * Read and write have very similar structures.
3895 * In general the read/write has three parts to it
3896 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3897 * Some complete chunks
3898 * An incomplete chunk to end off with
3900 * Curve-balls: the first chunk might also be the last chunk.
3903 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
3912 yaffs_ChunkCache *cache;
3919 //chunk = offset / dev->nDataBytesPerChunk + 1;
3920 //start = offset % dev->nDataBytesPerChunk;
3921 yaffs_AddrToChunk(dev,offset,&chunk,&start);
3924 /* OK now check for the curveball where the start and end are in
3927 if ((start + n) < dev->nDataBytesPerChunk) {
3930 nToCopy = dev->nDataBytesPerChunk - start;
3933 cache = yaffs_FindChunkCache(in, chunk);
3935 /* If the chunk is already in the cache or it is less than a whole chunk
3936 * then use the cache (if there is caching)
3937 * else bypass the cache.
3939 if (cache || nToCopy != dev->nDataBytesPerChunk) {
3940 if (dev->nShortOpCaches > 0) {
3942 /* If we can't find the data in the cache, then load it up. */
3945 cache = yaffs_GrabChunkCache(in->myDev);
3947 cache->chunkId = chunk;
3950 yaffs_ReadChunkDataFromObject(in, chunk,
3956 yaffs_UseChunkCache(dev, cache, 0);
3960 #ifdef CONFIG_YAFFS_WINCE
3961 yfsd_UnlockYAFFS(TRUE);
3963 memcpy(buffer, &cache->data[start], nToCopy);
3965 #ifdef CONFIG_YAFFS_WINCE
3966 yfsd_LockYAFFS(TRUE);
3970 /* Read into the local buffer then copy..*/
3973 yaffs_GetTempBuffer(dev, __LINE__);
3974 yaffs_ReadChunkDataFromObject(in, chunk,
3976 #ifdef CONFIG_YAFFS_WINCE
3977 yfsd_UnlockYAFFS(TRUE);
3979 memcpy(buffer, &localBuffer[start], nToCopy);
3981 #ifdef CONFIG_YAFFS_WINCE
3982 yfsd_LockYAFFS(TRUE);
3984 yaffs_ReleaseTempBuffer(dev, localBuffer,
3989 #ifdef CONFIG_YAFFS_WINCE
3990 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3992 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3993 * This is because we otherwise screw up WinCE's memory mapper
3995 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3997 #ifdef CONFIG_YAFFS_WINCE
3998 yfsd_UnlockYAFFS(TRUE);
4000 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4002 #ifdef CONFIG_YAFFS_WINCE
4003 yfsd_LockYAFFS(TRUE);
4004 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4008 /* A full chunk. Read directly into the supplied buffer. */
4009 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4023 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4024 int nBytes, int writeThrough)
4033 int startOfWrite = offset;
4034 int chunkWritten = 0;
4041 while (n > 0 && chunkWritten >= 0) {
4042 //chunk = offset / dev->nDataBytesPerChunk + 1;
4043 //start = offset % dev->nDataBytesPerChunk;
4044 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4047 /* OK now check for the curveball where the start and end are in
4051 if ((start + n) < dev->nDataBytesPerChunk) {
4054 /* Now folks, to calculate how many bytes to write back....
4055 * If we're overwriting and not writing to then end of file then
4056 * we need to write back as much as was there before.
4060 in->variant.fileVariant.fileSize -
4061 ((chunk - 1) * dev->nDataBytesPerChunk);
4063 if (nBytesRead > dev->nDataBytesPerChunk) {
4064 nBytesRead = dev->nDataBytesPerChunk;
4069 (start + n)) ? nBytesRead : (start + n);
4072 nToCopy = dev->nDataBytesPerChunk - start;
4073 nToWriteBack = dev->nDataBytesPerChunk;
4076 if (nToCopy != dev->nDataBytesPerChunk) {
4077 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4078 if (dev->nShortOpCaches > 0) {
4079 yaffs_ChunkCache *cache;
4080 /* If we can't find the data in the cache, then load the cache */
4081 cache = yaffs_FindChunkCache(in, chunk);
4084 && yaffs_CheckSpaceForAllocation(in->
4086 cache = yaffs_GrabChunkCache(in->myDev);
4088 cache->chunkId = chunk;
4091 yaffs_ReadChunkDataFromObject(in, chunk,
4097 !yaffs_CheckSpaceForAllocation(in->myDev)){
4098 /* Drop the cache if it was a read cache item and
4099 * no space check has been made for it.
4105 yaffs_UseChunkCache(dev, cache, 1);
4107 #ifdef CONFIG_YAFFS_WINCE
4108 yfsd_UnlockYAFFS(TRUE);
4111 memcpy(&cache->data[start], buffer,
4114 #ifdef CONFIG_YAFFS_WINCE
4115 yfsd_LockYAFFS(TRUE);
4118 cache->nBytes = nToWriteBack;
4122 yaffs_WriteChunkDataToObject
4125 cache->data, cache->nBytes,
4131 chunkWritten = -1; /* fail the write */
4134 /* An incomplete start or end chunk (or maybe both start and end chunk)
4135 * Read into the local buffer then copy, then copy over and write back.
4139 yaffs_GetTempBuffer(dev, __LINE__);
4141 yaffs_ReadChunkDataFromObject(in, chunk,
4144 #ifdef CONFIG_YAFFS_WINCE
4145 yfsd_UnlockYAFFS(TRUE);
4148 memcpy(&localBuffer[start], buffer, nToCopy);
4150 #ifdef CONFIG_YAFFS_WINCE
4151 yfsd_LockYAFFS(TRUE);
4154 yaffs_WriteChunkDataToObject(in, chunk,
4159 yaffs_ReleaseTempBuffer(dev, localBuffer,
4166 #ifdef CONFIG_YAFFS_WINCE
4167 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4168 * This is because we otherwise screw up WinCE's memory mapper
4170 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4171 #ifdef CONFIG_YAFFS_WINCE
4172 yfsd_UnlockYAFFS(TRUE);
4174 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4175 #ifdef CONFIG_YAFFS_WINCE
4176 yfsd_LockYAFFS(TRUE);
4179 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4180 dev->nDataBytesPerChunk,
4182 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4184 /* A full chunk. Write directly from the supplied buffer. */
4186 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4187 dev->nDataBytesPerChunk,
4190 /* Since we've overwritten the cached data, we better invalidate it. */
4191 yaffs_InvalidateChunkCache(in, chunk);
4194 if (chunkWritten >= 0) {
4203 /* Update file object */
4205 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4206 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4215 /* ---------------------- File resizing stuff ------------------ */
4217 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4220 yaffs_Device *dev = in->myDev;
4221 int oldFileSize = in->variant.fileVariant.fileSize;
4223 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4225 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4226 dev->nDataBytesPerChunk;
4230 /* Delete backwards so that we don't end up with holes if
4231 * power is lost part-way through the operation.
4233 for (i = lastDel; i >= startDel; i--) {
4234 /* NB this could be optimised somewhat,
4235 * eg. could retrieve the tags and write them without
4236 * using yaffs_DeleteChunk
4239 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4242 (dev->internalStartBlock * dev->nChunksPerBlock)
4244 ((dev->internalEndBlock +
4245 1) * dev->nChunksPerBlock)) {
4246 T(YAFFS_TRACE_ALWAYS,
4247 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4251 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4258 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4261 int oldFileSize = in->variant.fileVariant.fileSize;
4262 int newSizeOfPartialChunk;
4265 yaffs_Device *dev = in->myDev;
4267 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4269 yaffs_FlushFilesChunkCache(in);
4270 yaffs_InvalidateWholeChunkCache(in);
4272 yaffs_CheckGarbageCollection(dev);
4274 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4275 return yaffs_GetFileSize(in);
4278 if (newSize == oldFileSize) {
4282 if (newSize < oldFileSize) {
4284 yaffs_PruneResizedChunks(in, newSize);
4286 if (newSizeOfPartialChunk != 0) {
4287 int lastChunk = 1 + newFullChunks;
4289 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4291 /* Got to read and rewrite the last chunk with its new size and zero pad */
4292 yaffs_ReadChunkDataFromObject(in, lastChunk,
4295 memset(localBuffer + newSizeOfPartialChunk, 0,
4296 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4298 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4299 newSizeOfPartialChunk, 1);
4301 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4304 in->variant.fileVariant.fileSize = newSize;
4306 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4308 /* Write a new object header.
4309 * show we've shrunk the file, if need be
4310 * Do this only if the file is not in the deleted directories.
4312 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4313 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4314 yaffs_UpdateObjectHeader(in, NULL, 0,
4315 (newSize < oldFileSize) ? 1 : 0, 0);
4321 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4323 obj = yaffs_GetEquivalentObject(obj);
4325 switch (obj->variantType) {
4326 case YAFFS_OBJECT_TYPE_FILE:
4327 return obj->variant.fileVariant.fileSize;
4328 case YAFFS_OBJECT_TYPE_SYMLINK:
4329 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4337 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4341 yaffs_FlushFilesChunkCache(in);
4343 #ifdef CONFIG_YAFFS_WINCE
4344 yfsd_WinFileTimeNow(in->win_mtime);
4347 in->yst_mtime = Y_CURRENT_TIME;
4353 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4354 0) ? YAFFS_OK : YAFFS_FAIL;
4363 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4366 /* First off, invalidate the file's data in the cache, without flushing. */
4367 yaffs_InvalidateWholeChunkCache(in);
4369 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4370 /* Move to the unlinked directory so we have a record that it was deleted. */
4371 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4375 yaffs_RemoveObjectFromDirectory(in);
4376 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4379 yaffs_FreeObject(in);
4384 /* yaffs_DeleteFile deletes the whole file data
4385 * and the inode associated with the file.
4386 * It does not delete the links associated with the file.
4388 static int yaffs_UnlinkFile(yaffs_Object * in)
4392 int immediateDeletion = 0;
4397 immediateDeletion = 1;
4401 if (in->inUse <= 0) {
4402 immediateDeletion = 1;
4406 if (immediateDeletion) {
4408 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4410 T(YAFFS_TRACE_TRACING,
4411 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4414 in->myDev->nDeletedFiles++;
4415 if (0 && in->myDev->isYaffs2) {
4416 yaffs_ResizeFile(in, 0);
4418 yaffs_SoftDeleteFile(in);
4421 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4429 int yaffs_DeleteFile(yaffs_Object * in)
4431 int retVal = YAFFS_OK;
4433 if (in->nDataChunks > 0) {
4434 /* Use soft deletion if there is data in the file */
4435 if (!in->unlinked) {
4436 retVal = yaffs_UnlinkFile(in);
4438 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4440 in->myDev->nDeletedFiles++;
4441 yaffs_SoftDeleteFile(in);
4443 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4445 /* The file has no data chunks so we toss it immediately */
4446 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4447 in->variant.fileVariant.top = NULL;
4448 yaffs_DoGenericObjectDeletion(in);
4454 static int yaffs_DeleteDirectory(yaffs_Object * in)
4456 /* First check that the directory is empty. */
4457 if (list_empty(&in->variant.directoryVariant.children)) {
4458 return yaffs_DoGenericObjectDeletion(in);
4465 static int yaffs_DeleteSymLink(yaffs_Object * in)
4467 YFREE(in->variant.symLinkVariant.alias);
4469 return yaffs_DoGenericObjectDeletion(in);
4472 static int yaffs_DeleteHardLink(yaffs_Object * in)
4474 /* remove this hardlink from the list assocaited with the equivalent
4477 list_del(&in->hardLinks);
4478 return yaffs_DoGenericObjectDeletion(in);
4481 static void yaffs_DestroyObject(yaffs_Object * obj)
4483 switch (obj->variantType) {
4484 case YAFFS_OBJECT_TYPE_FILE:
4485 yaffs_DeleteFile(obj);
4487 case YAFFS_OBJECT_TYPE_DIRECTORY:
4488 yaffs_DeleteDirectory(obj);
4490 case YAFFS_OBJECT_TYPE_SYMLINK:
4491 yaffs_DeleteSymLink(obj);
4493 case YAFFS_OBJECT_TYPE_HARDLINK:
4494 yaffs_DeleteHardLink(obj);
4496 case YAFFS_OBJECT_TYPE_SPECIAL:
4497 yaffs_DoGenericObjectDeletion(obj);
4499 case YAFFS_OBJECT_TYPE_UNKNOWN:
4500 break; /* should not happen. */
4504 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4507 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4508 return yaffs_DeleteHardLink(obj);
4509 } else if (!list_empty(&obj->hardLinks)) {
4510 /* Curve ball: We're unlinking an object that has a hardlink.
4512 * This problem arises because we are not strictly following
4513 * The Linux link/inode model.
4515 * We can't really delete the object.
4516 * Instead, we do the following:
4517 * - Select a hardlink.
4518 * - Unhook it from the hard links
4519 * - Unhook it from its parent directory (so that the rename can work)
4520 * - Rename the object to the hardlink's name.
4521 * - Delete the hardlink
4526 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4528 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4530 list_del_init(&hl->hardLinks);
4531 list_del_init(&hl->siblings);
4533 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4535 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4537 if (retVal == YAFFS_OK) {
4538 retVal = yaffs_DoGenericObjectDeletion(hl);
4543 switch (obj->variantType) {
4544 case YAFFS_OBJECT_TYPE_FILE:
4545 return yaffs_UnlinkFile(obj);
4547 case YAFFS_OBJECT_TYPE_DIRECTORY:
4548 return yaffs_DeleteDirectory(obj);
4550 case YAFFS_OBJECT_TYPE_SYMLINK:
4551 return yaffs_DeleteSymLink(obj);
4553 case YAFFS_OBJECT_TYPE_SPECIAL:
4554 return yaffs_DoGenericObjectDeletion(obj);
4556 case YAFFS_OBJECT_TYPE_HARDLINK:
4557 case YAFFS_OBJECT_TYPE_UNKNOWN:
4565 static int yaffs_UnlinkObject( yaffs_Object *obj)
4568 if (obj && obj->unlinkAllowed) {
4569 return yaffs_UnlinkWorker(obj);
4575 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4579 obj = yaffs_FindObjectByName(dir, name);
4580 return yaffs_UnlinkObject(obj);
4583 /*----------------------- Initialisation Scanning ---------------------- */
4585 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4586 int backwardScanning)
4590 if (!backwardScanning) {
4591 /* Handle YAFFS1 forward scanning case
4592 * For YAFFS1 we always do the deletion
4596 /* Handle YAFFS2 case (backward scanning)
4597 * If the shadowed object exists then ignore.
4599 if (yaffs_FindObjectByNumber(dev, objId)) {
4604 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4605 * We put it in unlinked dir to be cleaned up after the scanning
4608 yaffs_FindOrCreateObjectByNumber(dev, objId,
4609 YAFFS_OBJECT_TYPE_FILE);
4610 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4611 obj->variant.fileVariant.shrinkSize = 0;
4612 obj->valid = 1; /* So that we don't read any other info for this file */
4622 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4629 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4631 in = yaffs_FindObjectByNumber(dev,
4632 hl->variant.hardLinkVariant.
4633 equivalentObjectId);
4636 /* Add the hardlink pointers */
4637 hl->variant.hardLinkVariant.equivalentObject = in;
4638 list_add(&hl->hardLinks, &in->hardLinks);
4640 /* Todo Need to report/handle this better.
4641 * Got a problem... hardlink to a non-existant object
4643 hl->variant.hardLinkVariant.equivalentObject = NULL;
4644 INIT_LIST_HEAD(&hl->hardLinks);
4656 static int ybicmp(const void *a, const void *b){
4657 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4658 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4659 register int ablock = ((yaffs_BlockIndex *)a)->block;
4660 register int bblock = ((yaffs_BlockIndex *)b)->block;
4662 return ablock - bblock;
4668 static int yaffs_Scan(yaffs_Device * dev)
4670 yaffs_ExtendedTags tags;
4675 int nBlocksToScan = 0;
4681 yaffs_BlockState state;
4682 yaffs_Object *hardList = NULL;
4684 yaffs_BlockInfo *bi;
4686 yaffs_ObjectHeader *oh;
4688 yaffs_Object *parent;
4689 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4693 yaffs_BlockIndex *blockIndex = NULL;
4695 if (dev->isYaffs2) {
4697 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4701 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4704 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4705 dev->internalStartBlock, dev->internalEndBlock));
4707 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4709 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4711 if (dev->isYaffs2) {
4712 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4715 /* Scan all the blocks to determine their state */
4716 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4717 bi = yaffs_GetBlockInfo(dev, blk);
4718 yaffs_ClearChunkBits(dev, blk);
4720 bi->softDeletions = 0;
4722 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4724 bi->blockState = state;
4725 bi->sequenceNumber = sequenceNumber;
4727 T(YAFFS_TRACE_SCAN_DEBUG,
4728 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4729 state, sequenceNumber));
4731 if (state == YAFFS_BLOCK_STATE_DEAD) {
4732 T(YAFFS_TRACE_BAD_BLOCKS,
4733 (TSTR("block %d is bad" TENDSTR), blk));
4734 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4735 T(YAFFS_TRACE_SCAN_DEBUG,
4736 (TSTR("Block empty " TENDSTR)));
4737 dev->nErasedBlocks++;
4738 dev->nFreeChunks += dev->nChunksPerBlock;
4739 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4741 /* Determine the highest sequence number */
4742 if (dev->isYaffs2 &&
4743 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4744 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4746 blockIndex[nBlocksToScan].seq = sequenceNumber;
4747 blockIndex[nBlocksToScan].block = blk;
4751 if (sequenceNumber >= dev->sequenceNumber) {
4752 dev->sequenceNumber = sequenceNumber;
4754 } else if (dev->isYaffs2) {
4755 /* TODO: Nasty sequence number! */
4758 ("Block scanning block %d has bad sequence number %d"
4759 TENDSTR), blk, sequenceNumber));
4766 * Dungy old bubble sort for now...
4768 if (dev->isYaffs2) {
4769 yaffs_BlockIndex temp;
4773 for (i = 0; i < nBlocksToScan; i++)
4774 for (j = i + 1; j < nBlocksToScan; j++)
4775 if (blockIndex[i].seq > blockIndex[j].seq) {
4776 temp = blockIndex[j];
4777 blockIndex[j] = blockIndex[i];
4778 blockIndex[i] = temp;
4782 /* Now scan the blocks looking at the data. */
4783 if (dev->isYaffs2) {
4785 endIterator = nBlocksToScan - 1;
4786 T(YAFFS_TRACE_SCAN_DEBUG,
4787 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4789 startIterator = dev->internalStartBlock;
4790 endIterator = dev->internalEndBlock;
4793 /* For each block.... */
4794 for (blockIterator = startIterator; blockIterator <= endIterator;
4797 if (dev->isYaffs2) {
4798 /* get the block to scan in the correct order */
4799 blk = blockIndex[blockIterator].block;
4801 blk = blockIterator;
4804 bi = yaffs_GetBlockInfo(dev, blk);
4805 state = bi->blockState;
4809 /* For each chunk in each block that needs scanning....*/
4810 for (c = 0; c < dev->nChunksPerBlock &&
4811 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4812 /* Read the tags and decide what to do */
4813 chunk = blk * dev->nChunksPerBlock + c;
4815 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4818 /* Let's have a good look at this chunk... */
4820 if (!dev->isYaffs2 && tags.chunkDeleted) {
4826 /*T((" %d %d deleted\n",blk,c)); */
4827 } else if (!tags.chunkUsed) {
4828 /* An unassigned chunk in the block
4829 * This means that either the block is empty or
4830 * this is the one being allocated from
4834 /* We're looking at the first chunk in the block so the block is unused */
4835 state = YAFFS_BLOCK_STATE_EMPTY;
4836 dev->nErasedBlocks++;
4838 /* this is the block being allocated from */
4841 (" Allocating from %d %d" TENDSTR),
4843 state = YAFFS_BLOCK_STATE_ALLOCATING;
4844 dev->allocationBlock = blk;
4845 dev->allocationPage = c;
4846 dev->allocationBlockFinder = blk;
4847 /* Set it to here to encourage the allocator to go forth from here. */
4849 /* Yaffs2 sanity check:
4850 * This should be the one with the highest sequence number
4853 && (dev->sequenceNumber !=
4854 bi->sequenceNumber)) {
4855 T(YAFFS_TRACE_ALWAYS,
4857 ("yaffs: Allocation block %d was not highest sequence id:"
4858 " block seq = %d, dev seq = %d"
4859 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4863 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4864 } else if (tags.chunkId > 0) {
4865 /* chunkId > 0 so it is a data chunk... */
4866 unsigned int endpos;
4868 yaffs_SetChunkBit(dev, blk, c);
4871 in = yaffs_FindOrCreateObjectByNumber(dev,
4874 YAFFS_OBJECT_TYPE_FILE);
4875 /* PutChunkIntoFile checks for a clash (two data chunks with
4876 * the same chunkId).
4878 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4881 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
4883 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4884 && in->variant.fileVariant.scannedFileSize <
4886 in->variant.fileVariant.
4887 scannedFileSize = endpos;
4888 if (!dev->useHeaderFileSize) {
4889 in->variant.fileVariant.
4891 in->variant.fileVariant.
4896 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4898 /* chunkId == 0, so it is an ObjectHeader.
4899 * Thus, we read in the object header and make the object
4901 yaffs_SetChunkBit(dev, blk, c);
4904 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4908 oh = (yaffs_ObjectHeader *) chunkData;
4910 in = yaffs_FindObjectByNumber(dev,
4912 if (in && in->variantType != oh->type) {
4913 /* This should not happen, but somehow
4914 * Wev'e ended up with an objectId that has been reused but not yet
4915 * deleted, and worse still it has changed type. Delete the old object.
4918 yaffs_DestroyObject(in);
4923 in = yaffs_FindOrCreateObjectByNumber(dev,
4928 if (oh->shadowsObject > 0) {
4929 yaffs_HandleShadowedObject(dev,
4936 /* We have already filled this one. We have a duplicate and need to resolve it. */
4938 unsigned existingSerial = in->serial;
4939 unsigned newSerial = tags.serialNumber;
4941 if (dev->isYaffs2 ||
4942 ((existingSerial + 1) & 3) ==
4944 /* Use new one - destroy the exisiting one */
4945 yaffs_DeleteChunk(dev,
4950 /* Use existing - destroy this one. */
4951 yaffs_DeleteChunk(dev, chunk, 1,
4957 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4958 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4959 /* We only load some info, don't fiddle with directory structure */
4961 in->variantType = oh->type;
4963 in->yst_mode = oh->yst_mode;
4964 #ifdef CONFIG_YAFFS_WINCE
4965 in->win_atime[0] = oh->win_atime[0];
4966 in->win_ctime[0] = oh->win_ctime[0];
4967 in->win_mtime[0] = oh->win_mtime[0];
4968 in->win_atime[1] = oh->win_atime[1];
4969 in->win_ctime[1] = oh->win_ctime[1];
4970 in->win_mtime[1] = oh->win_mtime[1];
4972 in->yst_uid = oh->yst_uid;
4973 in->yst_gid = oh->yst_gid;
4974 in->yst_atime = oh->yst_atime;
4975 in->yst_mtime = oh->yst_mtime;
4976 in->yst_ctime = oh->yst_ctime;
4977 in->yst_rdev = oh->yst_rdev;
4979 in->chunkId = chunk;
4981 } else if (!in->valid) {
4982 /* we need to load this info */
4985 in->variantType = oh->type;
4987 in->yst_mode = oh->yst_mode;
4988 #ifdef CONFIG_YAFFS_WINCE
4989 in->win_atime[0] = oh->win_atime[0];
4990 in->win_ctime[0] = oh->win_ctime[0];
4991 in->win_mtime[0] = oh->win_mtime[0];
4992 in->win_atime[1] = oh->win_atime[1];
4993 in->win_ctime[1] = oh->win_ctime[1];
4994 in->win_mtime[1] = oh->win_mtime[1];
4996 in->yst_uid = oh->yst_uid;
4997 in->yst_gid = oh->yst_gid;
4998 in->yst_atime = oh->yst_atime;
4999 in->yst_mtime = oh->yst_mtime;
5000 in->yst_ctime = oh->yst_ctime;
5001 in->yst_rdev = oh->yst_rdev;
5003 in->chunkId = chunk;
5005 yaffs_SetObjectName(in, oh->name);
5008 /* directory stuff...
5013 yaffs_FindOrCreateObjectByNumber
5014 (dev, oh->parentObjectId,
5015 YAFFS_OBJECT_TYPE_DIRECTORY);
5016 if (parent->variantType ==
5017 YAFFS_OBJECT_TYPE_UNKNOWN) {
5018 /* Set up as a directory */
5019 parent->variantType =
5020 YAFFS_OBJECT_TYPE_DIRECTORY;
5021 INIT_LIST_HEAD(&parent->variant.
5024 } else if (parent->variantType !=
5025 YAFFS_OBJECT_TYPE_DIRECTORY)
5027 /* Hoosterman, another problem....
5028 * We're trying to use a non-directory as a directory
5031 T(YAFFS_TRACE_ERROR,
5033 ("yaffs tragedy: attempting to use non-directory as"
5034 " a directory in scan. Put in lost+found."
5036 parent = dev->lostNFoundDir;
5039 yaffs_AddObjectToDirectory(parent, in);
5041 if (0 && (parent == dev->deletedDir ||
5042 parent == dev->unlinkedDir)) {
5043 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5044 dev->nDeletedFiles++;
5046 /* Note re hardlinks.
5047 * Since we might scan a hardlink before its equivalent object is scanned
5048 * we put them all in a list.
5049 * After scanning is complete, we should have all the objects, so we run through this
5050 * list and fix up all the chains.
5053 switch (in->variantType) {
5054 case YAFFS_OBJECT_TYPE_UNKNOWN:
5055 /* Todo got a problem */
5057 case YAFFS_OBJECT_TYPE_FILE:
5060 /* Prune back the shrunken chunks */
5061 yaffs_PruneResizedChunks
5063 /* Mark the block as having a shrinkHeader */
5064 bi->hasShrinkHeader = 1;
5067 if (dev->useHeaderFileSize)
5069 in->variant.fileVariant.
5074 case YAFFS_OBJECT_TYPE_HARDLINK:
5075 in->variant.hardLinkVariant.
5076 equivalentObjectId =
5077 oh->equivalentObjectId;
5078 in->hardLinks.next =
5079 (struct list_head *)
5083 case YAFFS_OBJECT_TYPE_DIRECTORY:
5086 case YAFFS_OBJECT_TYPE_SPECIAL:
5089 case YAFFS_OBJECT_TYPE_SYMLINK:
5090 in->variant.symLinkVariant.
5092 yaffs_CloneString(oh->alias);
5096 if (parent == dev->deletedDir) {
5097 yaffs_DestroyObject(in);
5098 bi->hasShrinkHeader = 1;
5104 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5105 /* If we got this far while scanning, then the block is fully allocated.*/
5106 state = YAFFS_BLOCK_STATE_FULL;
5109 bi->blockState = state;
5111 /* Now let's see if it was dirty */
5112 if (bi->pagesInUse == 0 &&
5113 !bi->hasShrinkHeader &&
5114 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5115 yaffs_BlockBecameDirty(dev, blk);
5125 /* Ok, we've done all the scanning.
5126 * Fix up the hard link chains.
5127 * We should now have scanned all the objects, now it's time to add these
5131 yaffs_HardlinkFixup(dev,hardList);
5133 /* Handle the unlinked files. Since they were left in an unlinked state we should
5137 struct list_head *i;
5138 struct list_head *n;
5141 /* Soft delete all the unlinked files */
5142 list_for_each_safe(i, n,
5143 &dev->unlinkedDir->variant.directoryVariant.
5146 l = list_entry(i, yaffs_Object, siblings);
5147 yaffs_DestroyObject(l);
5152 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5154 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5159 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5162 yaffs_ObjectHeader *oh;
5163 yaffs_Device *dev = in->myDev;
5164 yaffs_ExtendedTags tags;
5168 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5170 in->lazyLoaded ? "not yet" : "already"));
5175 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5177 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5178 oh = (yaffs_ObjectHeader *) chunkData;
5180 in->yst_mode = oh->yst_mode;
5181 #ifdef CONFIG_YAFFS_WINCE
5182 in->win_atime[0] = oh->win_atime[0];
5183 in->win_ctime[0] = oh->win_ctime[0];
5184 in->win_mtime[0] = oh->win_mtime[0];
5185 in->win_atime[1] = oh->win_atime[1];
5186 in->win_ctime[1] = oh->win_ctime[1];
5187 in->win_mtime[1] = oh->win_mtime[1];
5189 in->yst_uid = oh->yst_uid;
5190 in->yst_gid = oh->yst_gid;
5191 in->yst_atime = oh->yst_atime;
5192 in->yst_mtime = oh->yst_mtime;
5193 in->yst_ctime = oh->yst_ctime;
5194 in->yst_rdev = oh->yst_rdev;
5197 yaffs_SetObjectName(in, oh->name);
5199 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5200 in->variant.symLinkVariant.alias =
5201 yaffs_CloneString(oh->alias);
5203 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5207 static int yaffs_ScanBackwards(yaffs_Device * dev)
5209 yaffs_ExtendedTags tags;
5214 int nBlocksToScan = 0;
5220 yaffs_BlockState state;
5221 yaffs_Object *hardList = NULL;
5222 yaffs_BlockInfo *bi;
5224 yaffs_ObjectHeader *oh;
5226 yaffs_Object *parent;
5227 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5233 int foundChunksInBlock;
5234 int equivalentObjectId;
5237 yaffs_BlockIndex *blockIndex = NULL;
5238 int altBlockIndex = 0;
5240 if (!dev->isYaffs2) {
5242 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5248 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5249 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5252 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5254 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5257 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5263 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5267 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5269 /* Scan all the blocks to determine their state */
5270 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5271 bi = yaffs_GetBlockInfo(dev, blk);
5272 yaffs_ClearChunkBits(dev, blk);
5274 bi->softDeletions = 0;
5276 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5278 bi->blockState = state;
5279 bi->sequenceNumber = sequenceNumber;
5281 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5282 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5284 T(YAFFS_TRACE_SCAN_DEBUG,
5285 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5286 state, sequenceNumber));
5289 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5290 /* todo .. fix free space ? */
5292 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5293 T(YAFFS_TRACE_BAD_BLOCKS,
5294 (TSTR("block %d is bad" TENDSTR), blk));
5295 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5296 T(YAFFS_TRACE_SCAN_DEBUG,
5297 (TSTR("Block empty " TENDSTR)));
5298 dev->nErasedBlocks++;
5299 dev->nFreeChunks += dev->nChunksPerBlock;
5300 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5302 /* Determine the highest sequence number */
5303 if (dev->isYaffs2 &&
5304 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5305 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5307 blockIndex[nBlocksToScan].seq = sequenceNumber;
5308 blockIndex[nBlocksToScan].block = blk;
5312 if (sequenceNumber >= dev->sequenceNumber) {
5313 dev->sequenceNumber = sequenceNumber;
5315 } else if (dev->isYaffs2) {
5316 /* TODO: Nasty sequence number! */
5319 ("Block scanning block %d has bad sequence number %d"
5320 TENDSTR), blk, sequenceNumber));
5327 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5333 /* Sort the blocks */
5334 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5336 /* Use qsort now. */
5337 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5341 /* Dungy old bubble sort... */
5343 yaffs_BlockIndex temp;
5347 for (i = 0; i < nBlocksToScan; i++)
5348 for (j = i + 1; j < nBlocksToScan; j++)
5349 if (blockIndex[i].seq > blockIndex[j].seq) {
5350 temp = blockIndex[j];
5351 blockIndex[j] = blockIndex[i];
5352 blockIndex[i] = temp;
5359 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5361 /* Now scan the blocks looking at the data. */
5363 endIterator = nBlocksToScan - 1;
5364 T(YAFFS_TRACE_SCAN_DEBUG,
5365 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5367 /* For each block.... backwards */
5368 for (blockIterator = endIterator; blockIterator >= startIterator;
5370 /* Cooperative multitasking! This loop can run for so
5371 long that watchdog timers expire. */
5374 /* get the block to scan in the correct order */
5375 blk = blockIndex[blockIterator].block;
5377 bi = yaffs_GetBlockInfo(dev, blk);
5378 state = bi->blockState;
5382 /* For each chunk in each block that needs scanning.... */
5383 foundChunksInBlock = 0;
5384 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5385 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5386 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5387 /* Scan backwards...
5388 * Read the tags and decide what to do
5390 chunk = blk * dev->nChunksPerBlock + c;
5392 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5395 /* Let's have a good look at this chunk... */
5397 if (!tags.chunkUsed) {
5398 /* An unassigned chunk in the block.
5399 * If there are used chunks after this one, then
5400 * it is a chunk that was skipped due to failing the erased
5401 * check. Just skip it so that it can be deleted.
5402 * But, more typically, We get here when this is an unallocated
5403 * chunk and his means that either the block is empty or
5404 * this is the one being allocated from
5407 if(foundChunksInBlock)
5409 /* This is a chunk that was skipped due to failing the erased check */
5411 } else if (c == 0) {
5412 /* We're looking at the first chunk in the block so the block is unused */
5413 state = YAFFS_BLOCK_STATE_EMPTY;
5414 dev->nErasedBlocks++;
5416 /* this is the block being allocated from */
5418 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5421 (" Allocating from %d %d"
5424 state = YAFFS_BLOCK_STATE_ALLOCATING;
5425 dev->allocationBlock = blk;
5426 dev->allocationPage = c;
5427 dev->allocationBlockFinder = blk;
5428 /* Set it to here to encourage the allocator to
5429 * go forth from here.
5432 /* Yaffs2 sanity check:
5433 * This should be the one with the highest sequence number
5436 && (dev->sequenceNumber !=
5437 bi->sequenceNumber)) {
5438 T(YAFFS_TRACE_ALWAYS,
5440 ("yaffs: Allocation block %d was not highest sequence "
5441 "id: block seq = %d, dev seq = %d"
5444 dev->sequenceNumber));
5449 } else if (tags.chunkId > 0) {
5450 /* chunkId > 0 so it is a data chunk... */
5451 unsigned int endpos;
5453 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
5455 foundChunksInBlock = 1;
5458 yaffs_SetChunkBit(dev, blk, c);
5461 in = yaffs_FindOrCreateObjectByNumber(dev,
5464 YAFFS_OBJECT_TYPE_FILE);
5465 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5467 in->variant.fileVariant.shrinkSize) {
5468 /* This has not been invalidated by a resize */
5469 yaffs_PutChunkIntoFile(in, tags.chunkId,
5472 /* File size is calculated by looking at the data chunks if we have not
5473 * seen an object header yet. Stop this practice once we find an object header.
5477 1) * dev->nDataBytesPerChunk +
5480 if (!in->valid && /* have not got an object header yet */
5481 in->variant.fileVariant.
5482 scannedFileSize < endpos) {
5483 in->variant.fileVariant.
5484 scannedFileSize = endpos;
5485 in->variant.fileVariant.
5487 in->variant.fileVariant.
5492 /* This chunk has been invalidated by a resize, so delete */
5493 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5497 /* chunkId == 0, so it is an ObjectHeader.
5498 * Thus, we read in the object header and make the object
5500 foundChunksInBlock = 1;
5502 yaffs_SetChunkBit(dev, blk, c);
5508 if (tags.extraHeaderInfoAvailable) {
5509 in = yaffs_FindOrCreateObjectByNumber
5510 (dev, tags.objectId,
5511 tags.extraObjectType);
5515 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5518 tags.extraShadows ||
5520 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5521 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5524 /* If we don't have valid info then we need to read the chunk
5525 * TODO In future we can probably defer reading the chunk and
5526 * living with invalid data until needed.
5529 result = yaffs_ReadChunkWithTagsFromNAND(dev,
5534 oh = (yaffs_ObjectHeader *) chunkData;
5537 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5542 /* TODO Hoosterman we have a problem! */
5543 T(YAFFS_TRACE_ERROR,
5545 ("yaffs tragedy: Could not make object for object %d "
5546 "at chunk %d during scan"
5547 TENDSTR), tags.objectId, chunk));
5552 /* We have already filled this one.
5553 * We have a duplicate that will be discarded, but
5554 * we first have to suck out resize info if it is a file.
5557 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5559 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5560 (tags.extraHeaderInfoAvailable &&
5561 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5564 (oh) ? oh->fileSize : tags.
5566 __u32 parentObjectId =
5568 parentObjectId : tags.
5569 extraParentObjectId;
5571 (oh) ? oh->isShrink : tags.
5572 extraIsShrinkHeader;
5574 /* If it is deleted (unlinked at start also means deleted)
5575 * we treat the file size as being zeroed at this point.
5577 if (parentObjectId ==
5578 YAFFS_OBJECTID_DELETED
5579 || parentObjectId ==
5580 YAFFS_OBJECTID_UNLINKED) {
5586 in->variant.fileVariant.
5587 shrinkSize > thisSize) {
5588 in->variant.fileVariant.
5594 bi->hasShrinkHeader = 1;
5598 /* Use existing - destroy this one. */
5599 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5604 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5606 YAFFS_OBJECTID_LOSTNFOUND)) {
5607 /* We only load some info, don't fiddle with directory structure */
5611 in->variantType = oh->type;
5613 in->yst_mode = oh->yst_mode;
5614 #ifdef CONFIG_YAFFS_WINCE
5615 in->win_atime[0] = oh->win_atime[0];
5616 in->win_ctime[0] = oh->win_ctime[0];
5617 in->win_mtime[0] = oh->win_mtime[0];
5618 in->win_atime[1] = oh->win_atime[1];
5619 in->win_ctime[1] = oh->win_ctime[1];
5620 in->win_mtime[1] = oh->win_mtime[1];
5622 in->yst_uid = oh->yst_uid;
5623 in->yst_gid = oh->yst_gid;
5624 in->yst_atime = oh->yst_atime;
5625 in->yst_mtime = oh->yst_mtime;
5626 in->yst_ctime = oh->yst_ctime;
5627 in->yst_rdev = oh->yst_rdev;
5631 in->variantType = tags.extraObjectType;
5635 in->chunkId = chunk;
5637 } else if (!in->valid) {
5638 /* we need to load this info */
5641 in->chunkId = chunk;
5644 in->variantType = oh->type;
5646 in->yst_mode = oh->yst_mode;
5647 #ifdef CONFIG_YAFFS_WINCE
5648 in->win_atime[0] = oh->win_atime[0];
5649 in->win_ctime[0] = oh->win_ctime[0];
5650 in->win_mtime[0] = oh->win_mtime[0];
5651 in->win_atime[1] = oh->win_atime[1];
5652 in->win_ctime[1] = oh->win_ctime[1];
5653 in->win_mtime[1] = oh->win_mtime[1];
5655 in->yst_uid = oh->yst_uid;
5656 in->yst_gid = oh->yst_gid;
5657 in->yst_atime = oh->yst_atime;
5658 in->yst_mtime = oh->yst_mtime;
5659 in->yst_ctime = oh->yst_ctime;
5660 in->yst_rdev = oh->yst_rdev;
5663 if (oh->shadowsObject > 0)
5664 yaffs_HandleShadowedObject(dev,
5670 yaffs_SetObjectName(in, oh->name);
5672 yaffs_FindOrCreateObjectByNumber
5673 (dev, oh->parentObjectId,
5674 YAFFS_OBJECT_TYPE_DIRECTORY);
5676 fileSize = oh->fileSize;
5677 isShrink = oh->isShrink;
5678 equivalentObjectId = oh->equivalentObjectId;
5682 in->variantType = tags.extraObjectType;
5684 yaffs_FindOrCreateObjectByNumber
5685 (dev, tags.extraParentObjectId,
5686 YAFFS_OBJECT_TYPE_DIRECTORY);
5687 fileSize = tags.extraFileLength;
5688 isShrink = tags.extraIsShrinkHeader;
5689 equivalentObjectId = tags.extraEquivalentObjectId;
5695 /* directory stuff...
5699 if (parent->variantType ==
5700 YAFFS_OBJECT_TYPE_UNKNOWN) {
5701 /* Set up as a directory */
5702 parent->variantType =
5703 YAFFS_OBJECT_TYPE_DIRECTORY;
5704 INIT_LIST_HEAD(&parent->variant.
5707 } else if (parent->variantType !=
5708 YAFFS_OBJECT_TYPE_DIRECTORY)
5710 /* Hoosterman, another problem....
5711 * We're trying to use a non-directory as a directory
5714 T(YAFFS_TRACE_ERROR,
5716 ("yaffs tragedy: attempting to use non-directory as"
5717 " a directory in scan. Put in lost+found."
5719 parent = dev->lostNFoundDir;
5722 yaffs_AddObjectToDirectory(parent, in);
5724 itsUnlinked = (parent == dev->deletedDir) ||
5725 (parent == dev->unlinkedDir);
5728 /* Mark the block as having a shrinkHeader */
5729 bi->hasShrinkHeader = 1;
5732 /* Note re hardlinks.
5733 * Since we might scan a hardlink before its equivalent object is scanned
5734 * we put them all in a list.
5735 * After scanning is complete, we should have all the objects, so we run
5736 * through this list and fix up all the chains.
5739 switch (in->variantType) {
5740 case YAFFS_OBJECT_TYPE_UNKNOWN:
5741 /* Todo got a problem */
5743 case YAFFS_OBJECT_TYPE_FILE:
5745 if (in->variant.fileVariant.
5746 scannedFileSize < fileSize) {
5747 /* This covers the case where the file size is greater
5748 * than where the data is
5749 * This will happen if the file is resized to be larger
5750 * than its current data extents.
5752 in->variant.fileVariant.fileSize = fileSize;
5753 in->variant.fileVariant.scannedFileSize =
5754 in->variant.fileVariant.fileSize;
5758 in->variant.fileVariant.shrinkSize > fileSize) {
5759 in->variant.fileVariant.shrinkSize = fileSize;
5763 case YAFFS_OBJECT_TYPE_HARDLINK:
5765 in->variant.hardLinkVariant.equivalentObjectId =
5767 in->hardLinks.next =
5768 (struct list_head *) hardList;
5772 case YAFFS_OBJECT_TYPE_DIRECTORY:
5775 case YAFFS_OBJECT_TYPE_SPECIAL:
5778 case YAFFS_OBJECT_TYPE_SYMLINK:
5780 in->variant.symLinkVariant.alias =
5781 yaffs_CloneString(oh->
5790 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5791 /* If we got this far while scanning, then the block is fully allocated. */
5792 state = YAFFS_BLOCK_STATE_FULL;
5795 bi->blockState = state;
5797 /* Now let's see if it was dirty */
5798 if (bi->pagesInUse == 0 &&
5799 !bi->hasShrinkHeader &&
5800 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5801 yaffs_BlockBecameDirty(dev, blk);
5807 YFREE_ALT(blockIndex);
5811 /* Ok, we've done all the scanning.
5812 * Fix up the hard link chains.
5813 * We should now have scanned all the objects, now it's time to add these
5816 yaffs_HardlinkFixup(dev,hardList);
5820 * Sort out state of unlinked and deleted objects.
5823 struct list_head *i;
5824 struct list_head *n;
5828 /* Soft delete all the unlinked files */
5829 list_for_each_safe(i, n,
5830 &dev->unlinkedDir->variant.directoryVariant.
5833 l = list_entry(i, yaffs_Object, siblings);
5834 yaffs_DestroyObject(l);
5838 /* Soft delete all the deletedDir files */
5839 list_for_each_safe(i, n,
5840 &dev->deletedDir->variant.directoryVariant.
5843 l = list_entry(i, yaffs_Object, siblings);
5844 yaffs_DestroyObject(l);
5850 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5852 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5857 /*------------------------------ Directory Functions ----------------------------- */
5859 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5861 yaffs_Device *dev = obj->myDev;
5863 if(dev && dev->removeObjectCallback)
5864 dev->removeObjectCallback(obj);
5866 list_del_init(&obj->siblings);
5871 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5876 T(YAFFS_TRACE_ALWAYS,
5878 ("tragedy: Trying to add an object to a null pointer directory"
5882 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5883 T(YAFFS_TRACE_ALWAYS,
5885 ("tragedy: Trying to add an object to a non-directory"
5890 if (obj->siblings.prev == NULL) {
5891 /* Not initialised */
5892 INIT_LIST_HEAD(&obj->siblings);
5894 } else if (!list_empty(&obj->siblings)) {
5895 /* If it is holed up somewhere else, un hook it */
5896 yaffs_RemoveObjectFromDirectory(obj);
5899 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5900 obj->parent = directory;
5902 if (directory == obj->myDev->unlinkedDir
5903 || directory == obj->myDev->deletedDir) {
5905 obj->myDev->nUnlinkedFiles++;
5906 obj->renameAllowed = 0;
5910 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5915 struct list_head *i;
5916 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5925 T(YAFFS_TRACE_ALWAYS,
5927 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5931 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5932 T(YAFFS_TRACE_ALWAYS,
5934 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5938 sum = yaffs_CalcNameSum(name);
5940 list_for_each(i, &directory->variant.directoryVariant.children) {
5942 l = list_entry(i, yaffs_Object, siblings);
5944 yaffs_CheckObjectDetailsLoaded(l);
5946 /* Special case for lost-n-found */
5947 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5948 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5951 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5953 /* LostnFound cunk called Objxxx
5956 yaffs_GetObjectName(l, buffer,
5957 YAFFS_MAX_NAME_LENGTH);
5958 if (yaffs_strcmp(name, buffer) == 0) {
5971 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5972 int (*fn) (yaffs_Object *))
5974 struct list_head *i;
5978 T(YAFFS_TRACE_ALWAYS,
5980 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5984 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5985 T(YAFFS_TRACE_ALWAYS,
5987 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5991 list_for_each(i, &theDir->variant.directoryVariant.children) {
5993 l = list_entry(i, yaffs_Object, siblings);
6005 /* GetEquivalentObject dereferences any hard links to get to the
6009 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6011 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6012 /* We want the object id of the equivalent object, not this one */
6013 obj = obj->variant.hardLinkVariant.equivalentObject;
6019 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6021 memset(name, 0, buffSize * sizeof(YCHAR));
6023 yaffs_CheckObjectDetailsLoaded(obj);
6025 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6026 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6027 } else if (obj->chunkId <= 0) {
6029 /* make up a name */
6030 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6032 yaffs_strncpy(name, locName, buffSize - 1);
6035 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6036 else if (obj->shortName[0]) {
6037 yaffs_strcpy(name, obj->shortName);
6042 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6044 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6046 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6048 if (obj->chunkId >= 0) {
6049 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6050 obj->chunkId, buffer,
6053 yaffs_strncpy(name, oh->name, buffSize - 1);
6055 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6058 return yaffs_strlen(name);
6061 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6064 /* Dereference any hard linking */
6065 obj = yaffs_GetEquivalentObject(obj);
6067 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6068 return obj->variant.fileVariant.fileSize;
6070 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6071 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6073 /* Only a directory should drop through to here */
6074 return obj->myDev->nDataBytesPerChunk;
6078 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6081 struct list_head *i;
6083 if (!obj->unlinked) {
6084 count++; /* the object itself */
6086 list_for_each(i, &obj->hardLinks) {
6087 count++; /* add the hard links; */
6093 int yaffs_GetObjectInode(yaffs_Object * obj)
6095 obj = yaffs_GetEquivalentObject(obj);
6097 return obj->objectId;
6100 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6102 obj = yaffs_GetEquivalentObject(obj);
6104 switch (obj->variantType) {
6105 case YAFFS_OBJECT_TYPE_FILE:
6108 case YAFFS_OBJECT_TYPE_DIRECTORY:
6111 case YAFFS_OBJECT_TYPE_SYMLINK:
6114 case YAFFS_OBJECT_TYPE_HARDLINK:
6117 case YAFFS_OBJECT_TYPE_SPECIAL:
6118 if (S_ISFIFO(obj->yst_mode))
6120 if (S_ISCHR(obj->yst_mode))
6122 if (S_ISBLK(obj->yst_mode))
6124 if (S_ISSOCK(obj->yst_mode))
6132 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6134 obj = yaffs_GetEquivalentObject(obj);
6135 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6136 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6138 return yaffs_CloneString(_Y(""));
6142 #ifndef CONFIG_YAFFS_WINCE
6144 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6146 unsigned int valid = attr->ia_valid;
6148 if (valid & ATTR_MODE)
6149 obj->yst_mode = attr->ia_mode;
6150 if (valid & ATTR_UID)
6151 obj->yst_uid = attr->ia_uid;
6152 if (valid & ATTR_GID)
6153 obj->yst_gid = attr->ia_gid;
6155 if (valid & ATTR_ATIME)
6156 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6157 if (valid & ATTR_CTIME)
6158 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6159 if (valid & ATTR_MTIME)
6160 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6162 if (valid & ATTR_SIZE)
6163 yaffs_ResizeFile(obj, attr->ia_size);
6165 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6170 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6172 unsigned int valid = 0;
6174 attr->ia_mode = obj->yst_mode;
6176 attr->ia_uid = obj->yst_uid;
6178 attr->ia_gid = obj->yst_gid;
6181 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6182 valid |= ATTR_ATIME;
6183 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6184 valid |= ATTR_CTIME;
6185 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6186 valid |= ATTR_MTIME;
6188 attr->ia_size = yaffs_GetFileSize(obj);
6191 attr->ia_valid = valid;
6200 int yaffs_DumpObject(yaffs_Object * obj)
6204 yaffs_GetObjectName(obj, name, 256);
6206 T(YAFFS_TRACE_ALWAYS,
6208 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6209 " chunk %d type %d size %d\n"
6210 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6211 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6212 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6218 /*---------------------------- Initialisation code -------------------------------------- */
6220 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6223 /* Common functions, gotta have */
6224 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6227 #ifdef CONFIG_YAFFS_YAFFS2
6229 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6230 if (dev->writeChunkWithTagsToNAND &&
6231 dev->readChunkWithTagsFromNAND &&
6232 !dev->writeChunkToNAND &&
6233 !dev->readChunkFromNAND &&
6234 dev->markNANDBlockBad && dev->queryNANDBlock)
6238 /* Can use the "spare" style interface for yaffs1 */
6239 if (!dev->isYaffs2 &&
6240 !dev->writeChunkWithTagsToNAND &&
6241 !dev->readChunkWithTagsFromNAND &&
6242 dev->writeChunkToNAND &&
6243 dev->readChunkFromNAND &&
6244 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6251 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6253 /* Initialise the unlinked, deleted, root and lost and found directories */
6255 dev->lostNFoundDir = dev->rootDir = NULL;
6256 dev->unlinkedDir = dev->deletedDir = NULL;
6259 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6261 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6264 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6265 YAFFS_ROOT_MODE | S_IFDIR);
6266 dev->lostNFoundDir =
6267 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6268 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6269 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6272 int yaffs_GutsInitialise(yaffs_Device * dev)
6277 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6279 /* Check stuff that must be set */
6282 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6286 dev->internalStartBlock = dev->startBlock;
6287 dev->internalEndBlock = dev->endBlock;
6288 dev->blockOffset = 0;
6289 dev->chunkOffset = 0;
6290 dev->nFreeChunks = 0;
6292 if (dev->startBlock == 0) {
6293 dev->internalStartBlock = dev->startBlock + 1;
6294 dev->internalEndBlock = dev->endBlock + 1;
6295 dev->blockOffset = 1;
6296 dev->chunkOffset = dev->nChunksPerBlock;
6299 /* Check geometry parameters. */
6301 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
6302 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
6303 dev->nChunksPerBlock < 2 ||
6304 dev->nReservedBlocks < 2 ||
6305 dev->internalStartBlock <= 0 ||
6306 dev->internalEndBlock <= 0 ||
6307 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6309 T(YAFFS_TRACE_ALWAYS,
6311 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6312 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6316 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6317 T(YAFFS_TRACE_ALWAYS,
6318 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6322 /* Got the right mix of functions? */
6323 if (!yaffs_CheckDevFunctions(dev)) {
6324 /* Function missing */
6325 T(YAFFS_TRACE_ALWAYS,
6327 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6332 /* This is really a compilation check. */
6333 if (!yaffs_CheckStructures()) {
6334 T(YAFFS_TRACE_ALWAYS,
6335 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6339 if (dev->isMounted) {
6340 T(YAFFS_TRACE_ALWAYS,
6341 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6345 /* Finished with most checks. One or two more checks happen later on too. */
6351 /* OK now calculate a few things for the device */
6354 * Calculate all the chunk size manipulation numbers:
6356 /* Start off assuming it is a power of 2 */
6357 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
6358 dev->chunkMask = (1<<dev->chunkShift) - 1;
6360 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
6361 /* Yes it is a power of 2, disable crumbs */
6363 dev->crumbShift = 0;
6364 dev->crumbsPerChunk = 0;
6366 /* Not a power of 2, use crumbs instead */
6367 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
6368 dev->crumbMask = (1<<dev->crumbShift)-1;
6369 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
6370 dev->chunkShift = 0;
6376 * Calculate chunkGroupBits.
6377 * We need to find the next power of 2 > than internalEndBlock
6380 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6384 /* Set up tnode width if wide tnodes are enabled. */
6385 if(!dev->wideTnodesDisabled){
6386 /* bits must be even so that we end up with 32-bit words */
6390 dev->tnodeWidth = 16;
6392 dev->tnodeWidth = bits;
6395 dev->tnodeWidth = 16;
6397 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6399 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6400 * so if the bitwidth of the
6401 * chunk range we're using is greater than 16 we need
6402 * to figure out chunk shift and chunkGroupSize
6405 if (bits <= dev->tnodeWidth)
6406 dev->chunkGroupBits = 0;
6408 dev->chunkGroupBits = bits - dev->tnodeWidth;
6411 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6413 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6414 /* We have a problem because the soft delete won't work if
6415 * the chunk group size > chunks per block.
6416 * This can be remedied by using larger "virtual blocks".
6418 T(YAFFS_TRACE_ALWAYS,
6419 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6424 /* OK, we've finished verifying the device, lets continue with initialisation */
6426 /* More device initialisation */
6427 dev->garbageCollections = 0;
6428 dev->passiveGarbageCollections = 0;
6429 dev->currentDirtyChecker = 0;
6430 dev->bufferedBlock = -1;
6431 dev->doingBufferedBlockRewrite = 0;
6432 dev->nDeletedFiles = 0;
6433 dev->nBackgroundDeletions = 0;
6434 dev->nUnlinkedFiles = 0;
6436 dev->eccUnfixed = 0;
6437 dev->tagsEccFixed = 0;
6438 dev->tagsEccUnfixed = 0;
6439 dev->nErasureFailures = 0;
6440 dev->nErasedBlocks = 0;
6442 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
6444 /* Initialise temporary buffers and caches. */
6447 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6448 dev->tempBuffer[i].line = 0; /* not in use */
6449 dev->tempBuffer[i].buffer =
6450 YMALLOC_DMA(dev->nDataBytesPerChunk);
6454 if (dev->nShortOpCaches > 0) {
6457 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6458 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6462 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6464 for (i = 0; i < dev->nShortOpCaches; i++) {
6465 dev->srCache[i].object = NULL;
6466 dev->srCache[i].lastUse = 0;
6467 dev->srCache[i].dirty = 0;
6468 dev->srCache[i].data = YMALLOC_DMA(dev->nDataBytesPerChunk);
6475 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6477 if (dev->isYaffs2) {
6478 dev->useHeaderFileSize = 1;
6481 yaffs_InitialiseBlocks(dev);
6482 yaffs_InitialiseTnodes(dev);
6483 yaffs_InitialiseObjects(dev);
6485 yaffs_CreateInitialDirectories(dev);
6488 /* Now scan the flash. */
6489 if (dev->isYaffs2) {
6490 if(yaffs_CheckpointRestore(dev)) {
6491 T(YAFFS_TRACE_ALWAYS,
6492 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6495 /* Clean up the mess caused by an aborted checkpoint load
6496 * and scan backwards.
6498 yaffs_DeinitialiseBlocks(dev);
6499 yaffs_DeinitialiseTnodes(dev);
6500 yaffs_DeinitialiseObjects(dev);
6501 yaffs_InitialiseBlocks(dev);
6502 yaffs_InitialiseTnodes(dev);
6503 yaffs_InitialiseObjects(dev);
6504 yaffs_CreateInitialDirectories(dev);
6506 yaffs_ScanBackwards(dev);
6511 /* Zero out stats */
6512 dev->nPageReads = 0;
6513 dev->nPageWrites = 0;
6514 dev->nBlockErasures = 0;
6516 dev->nRetriedWrites = 0;
6518 dev->nRetiredBlocks = 0;
6520 yaffs_VerifyFreeChunks(dev);
6522 T(YAFFS_TRACE_TRACING,
6523 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6528 void yaffs_Deinitialise(yaffs_Device * dev)
6530 if (dev->isMounted) {
6533 yaffs_DeinitialiseBlocks(dev);
6534 yaffs_DeinitialiseTnodes(dev);
6535 yaffs_DeinitialiseObjects(dev);
6536 if (dev->nShortOpCaches > 0) {
6538 for (i = 0; i < dev->nShortOpCaches; i++) {
6539 YFREE(dev->srCache[i].data);
6542 YFREE(dev->srCache);
6545 YFREE(dev->gcCleanupList);
6547 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6548 YFREE(dev->tempBuffer[i].buffer);
6556 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6561 yaffs_BlockInfo *blk;
6563 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6565 blk = yaffs_GetBlockInfo(dev, b);
6567 switch (blk->blockState) {
6568 case YAFFS_BLOCK_STATE_EMPTY:
6569 case YAFFS_BLOCK_STATE_ALLOCATING:
6570 case YAFFS_BLOCK_STATE_COLLECTING:
6571 case YAFFS_BLOCK_STATE_FULL:
6573 (dev->nChunksPerBlock - blk->pagesInUse +
6574 blk->softDeletions);
6585 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6587 /* This is what we report to the outside world */
6590 int nDirtyCacheChunks;
6591 int blocksForCheckpoint;
6594 nFree = dev->nFreeChunks;
6596 nFree = yaffs_CountFreeChunks(dev);
6599 nFree += dev->nDeletedFiles;
6601 /* Now count the number of dirty chunks in the cache and subtract those */
6605 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6606 if (dev->srCache[i].dirty)
6607 nDirtyCacheChunks++;
6611 nFree -= nDirtyCacheChunks;
6613 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6615 /* Now we figure out how much to reserve for the checkpoint and report that... */
6616 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6617 if(blocksForCheckpoint < 0)
6618 blocksForCheckpoint = 0;
6620 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6629 static int yaffs_freeVerificationFailures;
6631 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6633 int counted = yaffs_CountFreeChunks(dev);
6635 int difference = dev->nFreeChunks - counted;
6638 T(YAFFS_TRACE_ALWAYS,
6639 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6640 dev->nFreeChunks, counted, difference));
6641 yaffs_freeVerificationFailures++;
6645 /*---------------------------------------- YAFFS test code ----------------------*/
6647 #define yaffs_CheckStruct(structure,syze, name) \
6648 if(sizeof(structure) != syze) \
6650 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6651 name,syze,sizeof(structure))); \
6652 return YAFFS_FAIL; \
6655 static int yaffs_CheckStructures(void)
6657 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6658 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6659 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6660 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6661 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6663 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")