2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2007 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.
14 const char *yaffs_guts_c_version =
15 "$Id: yaffs_guts.c,v 1.47 2007-02-14 01:09:06 wookey Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_tagscompat.h"
24 #ifndef CONFIG_YAFFS_OWN_SORT
25 #include "yaffs_qsort.h"
27 #include "yaffs_nand.h"
29 #include "yaffs_checkptrw.h"
31 #include "yaffs_nand.h"
32 #include "yaffs_packedtags2.h"
35 #ifdef CONFIG_YAFFS_WINCE
36 void yfsd_LockYAFFS(BOOL fsLockOnly);
37 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
40 #define YAFFS_PASSIVE_GC_CHUNKS 2
42 #include "yaffs_ecc.h"
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
48 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
50 const yaffs_ExtendedTags * tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
52 const yaffs_ExtendedTags * tags);
54 /* Other local prototypes */
55 static int yaffs_UnlinkObject( yaffs_Object *obj);
56 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62 yaffs_ExtendedTags * tags,
64 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
65 int chunkInNAND, int inScan);
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
68 yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
72 int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
76 int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
82 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
85 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
88 static int yaffs_UnlinkWorker(yaffs_Object * obj);
89 static void yaffs_DestroyObject(yaffs_Object * obj);
91 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
94 loff_t yaffs_GetFileSize(yaffs_Object * obj);
96 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
98 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
100 #ifdef YAFFS_PARANOID
101 static int yaffs_CheckFileSanity(yaffs_Object * in);
103 #define yaffs_CheckFileSanity(in)
106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
107 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
109 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
113 /* Function to calculate chunk and offset */
115 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
118 /* Easy-peasy power of 2 case */
119 *chunk = (__u32)(addr >> dev->chunkShift);
120 *offset = (__u32)(addr & dev->chunkMask);
122 else if(dev->crumbsPerChunk)
124 /* Case where we're using "crumbs" */
125 *offset = (__u32)(addr & dev->crumbMask);
126 addr >>= dev->crumbShift;
127 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
128 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
134 /* Function to return the number of shifts for a power of 2 greater than or equal
135 * to the given number
136 * Note we don't try to cater for all possible numbers and this does not have to
137 * be hellishly efficient.
140 static __u32 ShiftsGE(__u32 x)
145 nShifts = extraBits = 0;
148 if(x & 1) extraBits++;
159 /* Function to return the number of shifts to get a 1 in bit 0
162 static __u32 ShiftDiv(__u32 x)
181 * Temporary buffer manipulations.
184 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
187 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
188 if (dev->tempBuffer[i].line == 0) {
189 dev->tempBuffer[i].line = lineNo;
190 if ((i + 1) > dev->maxTemp) {
191 dev->maxTemp = i + 1;
192 for (j = 0; j <= i; j++)
193 dev->tempBuffer[j].maxLine =
194 dev->tempBuffer[j].line;
197 return dev->tempBuffer[i].buffer;
201 T(YAFFS_TRACE_BUFFERS,
202 (TSTR("Out of temp buffers at line %d, other held by lines:"),
204 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
205 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
207 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
210 * If we got here then we have to allocate an unmanaged one
214 dev->unmanagedTempAllocations++;
215 return YMALLOC(dev->nDataBytesPerChunk);
219 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
223 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
224 if (dev->tempBuffer[i].buffer == buffer) {
225 dev->tempBuffer[i].line = 0;
231 /* assume it is an unmanaged one. */
232 T(YAFFS_TRACE_BUFFERS,
233 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
236 dev->unmanagedTempDeallocations++;
242 * Determine if we have a managed buffer.
244 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
247 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
248 if (dev->tempBuffer[i].buffer == buffer)
253 for (i = 0; i < dev->nShortOpCaches; i++) {
254 if( dev->srCache[i].data == buffer )
259 if (buffer == dev->checkpointBuffer)
262 T(YAFFS_TRACE_ALWAYS,
263 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
268 * Chunk bitmap manipulations
271 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
273 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
275 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
279 return dev->chunkBits +
280 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
283 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
285 __u8 *blkBits = yaffs_BlockBits(dev, blk);
287 memset(blkBits, 0, dev->chunkBitmapStride);
290 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
292 __u8 *blkBits = yaffs_BlockBits(dev, blk);
294 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
297 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
299 __u8 *blkBits = yaffs_BlockBits(dev, blk);
301 blkBits[chunk / 8] |= (1 << (chunk & 7));
304 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
306 __u8 *blkBits = yaffs_BlockBits(dev, blk);
307 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
310 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
312 __u8 *blkBits = yaffs_BlockBits(dev, blk);
314 for (i = 0; i < dev->chunkBitmapStride; i++) {
323 * Simple hash function. Needs to have a reasonable spread
326 static Y_INLINE int yaffs_HashFunction(int n)
329 return (n % YAFFS_NOBJECT_BUCKETS);
333 * Access functions to useful fake objects
336 yaffs_Object *yaffs_Root(yaffs_Device * dev)
341 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
343 return dev->lostNFoundDir;
348 * Erased NAND checking functions
351 int yaffs_CheckFF(__u8 * buffer, int nBytes)
353 /* Horrible, slow implementation */
362 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
366 int retval = YAFFS_OK;
367 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
368 yaffs_ExtendedTags tags;
371 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
373 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
377 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
378 T(YAFFS_TRACE_NANDACCESS,
379 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
383 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
389 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
391 yaffs_ExtendedTags * tags,
401 yaffs_InvalidateCheckpoint(dev);
404 chunk = yaffs_AllocateChunk(dev, useReserve,&bi);
407 /* First check this chunk is erased, if it needs checking.
408 * The checking policy (unless forced always on) is as follows:
409 * Check the first page we try to write in a block.
410 * - If the check passes then we don't need to check any more.
411 * - If the check fails, we check again...
412 * If the block has been erased, we don't need to check.
414 * However, if the block has been prioritised for gc, then
415 * we think there might be something odd about this block
419 * We should only ever see chunks that have not been erased
420 * if there was a partially written chunk due to power loss
421 * This checking policy should catch that case with very
422 * few checks and thus save a lot of checks that are most likely not
426 if(bi->gcPrioritise){
427 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
429 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
431 bi->skipErasedCheck = 0;
434 if(!bi->skipErasedCheck){
435 erasedOk = yaffs_CheckChunkErased(dev, chunk);
436 if(erasedOk && !bi->gcPrioritise)
437 bi->skipErasedCheck = 1;
443 ("**>> yaffs chunk %d was not erased"
447 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
455 * Copy the data into the robustification buffer.
456 * NB We do this at the end to prevent duplicates in the case of a write error.
459 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
462 /* The erased check or write failed */
463 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
468 } while (chunk >= 0 && !writeOk);
472 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
474 dev->nRetriedWrites += (attempts - 1);
481 * Block retiring for handling a broken block.
484 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
486 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
488 yaffs_InvalidateCheckpoint(dev);
490 yaffs_MarkBlockBad(dev, blockInNAND);
492 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
493 bi->gcPrioritise = 0;
494 bi->needsRetiring = 0;
496 dev->nRetiredBlocks++;
500 * Functions for robustisizing TODO
504 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
506 const yaffs_ExtendedTags * tags)
510 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
511 const yaffs_ExtendedTags * tags)
515 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
517 if(!bi->gcPrioritise){
518 bi->gcPrioritise = 1;
519 dev->hasPendingPrioritisedGCs = 1;
520 bi->chunkErrorStrikes ++;
522 if(bi->chunkErrorStrikes > 3){
523 bi->needsRetiring = 1; /* Too many stikes, so retire this */
524 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
531 static void yaffs_ReportOddballBlocks(yaffs_Device *dev)
535 for(i = dev->internalStartBlock; i <= dev->internalEndBlock && (yaffs_traceMask & YAFFS_TRACE_BAD_BLOCKS); i++){
536 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
537 if(bi->needsRetiring || bi->gcPrioritise)
538 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("yaffs block %d%s%s" TENDSTR),
540 bi->needsRetiring ? " needs retiring" : "",
541 bi->gcPrioritise ? " gc prioritised" : ""));
546 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
549 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
550 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
552 yaffs_HandleChunkError(dev,bi);
556 /* Was an actual write failure, so mark the block for retirement */
557 bi->needsRetiring = 1;
558 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
559 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
564 /* Delete the chunk */
565 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
569 /*---------------- Name handling functions ------------*/
571 static __u16 yaffs_CalcNameSum(const YCHAR * name)
576 YUCHAR *bname = (YUCHAR *) name;
578 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
580 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
581 sum += yaffs_toupper(*bname) * i;
592 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
594 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
595 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
596 yaffs_strcpy(obj->shortName, name);
598 obj->shortName[0] = _Y('\0');
601 obj->sum = yaffs_CalcNameSum(name);
604 /*-------------------- TNODES -------------------
606 * List of spare tnodes
607 * The list is hooked together using the first pointer
611 /* yaffs_CreateTnodes creates a bunch more tnodes and
612 * adds them to the tnode free list.
613 * Don't use this function directly
616 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
620 yaffs_Tnode *newTnodes;
624 yaffs_TnodeList *tnl;
629 /* Calculate the tnode size in bytes for variable width tnode support.
630 * Must be a multiple of 32-bits */
631 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
633 /* make these things */
635 newTnodes = YMALLOC(nTnodes * tnodeSize);
636 mem = (__u8 *)newTnodes;
640 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
644 /* Hook them into the free list */
646 for (i = 0; i < nTnodes - 1; i++) {
647 newTnodes[i].internal[0] = &newTnodes[i + 1];
648 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
649 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
653 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
654 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
655 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
657 dev->freeTnodes = newTnodes;
659 /* New hookup for wide tnodes */
660 for(i = 0; i < nTnodes -1; i++) {
661 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
662 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
663 curr->internal[0] = next;
666 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
667 curr->internal[0] = dev->freeTnodes;
668 dev->freeTnodes = (yaffs_Tnode *)mem;
673 dev->nFreeTnodes += nTnodes;
674 dev->nTnodesCreated += nTnodes;
676 /* Now add this bunch of tnodes to a list for freeing up.
677 * NB If we can't add this to the management list it isn't fatal
678 * but it just means we can't free this bunch of tnodes later.
681 tnl = YMALLOC(sizeof(yaffs_TnodeList));
685 ("yaffs: Could not add tnodes to management list" TENDSTR)));
688 tnl->tnodes = newTnodes;
689 tnl->next = dev->allocatedTnodeList;
690 dev->allocatedTnodeList = tnl;
693 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
698 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
700 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
702 yaffs_Tnode *tn = NULL;
704 /* If there are none left make more */
705 if (!dev->freeTnodes) {
706 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
709 if (dev->freeTnodes) {
710 tn = dev->freeTnodes;
711 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
712 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
713 /* Hoosterman, this thing looks like it isn't in the list */
714 T(YAFFS_TRACE_ALWAYS,
715 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
718 dev->freeTnodes = dev->freeTnodes->internal[0];
725 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
727 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
730 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
735 /* FreeTnode frees up a tnode and puts it back on the free list */
736 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
739 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
740 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
741 /* Hoosterman, this thing looks like it is already in the list */
742 T(YAFFS_TRACE_ALWAYS,
743 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
745 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
747 tn->internal[0] = dev->freeTnodes;
748 dev->freeTnodes = tn;
753 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
755 /* Free the list of allocated tnodes */
756 yaffs_TnodeList *tmp;
758 while (dev->allocatedTnodeList) {
759 tmp = dev->allocatedTnodeList->next;
761 YFREE(dev->allocatedTnodeList->tnodes);
762 YFREE(dev->allocatedTnodeList);
763 dev->allocatedTnodeList = tmp;
767 dev->freeTnodes = NULL;
768 dev->nFreeTnodes = 0;
771 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
773 dev->allocatedTnodeList = NULL;
774 dev->freeTnodes = NULL;
775 dev->nFreeTnodes = 0;
776 dev->nTnodesCreated = 0;
781 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
783 __u32 *map = (__u32 *)tn;
789 pos &= YAFFS_TNODES_LEVEL0_MASK;
790 val >>= dev->chunkGroupBits;
792 bitInMap = pos * dev->tnodeWidth;
793 wordInMap = bitInMap /32;
794 bitInWord = bitInMap & (32 -1);
796 mask = dev->tnodeMask << bitInWord;
798 map[wordInMap] &= ~mask;
799 map[wordInMap] |= (mask & (val << bitInWord));
801 if(dev->tnodeWidth > (32-bitInWord)) {
802 bitInWord = (32 - bitInWord);
804 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
805 map[wordInMap] &= ~mask;
806 map[wordInMap] |= (mask & (val >> bitInWord));
810 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
812 __u32 *map = (__u32 *)tn;
818 pos &= YAFFS_TNODES_LEVEL0_MASK;
820 bitInMap = pos * dev->tnodeWidth;
821 wordInMap = bitInMap /32;
822 bitInWord = bitInMap & (32 -1);
824 val = map[wordInMap] >> bitInWord;
826 if(dev->tnodeWidth > (32-bitInWord)) {
827 bitInWord = (32 - bitInWord);
829 val |= (map[wordInMap] << bitInWord);
832 val &= dev->tnodeMask;
833 val <<= dev->chunkGroupBits;
838 /* ------------------- End of individual tnode manipulation -----------------*/
840 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
841 * The look up tree is represented by the top tnode and the number of topLevel
842 * in the tree. 0 means only the level 0 tnode is in the tree.
845 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
846 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
847 yaffs_FileStructure * fStruct,
851 yaffs_Tnode *tn = fStruct->top;
853 int requiredTallness;
854 int level = fStruct->topLevel;
856 /* Check sane level and chunk Id */
857 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
861 if (chunkId > YAFFS_MAX_CHUNK_ID) {
865 /* First check we're tall enough (ie enough topLevel) */
867 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
868 requiredTallness = 0;
870 i >>= YAFFS_TNODES_INTERNAL_BITS;
874 if (requiredTallness > fStruct->topLevel) {
875 /* Not tall enough, so we can't find it, return NULL. */
879 /* Traverse down to level 0 */
880 while (level > 0 && tn) {
883 ( YAFFS_TNODES_LEVEL0_BITS +
885 YAFFS_TNODES_INTERNAL_BITS)
887 YAFFS_TNODES_INTERNAL_MASK];
895 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
896 * This happens in two steps:
897 * 1. If the tree isn't tall enough, then make it taller.
898 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
900 * Used when modifying the tree.
902 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
903 * be plugged into the ttree.
906 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
907 yaffs_FileStructure * fStruct,
909 yaffs_Tnode *passedTn)
912 int requiredTallness;
920 /* Check sane level and page Id */
921 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
925 if (chunkId > YAFFS_MAX_CHUNK_ID) {
929 /* First check we're tall enough (ie enough topLevel) */
931 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
932 requiredTallness = 0;
934 x >>= YAFFS_TNODES_INTERNAL_BITS;
939 if (requiredTallness > fStruct->topLevel) {
940 /* Not tall enough,gotta make the tree taller */
941 for (i = fStruct->topLevel; i < requiredTallness; i++) {
943 tn = yaffs_GetTnode(dev);
946 tn->internal[0] = fStruct->top;
950 (TSTR("yaffs: no more tnodes" TENDSTR)));
954 fStruct->topLevel = requiredTallness;
957 /* Traverse down to level 0, adding anything we need */
959 l = fStruct->topLevel;
963 while (l > 0 && tn) {
965 ( YAFFS_TNODES_LEVEL0_BITS +
966 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
967 YAFFS_TNODES_INTERNAL_MASK;
970 if((l>1) && !tn->internal[x]){
971 /* Add missing non-level-zero tnode */
972 tn->internal[x] = yaffs_GetTnode(dev);
975 /* Looking from level 1 at level 0 */
977 /* If we already have one, then release it.*/
979 yaffs_FreeTnode(dev,tn->internal[x]);
980 tn->internal[x] = passedTn;
982 } else if(!tn->internal[x]) {
983 /* Don't have one, none passed in */
984 tn->internal[x] = yaffs_GetTnode(dev);
988 tn = tn->internal[x];
994 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
995 yaffs_FreeTnode(dev,passedTn);
1002 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1003 yaffs_ExtendedTags * tags, int objectId,
1008 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1009 if (yaffs_CheckChunkBit
1010 (dev, theChunk / dev->nChunksPerBlock,
1011 theChunk % dev->nChunksPerBlock)) {
1012 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1014 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1026 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1027 * chunks and tnodes in the file
1028 * Returns 1 if the tree was deleted.
1029 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1032 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1033 int chunkOffset, int *limit)
1038 yaffs_ExtendedTags tags;
1040 yaffs_Device *dev = in->myDev;
1047 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1049 if (tn->internal[i]) {
1050 if (limit && (*limit) < 0) {
1054 yaffs_DeleteWorker(in,
1062 YAFFS_TNODES_INTERNAL_BITS)
1067 yaffs_FreeTnode(dev,
1070 tn->internal[i] = NULL;
1075 return (allDone) ? 1 : 0;
1076 } else if (level == 0) {
1079 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1081 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1086 YAFFS_TNODES_LEVEL0_BITS) + i;
1089 yaffs_FindChunkInGroup(dev,
1095 if (foundChunk > 0) {
1096 yaffs_DeleteChunk(dev,
1101 *limit = *limit - 1;
1109 yaffs_PutLevel0Tnode(dev,tn,i,0);
1113 return (i < 0) ? 1 : 0;
1123 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1126 yaffs_BlockInfo *theBlock;
1128 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1130 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1132 theBlock->softDeletions++;
1137 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1138 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1140 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1143 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1144 __u32 level, int chunkOffset)
1149 yaffs_Device *dev = in->myDev;
1154 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1156 if (tn->internal[i]) {
1158 yaffs_SoftDeleteWorker(in,
1164 YAFFS_TNODES_INTERNAL_BITS)
1167 yaffs_FreeTnode(dev,
1170 tn->internal[i] = NULL;
1172 /* Hoosterman... how could this happen? */
1176 return (allDone) ? 1 : 0;
1177 } else if (level == 0) {
1179 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1180 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1182 /* Note this does not find the real chunk, only the chunk group.
1183 * We make an assumption that a chunk group is not larger than
1186 yaffs_SoftDeleteChunk(dev, theChunk);
1187 yaffs_PutLevel0Tnode(dev,tn,i,0);
1201 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1204 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1205 if (obj->nDataChunks <= 0) {
1206 /* Empty file with no duplicate object headers, just delete it immediately */
1207 yaffs_FreeTnode(obj->myDev,
1208 obj->variant.fileVariant.top);
1209 obj->variant.fileVariant.top = NULL;
1210 T(YAFFS_TRACE_TRACING,
1211 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1213 yaffs_DoGenericObjectDeletion(obj);
1215 yaffs_SoftDeleteWorker(obj,
1216 obj->variant.fileVariant.top,
1217 obj->variant.fileVariant.
1219 obj->softDeleted = 1;
1224 /* Pruning removes any part of the file structure tree that is beyond the
1225 * bounds of the file (ie that does not point to chunks).
1227 * A file should only get pruned when its size is reduced.
1229 * Before pruning, the chunks must be pulled from the tree and the
1230 * level 0 tnode entries must be zeroed out.
1231 * Could also use this for file deletion, but that's probably better handled
1232 * by a special case.
1235 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1236 __u32 level, int del0)
1244 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1245 if (tn->internal[i] && level > 0) {
1247 yaffs_PruneWorker(dev, tn->internal[i],
1249 (i == 0) ? del0 : 1);
1252 if (tn->internal[i]) {
1257 if (hasData == 0 && del0) {
1258 /* Free and return NULL */
1260 yaffs_FreeTnode(dev, tn);
1270 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1271 yaffs_FileStructure * fStruct)
1278 if (fStruct->topLevel > 0) {
1280 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1282 /* Now we have a tree with all the non-zero branches NULL but the height
1283 * is the same as it was.
1284 * Let's see if we can trim internal tnodes to shorten the tree.
1285 * We can do this if only the 0th element in the tnode is in use
1286 * (ie all the non-zero are NULL)
1289 while (fStruct->topLevel && !done) {
1293 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1294 if (tn->internal[i]) {
1300 fStruct->top = tn->internal[0];
1301 fStruct->topLevel--;
1302 yaffs_FreeTnode(dev, tn);
1312 /*-------------------- End of File Structure functions.-------------------*/
1314 /* yaffs_CreateFreeObjects creates a bunch more objects and
1315 * adds them to the object free list.
1317 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1320 yaffs_Object *newObjects;
1321 yaffs_ObjectList *list;
1326 /* make these things */
1327 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1330 T(YAFFS_TRACE_ALLOCATE,
1331 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1335 /* Hook them into the free list */
1336 for (i = 0; i < nObjects - 1; i++) {
1337 newObjects[i].siblings.next =
1338 (struct list_head *)(&newObjects[i + 1]);
1341 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1342 dev->freeObjects = newObjects;
1343 dev->nFreeObjects += nObjects;
1344 dev->nObjectsCreated += nObjects;
1346 /* Now add this bunch of Objects to a list for freeing up. */
1348 list = YMALLOC(sizeof(yaffs_ObjectList));
1350 T(YAFFS_TRACE_ALLOCATE,
1351 (TSTR("Could not add objects to management list" TENDSTR)));
1353 list->objects = newObjects;
1354 list->next = dev->allocatedObjectList;
1355 dev->allocatedObjectList = list;
1362 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1363 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1365 yaffs_Object *tn = NULL;
1367 /* If there are none left make more */
1368 if (!dev->freeObjects) {
1369 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1372 if (dev->freeObjects) {
1373 tn = dev->freeObjects;
1375 (yaffs_Object *) (dev->freeObjects->siblings.next);
1376 dev->nFreeObjects--;
1378 /* Now sweeten it up... */
1380 memset(tn, 0, sizeof(yaffs_Object));
1383 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1384 INIT_LIST_HEAD(&(tn->hardLinks));
1385 INIT_LIST_HEAD(&(tn->hashLink));
1386 INIT_LIST_HEAD(&tn->siblings);
1388 /* Add it to the lost and found directory.
1389 * NB Can't put root or lostNFound in lostNFound so
1390 * check if lostNFound exists first
1392 if (dev->lostNFoundDir) {
1393 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1400 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1405 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1407 obj->fake = 1; /* it is fake so it has no NAND presence... */
1408 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1409 obj->unlinkAllowed = 0; /* ... or unlink it */
1412 obj->yst_mode = mode;
1414 obj->chunkId = 0; /* Not a valid chunk. */
1421 static void yaffs_UnhashObject(yaffs_Object * tn)
1424 yaffs_Device *dev = tn->myDev;
1426 /* If it is still linked into the bucket list, free from the list */
1427 if (!list_empty(&tn->hashLink)) {
1428 list_del_init(&tn->hashLink);
1429 bucket = yaffs_HashFunction(tn->objectId);
1430 dev->objectBucket[bucket].count--;
1435 /* FreeObject frees up a Object and puts it back on the free list */
1436 static void yaffs_FreeObject(yaffs_Object * tn)
1439 yaffs_Device *dev = tn->myDev;
1443 /* We're still hooked up to a cached inode.
1444 * Don't delete now, but mark for later deletion
1446 tn->deferedFree = 1;
1451 yaffs_UnhashObject(tn);
1453 /* Link into the free list. */
1454 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1455 dev->freeObjects = tn;
1456 dev->nFreeObjects++;
1461 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1463 if (obj->deferedFree) {
1464 yaffs_FreeObject(obj);
1470 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1472 /* Free the list of allocated Objects */
1474 yaffs_ObjectList *tmp;
1476 while (dev->allocatedObjectList) {
1477 tmp = dev->allocatedObjectList->next;
1478 YFREE(dev->allocatedObjectList->objects);
1479 YFREE(dev->allocatedObjectList);
1481 dev->allocatedObjectList = tmp;
1484 dev->freeObjects = NULL;
1485 dev->nFreeObjects = 0;
1488 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1492 dev->allocatedObjectList = NULL;
1493 dev->freeObjects = NULL;
1494 dev->nFreeObjects = 0;
1496 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1497 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1498 dev->objectBucket[i].count = 0;
1503 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1508 int lowest = 999999;
1510 /* First let's see if we can find one that's empty. */
1512 for (i = 0; i < 10 && lowest > 0; i++) {
1514 x %= YAFFS_NOBJECT_BUCKETS;
1515 if (dev->objectBucket[x].count < lowest) {
1516 lowest = dev->objectBucket[x].count;
1522 /* If we didn't find an empty list, then try
1523 * looking a bit further for a short one
1526 for (i = 0; i < 10 && lowest > 3; i++) {
1528 x %= YAFFS_NOBJECT_BUCKETS;
1529 if (dev->objectBucket[x].count < lowest) {
1530 lowest = dev->objectBucket[x].count;
1539 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1541 int bucket = yaffs_FindNiceObjectBucket(dev);
1543 /* Now find an object value that has not already been taken
1544 * by scanning the list.
1548 struct list_head *i;
1550 __u32 n = (__u32) bucket;
1552 /* yaffs_CheckObjectHashSanity(); */
1556 n += YAFFS_NOBJECT_BUCKETS;
1557 if (1 || dev->objectBucket[bucket].count > 0) {
1558 list_for_each(i, &dev->objectBucket[bucket].list) {
1559 /* If there is already one in the list */
1561 && list_entry(i, yaffs_Object,
1562 hashLink)->objectId == n) {
1573 static void yaffs_HashObject(yaffs_Object * in)
1575 int bucket = yaffs_HashFunction(in->objectId);
1576 yaffs_Device *dev = in->myDev;
1578 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1579 dev->objectBucket[bucket].count++;
1583 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1585 int bucket = yaffs_HashFunction(number);
1586 struct list_head *i;
1589 list_for_each(i, &dev->objectBucket[bucket].list) {
1590 /* Look if it is in the list */
1592 in = list_entry(i, yaffs_Object, hashLink);
1593 if (in->objectId == number) {
1595 /* Don't tell the VFS about this one if it is defered free */
1596 if (in->deferedFree)
1608 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1609 yaffs_ObjectType type)
1612 yaffs_Object *theObject;
1615 number = yaffs_CreateNewObjectNumber(dev);
1618 theObject = yaffs_AllocateEmptyObject(dev);
1621 theObject->fake = 0;
1622 theObject->renameAllowed = 1;
1623 theObject->unlinkAllowed = 1;
1624 theObject->objectId = number;
1625 yaffs_HashObject(theObject);
1626 theObject->variantType = type;
1627 #ifdef CONFIG_YAFFS_WINCE
1628 yfsd_WinFileTimeNow(theObject->win_atime);
1629 theObject->win_ctime[0] = theObject->win_mtime[0] =
1630 theObject->win_atime[0];
1631 theObject->win_ctime[1] = theObject->win_mtime[1] =
1632 theObject->win_atime[1];
1636 theObject->yst_atime = theObject->yst_mtime =
1637 theObject->yst_ctime = Y_CURRENT_TIME;
1640 case YAFFS_OBJECT_TYPE_FILE:
1641 theObject->variant.fileVariant.fileSize = 0;
1642 theObject->variant.fileVariant.scannedFileSize = 0;
1643 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1644 theObject->variant.fileVariant.topLevel = 0;
1645 theObject->variant.fileVariant.top =
1646 yaffs_GetTnode(dev);
1648 case YAFFS_OBJECT_TYPE_DIRECTORY:
1649 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1652 case YAFFS_OBJECT_TYPE_SYMLINK:
1653 case YAFFS_OBJECT_TYPE_HARDLINK:
1654 case YAFFS_OBJECT_TYPE_SPECIAL:
1655 /* No action required */
1657 case YAFFS_OBJECT_TYPE_UNKNOWN:
1658 /* todo this should not happen */
1666 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1668 yaffs_ObjectType type)
1670 yaffs_Object *theObject = NULL;
1673 theObject = yaffs_FindObjectByNumber(dev, number);
1677 theObject = yaffs_CreateNewObject(dev, number, type);
1685 static YCHAR *yaffs_CloneString(const YCHAR * str)
1687 YCHAR *newStr = NULL;
1690 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1691 yaffs_strcpy(newStr, str);
1699 * Mknod (create) a new object.
1700 * equivalentObject only has meaning for a hard link;
1701 * aliasString only has meaning for a sumlink.
1702 * rdev only has meaning for devices (a subset of special objects)
1705 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1706 yaffs_Object * parent,
1711 yaffs_Object * equivalentObject,
1712 const YCHAR * aliasString, __u32 rdev)
1716 yaffs_Device *dev = parent->myDev;
1718 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1719 if (yaffs_FindObjectByName(parent, name)) {
1723 in = yaffs_CreateNewObject(dev, -1, type);
1728 in->variantType = type;
1730 in->yst_mode = mode;
1732 #ifdef CONFIG_YAFFS_WINCE
1733 yfsd_WinFileTimeNow(in->win_atime);
1734 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1735 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1738 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1740 in->yst_rdev = rdev;
1744 in->nDataChunks = 0;
1746 yaffs_SetObjectName(in, name);
1749 yaffs_AddObjectToDirectory(parent, in);
1751 in->myDev = parent->myDev;
1754 case YAFFS_OBJECT_TYPE_SYMLINK:
1755 in->variant.symLinkVariant.alias =
1756 yaffs_CloneString(aliasString);
1758 case YAFFS_OBJECT_TYPE_HARDLINK:
1759 in->variant.hardLinkVariant.equivalentObject =
1761 in->variant.hardLinkVariant.equivalentObjectId =
1762 equivalentObject->objectId;
1763 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1765 case YAFFS_OBJECT_TYPE_FILE:
1766 case YAFFS_OBJECT_TYPE_DIRECTORY:
1767 case YAFFS_OBJECT_TYPE_SPECIAL:
1768 case YAFFS_OBJECT_TYPE_UNKNOWN:
1773 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1774 /* Could not create the object header, fail the creation */
1775 yaffs_DestroyObject(in);
1784 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1785 __u32 mode, __u32 uid, __u32 gid)
1787 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1788 uid, gid, NULL, NULL, 0);
1791 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1792 __u32 mode, __u32 uid, __u32 gid)
1794 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1795 mode, uid, gid, NULL, NULL, 0);
1798 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1799 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1801 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1802 uid, gid, NULL, NULL, rdev);
1805 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1806 __u32 mode, __u32 uid, __u32 gid,
1807 const YCHAR * alias)
1809 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1810 uid, gid, NULL, alias, 0);
1813 /* yaffs_Link returns the object id of the equivalent object.*/
1814 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1815 yaffs_Object * equivalentObject)
1817 /* Get the real object in case we were fed a hard link as an equivalent object */
1818 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1820 if (yaffs_MknodObject
1821 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1822 equivalentObject, NULL, 0)) {
1823 return equivalentObject;
1830 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1831 const YCHAR * newName, int force, int shadows)
1836 yaffs_Object *existingTarget;
1838 if (newDir == NULL) {
1839 newDir = obj->parent; /* use the old directory */
1842 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1843 T(YAFFS_TRACE_ALWAYS,
1845 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1850 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1851 if (obj->myDev->isYaffs2) {
1852 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1854 unlinkOp = (newDir == obj->myDev->unlinkedDir
1855 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1858 deleteOp = (newDir == obj->myDev->deletedDir);
1860 existingTarget = yaffs_FindObjectByName(newDir, newName);
1862 /* If the object is a file going into the unlinked directory,
1863 * then it is OK to just stuff it in since duplicate names are allowed.
1864 * else only proceed if the new name does not exist and if we're putting
1865 * it into a directory.
1872 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1873 yaffs_SetObjectName(obj, newName);
1876 yaffs_AddObjectToDirectory(newDir, obj);
1881 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1882 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1889 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1890 yaffs_Object * newDir, const YCHAR * newName)
1893 yaffs_Object *existingTarget;
1896 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1897 /* Special case for case insemsitive systems (eg. WinCE).
1898 * While look-up is case insensitive, the name isn't.
1899 * Therefore we might want to change x.txt to X.txt
1901 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1906 obj = yaffs_FindObjectByName(oldDir, oldName);
1907 /* Check new name to long. */
1908 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1909 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1912 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1913 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1917 if (obj && obj->renameAllowed) {
1919 /* Now do the handling for an existing target, if there is one */
1921 existingTarget = yaffs_FindObjectByName(newDir, newName);
1922 if (existingTarget &&
1923 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1924 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1925 /* There is a target that is a non-empty directory, so we fail */
1926 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1927 } else if (existingTarget && existingTarget != obj) {
1928 /* Nuke the target first, using shadowing,
1929 * but only if it isn't the same object
1931 yaffs_ChangeObjectName(obj, newDir, newName, force,
1932 existingTarget->objectId);
1933 yaffs_UnlinkObject(existingTarget);
1936 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1941 /*------------------------- Block Management and Page Allocation ----------------*/
1943 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1945 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1947 dev->allocationBlock = -1; /* force it to get a new one */
1949 /* Todo we're assuming the malloc will pass. */
1950 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1951 if(!dev->blockInfo){
1952 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1953 dev->blockInfoAlt = 1;
1956 dev->blockInfoAlt = 0;
1958 /* Set up dynamic blockinfo stuff. */
1959 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
1960 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1961 if(!dev->chunkBits){
1962 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1963 dev->chunkBitsAlt = 1;
1966 dev->chunkBitsAlt = 0;
1968 if (dev->blockInfo && dev->chunkBits) {
1969 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1970 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1978 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1980 if(dev->blockInfoAlt)
1981 YFREE_ALT(dev->blockInfo);
1983 YFREE(dev->blockInfo);
1984 dev->blockInfoAlt = 0;
1986 dev->blockInfo = NULL;
1988 if(dev->chunkBitsAlt)
1989 YFREE_ALT(dev->chunkBits);
1991 YFREE(dev->chunkBits);
1992 dev->chunkBitsAlt = 0;
1993 dev->chunkBits = NULL;
1996 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1997 yaffs_BlockInfo * bi)
2004 return 1; /* disqualification only applies to yaffs2. */
2006 if (!bi->hasShrinkHeader)
2007 return 1; /* can gc */
2009 /* Find the oldest dirty sequence number if we don't know it and save it
2010 * so we don't have to keep recomputing it.
2012 if (!dev->oldestDirtySequence) {
2013 seq = dev->sequenceNumber;
2015 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2017 b = yaffs_GetBlockInfo(dev, i);
2018 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2019 (b->pagesInUse - b->softDeletions) <
2020 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2021 seq = b->sequenceNumber;
2024 dev->oldestDirtySequence = seq;
2027 /* Can't do gc of this block if there are any blocks older than this one that have
2030 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2034 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2035 * for garbage collection.
2038 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2042 int b = dev->currentDirtyChecker;
2049 yaffs_BlockInfo *bi;
2050 static int nonAggressiveSkip = 0;
2051 int pendingPrioritisedExist = 0;
2053 /* First let's see if we need to grab a prioritised block */
2054 if(dev->hasPendingPrioritisedGCs){
2055 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2057 bi = yaffs_GetBlockInfo(dev, i);
2058 if(bi->gcPrioritise) {
2059 pendingPrioritisedExist = 1;
2060 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 */
2070 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2071 dev->hasPendingPrioritisedGCs = 0;
2074 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2076 * else (we're doing a leasurely gc), then we only bother to do this if the
2077 * block has only a few pages in use.
2080 nonAggressiveSkip--;
2082 if (!aggressive && (nonAggressiveSkip > 0)) {
2088 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2092 dev->internalEndBlock - dev->internalStartBlock + 1;
2095 dev->internalEndBlock - dev->internalStartBlock + 1;
2096 iterations = iterations / 16;
2097 if (iterations > 200) {
2102 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2104 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2105 b = dev->internalStartBlock;
2108 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2109 T(YAFFS_TRACE_ERROR,
2110 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2114 bi = yaffs_GetBlockInfo(dev, b);
2117 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2124 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2125 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2126 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2128 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2132 dev->currentDirtyChecker = b;
2136 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2137 dev->nChunksPerBlock - pagesInUse,prioritised));
2140 dev->oldestDirtySequence = 0;
2143 nonAggressiveSkip = 4;
2149 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2151 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2155 /* If the block is still healthy erase it and mark as clean.
2156 * If the block has had a data failure, then retire it.
2159 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2160 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2161 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2163 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2165 if (!bi->needsRetiring) {
2166 yaffs_InvalidateCheckpoint(dev);
2167 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2169 dev->nErasureFailures++;
2170 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2171 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2175 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2177 for (i = 0; i < dev->nChunksPerBlock; i++) {
2178 if (!yaffs_CheckChunkErased
2179 (dev, blockNo * dev->nChunksPerBlock + i)) {
2180 T(YAFFS_TRACE_ERROR,
2182 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2183 TENDSTR), blockNo, i));
2189 /* Clean it up... */
2190 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2191 dev->nErasedBlocks++;
2193 bi->softDeletions = 0;
2194 bi->hasShrinkHeader = 0;
2195 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2196 bi->gcPrioritise = 0;
2197 yaffs_ClearChunkBits(dev, blockNo);
2199 T(YAFFS_TRACE_ERASE,
2200 (TSTR("Erased block %d" TENDSTR), blockNo));
2202 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2204 yaffs_RetireBlock(dev, blockNo);
2205 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2206 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2210 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2214 yaffs_BlockInfo *bi;
2216 if (dev->nErasedBlocks < 1) {
2217 /* Hoosterman we've got a problem.
2218 * Can't get space to gc
2220 T(YAFFS_TRACE_ERROR,
2221 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2226 /* Find an empty block. */
2228 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2229 dev->allocationBlockFinder++;
2230 if (dev->allocationBlockFinder < dev->internalStartBlock
2231 || dev->allocationBlockFinder > dev->internalEndBlock) {
2232 dev->allocationBlockFinder = dev->internalStartBlock;
2235 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2237 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2238 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2239 dev->sequenceNumber++;
2240 bi->sequenceNumber = dev->sequenceNumber;
2241 dev->nErasedBlocks--;
2242 T(YAFFS_TRACE_ALLOCATE,
2243 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2244 dev->allocationBlockFinder, dev->sequenceNumber,
2245 dev->nErasedBlocks));
2246 return dev->allocationBlockFinder;
2250 T(YAFFS_TRACE_ALWAYS,
2252 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2253 TENDSTR), dev->nErasedBlocks));
2259 // Check if there's space to allocate...
2260 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2261 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2264 int reservedBlocks = dev->nReservedBlocks;
2265 int checkpointBlocks;
2267 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2268 if(checkpointBlocks < 0)
2269 checkpointBlocks = 0;
2271 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2273 return (dev->nFreeChunks > reservedChunks);
2276 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2279 yaffs_BlockInfo *bi;
2281 if (dev->allocationBlock < 0) {
2282 /* Get next block to allocate off */
2283 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2284 dev->allocationPage = 0;
2287 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2288 /* Not enough space to allocate unless we're allowed to use the reserve. */
2292 if (dev->nErasedBlocks < dev->nReservedBlocks
2293 && dev->allocationPage == 0) {
2294 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2297 /* Next page please.... */
2298 if (dev->allocationBlock >= 0) {
2299 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2301 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2302 dev->allocationPage;
2304 yaffs_SetChunkBit(dev, dev->allocationBlock,
2305 dev->allocationPage);
2307 dev->allocationPage++;
2311 /* If the block is full set the state to full */
2312 if (dev->allocationPage >= dev->nChunksPerBlock) {
2313 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2314 dev->allocationBlock = -1;
2323 T(YAFFS_TRACE_ERROR,
2324 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2329 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2333 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2335 if (dev->allocationBlock > 0) {
2336 n += (dev->nChunksPerBlock - dev->allocationPage);
2343 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2349 int retVal = YAFFS_OK;
2352 int isCheckpointBlock;
2354 int chunksBefore = yaffs_GetErasedChunks(dev);
2357 yaffs_ExtendedTags tags;
2359 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2361 yaffs_Object *object;
2363 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2365 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2367 T(YAFFS_TRACE_TRACING,
2368 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2369 bi->pagesInUse, bi->hasShrinkHeader));
2371 /*yaffs_VerifyFreeChunks(dev); */
2373 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2375 /* Take off the number of soft deleted entries because
2376 * they're going to get really deleted during GC.
2378 dev->nFreeChunks -= bi->softDeletions;
2382 if (isCheckpointBlock ||
2383 !yaffs_StillSomeChunkBits(dev, block)) {
2384 T(YAFFS_TRACE_TRACING,
2386 ("Collecting block %d that has no chunks in use" TENDSTR),
2388 yaffs_BlockBecameDirty(dev, block);
2391 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2393 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2394 chunkInBlock < dev->nChunksPerBlock
2395 && yaffs_StillSomeChunkBits(dev, block);
2396 chunkInBlock++, oldChunk++) {
2397 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2399 /* This page is in use and might need to be copied off */
2403 yaffs_InitialiseTags(&tags);
2405 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2409 yaffs_FindObjectByNumber(dev,
2412 T(YAFFS_TRACE_GC_DETAIL,
2414 ("Collecting page %d, %d %d %d " TENDSTR),
2415 chunkInBlock, tags.objectId, tags.chunkId,
2419 T(YAFFS_TRACE_ERROR,
2421 ("page %d in gc has no object "
2422 TENDSTR), oldChunk));
2425 if (object && object->deleted
2426 && tags.chunkId != 0) {
2427 /* Data chunk in a deleted file, throw it away
2428 * It's a soft deleted data chunk,
2429 * No need to copy this, just forget about it and
2430 * fix up the object.
2433 object->nDataChunks--;
2435 if (object->nDataChunks <= 0) {
2436 /* remeber to clean up the object */
2437 dev->gcCleanupList[cleanups] =
2443 /* Todo object && object->deleted && object->nDataChunks == 0 */
2445 /* Deleted object header with no data chunks.
2446 * Can be discarded and the file deleted.
2448 object->chunkId = 0;
2449 yaffs_FreeTnode(object->myDev,
2452 object->variant.fileVariant.top = NULL;
2453 yaffs_DoGenericObjectDeletion(object);
2455 } else if (object) {
2456 /* It's either a data chunk in a live file or
2457 * an ObjectHeader, so we're interested in it.
2458 * NB Need to keep the ObjectHeaders of deleted files
2459 * until the whole file has been deleted off
2461 tags.serialNumber++;
2465 if (tags.chunkId == 0) {
2466 /* It is an object Id,
2467 * We need to nuke the shrinkheader flags first
2468 * We no longer want the shrinkHeader flag since its work is done
2469 * and if it is left in place it will mess up scanning.
2470 * Also, clear out any shadowing stuff
2473 yaffs_ObjectHeader *oh;
2474 oh = (yaffs_ObjectHeader *)buffer;
2476 oh->shadowsObject = -1;
2477 tags.extraShadows = 0;
2478 tags.extraIsShrinkHeader = 0;
2482 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2485 retVal = YAFFS_FAIL;
2488 /* Ok, now fix up the Tnodes etc. */
2490 if (tags.chunkId == 0) {
2492 object->chunkId = newChunk;
2493 object->serial = tags.serialNumber;
2495 /* It's a data chunk */
2496 yaffs_PutChunkIntoFile
2504 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2509 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2512 /* Do any required cleanups */
2513 for (i = 0; i < cleanups; i++) {
2514 /* Time to delete the file too */
2516 yaffs_FindObjectByNumber(dev,
2517 dev->gcCleanupList[i]);
2519 yaffs_FreeTnode(dev,
2520 object->variant.fileVariant.
2522 object->variant.fileVariant.top = NULL;
2525 ("yaffs: About to finally delete object %d"
2526 TENDSTR), object->objectId));
2527 yaffs_DoGenericObjectDeletion(object);
2528 object->myDev->nDeletedFiles--;
2535 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2538 ("gc did not increase free chunks before %d after %d"
2539 TENDSTR), chunksBefore, chunksAfter));
2547 /* New garbage collector
2548 * If we're very low on erased blocks then we do aggressive garbage collection
2549 * otherwise we do "leasurely" garbage collection.
2550 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2551 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2553 * The idea is to help clear out space in a more spread-out manner.
2554 * Dunno if it really does anything useful.
2556 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2560 int gcOk = YAFFS_OK;
2563 int checkpointBlockAdjust;
2565 if (dev->isDoingGC) {
2566 /* Bail out so we don't get recursive gc */
2570 /* This loop should pass the first time.
2571 * We'll only see looping here if the erase of the collected block fails.
2577 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2578 if(checkpointBlockAdjust < 0)
2579 checkpointBlockAdjust = 0;
2581 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2582 /* We need a block soon...*/
2585 /* We're in no hurry */
2589 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2592 dev->garbageCollections++;
2594 dev->passiveGarbageCollections++;
2599 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2600 dev->nErasedBlocks, aggressive));
2602 gcOk = yaffs_GarbageCollectBlock(dev, block);
2605 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2608 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2609 TENDSTR), dev->nErasedBlocks, maxTries, block));
2611 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2614 return aggressive ? gcOk : YAFFS_OK;
2617 /*------------------------- TAGS --------------------------------*/
2619 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2622 return (tags->chunkId == chunkInObject &&
2623 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2628 /*-------------------- Data file manipulation -----------------*/
2630 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2631 yaffs_ExtendedTags * tags)
2633 /*Get the Tnode, then get the level 0 offset chunk offset */
2636 yaffs_ExtendedTags localTags;
2639 yaffs_Device *dev = in->myDev;
2642 /* Passed a NULL, so use our own tags space */
2646 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2649 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2652 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2658 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2659 yaffs_ExtendedTags * tags)
2661 /* Get the Tnode, then get the level 0 offset chunk offset */
2664 yaffs_ExtendedTags localTags;
2666 yaffs_Device *dev = in->myDev;
2670 /* Passed a NULL, so use our own tags space */
2674 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2678 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2681 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2684 /* Delete the entry in the filestructure (if found) */
2686 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2689 /*T(("No level 0 found for %d\n", chunkInInode)); */
2693 /* T(("Could not find %d to delete\n",chunkInInode)); */
2698 #ifdef YAFFS_PARANOID
2700 static int yaffs_CheckFileSanity(yaffs_Object * in)
2708 yaffs_Tags localTags;
2709 yaffs_Tags *tags = &localTags;
2713 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2714 /* T(("Object not a file\n")); */
2718 objId = in->objectId;
2719 fSize = in->variant.fileVariant.fileSize;
2721 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
2723 for (chunk = 1; chunk <= nChunks; chunk++) {
2724 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2729 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2731 if (yaffs_CheckChunkBits
2732 (dev, theChunk / dev->nChunksPerBlock,
2733 theChunk % dev->nChunksPerBlock)) {
2735 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2739 (tags, in->objectId, chunk, chunkDeleted)) {
2749 /* T(("No level 0 found for %d\n", chunk)); */
2753 return failed ? YAFFS_FAIL : YAFFS_OK;
2758 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2759 int chunkInNAND, int inScan)
2761 /* NB inScan is zero unless scanning.
2762 * For forward scanning, inScan is > 0;
2763 * for backward scanning inScan is < 0
2767 yaffs_Device *dev = in->myDev;
2769 yaffs_ExtendedTags existingTags;
2770 yaffs_ExtendedTags newTags;
2771 unsigned existingSerial, newSerial;
2773 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2774 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2775 * If it is not during Scanning then something went wrong!
2778 T(YAFFS_TRACE_ERROR,
2780 ("yaffs tragedy:attempt to put data chunk into a non-file"
2785 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2789 tn = yaffs_AddOrFindLevel0Tnode(dev,
2790 &in->variant.fileVariant,
2797 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2800 /* If we're scanning then we need to test for duplicates
2801 * NB This does not need to be efficient since it should only ever
2802 * happen when the power fails during a write, then only one
2803 * chunk should ever be affected.
2805 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2806 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2809 if (existingChunk != 0) {
2810 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2811 * thus we have to do a FindChunkInFile to get the real chunk id.
2813 * We have a duplicate now we need to decide which one to use:
2815 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2816 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2817 * YAFFS1: Get both sets of tags and compare serial numbers.
2821 /* Only do this for forward scanning */
2822 yaffs_ReadChunkWithTagsFromNAND(dev,
2826 /* Do a proper find */
2828 yaffs_FindChunkInFile(in, chunkInInode,
2832 if (existingChunk <= 0) {
2833 /*Hoosterman - how did this happen? */
2835 T(YAFFS_TRACE_ERROR,
2837 ("yaffs tragedy: existing chunk < 0 in scan"
2842 /* NB The deleted flags should be false, otherwise the chunks will
2843 * not be loaded during a scan
2846 newSerial = newTags.serialNumber;
2847 existingSerial = existingTags.serialNumber;
2850 (in->myDev->isYaffs2 ||
2851 existingChunk <= 0 ||
2852 ((existingSerial + 1) & 3) == newSerial)) {
2853 /* Forward scanning.
2855 * Delete the old one and drop through to update the tnode
2857 yaffs_DeleteChunk(dev, existingChunk, 1,
2860 /* Backward scanning or we want to use the existing one
2862 * Delete the new one and return early so that the tnode isn't changed
2864 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2872 if (existingChunk == 0) {
2876 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2881 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2884 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2886 if (chunkInNAND >= 0) {
2887 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2890 T(YAFFS_TRACE_NANDACCESS,
2891 (TSTR("Chunk %d not found zero instead" TENDSTR),
2893 /* get sane (zero) data if you read a hole */
2894 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2900 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2904 yaffs_ExtendedTags tags;
2905 yaffs_BlockInfo *bi;
2911 block = chunkId / dev->nChunksPerBlock;
2912 page = chunkId % dev->nChunksPerBlock;
2914 bi = yaffs_GetBlockInfo(dev, block);
2916 T(YAFFS_TRACE_DELETION,
2917 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2920 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2922 yaffs_InitialiseTags(&tags);
2924 tags.chunkDeleted = 1;
2926 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2927 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2929 dev->nUnmarkedDeletions++;
2932 /* Pull out of the management area.
2933 * If the whole block became dirty, this will kick off an erasure.
2935 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2936 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2937 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2938 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2941 yaffs_ClearChunkBit(dev, block, page);
2945 if (bi->pagesInUse == 0 &&
2946 !bi->hasShrinkHeader &&
2947 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2948 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2949 yaffs_BlockBecameDirty(dev, block);
2953 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2958 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2959 const __u8 * buffer, int nBytes,
2962 /* Find old chunk Need to do this to get serial number
2963 * Write new one and patch into tree.
2964 * Invalidate old tags.
2968 yaffs_ExtendedTags prevTags;
2971 yaffs_ExtendedTags newTags;
2973 yaffs_Device *dev = in->myDev;
2975 yaffs_CheckGarbageCollection(dev);
2977 /* Get the previous chunk at this location in the file if it exists */
2978 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2980 /* Set up new tags */
2981 yaffs_InitialiseTags(&newTags);
2983 newTags.chunkId = chunkInInode;
2984 newTags.objectId = in->objectId;
2985 newTags.serialNumber =
2986 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2987 newTags.byteCount = nBytes;
2990 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2993 if (newChunkId >= 0) {
2994 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2996 if (prevChunkId >= 0) {
2997 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3001 yaffs_CheckFileSanity(in);
3007 /* UpdateObjectHeader updates the header on NAND for an object.
3008 * If name is not NULL, then that new name is used.
3010 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3011 int isShrink, int shadows)
3014 yaffs_BlockInfo *bi;
3016 yaffs_Device *dev = in->myDev;
3023 yaffs_ExtendedTags newTags;
3025 __u8 *buffer = NULL;
3026 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3028 yaffs_ObjectHeader *oh = NULL;
3030 if (!in->fake || force) {
3032 yaffs_CheckGarbageCollection(dev);
3034 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3035 oh = (yaffs_ObjectHeader *) buffer;
3037 prevChunkId = in->chunkId;
3039 if (prevChunkId >= 0) {
3040 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3042 memcpy(oldName, oh->name, sizeof(oh->name));
3045 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3047 oh->type = in->variantType;
3048 oh->yst_mode = in->yst_mode;
3049 oh->shadowsObject = shadows;
3051 #ifdef CONFIG_YAFFS_WINCE
3052 oh->win_atime[0] = in->win_atime[0];
3053 oh->win_ctime[0] = in->win_ctime[0];
3054 oh->win_mtime[0] = in->win_mtime[0];
3055 oh->win_atime[1] = in->win_atime[1];
3056 oh->win_ctime[1] = in->win_ctime[1];
3057 oh->win_mtime[1] = in->win_mtime[1];
3059 oh->yst_uid = in->yst_uid;
3060 oh->yst_gid = in->yst_gid;
3061 oh->yst_atime = in->yst_atime;
3062 oh->yst_mtime = in->yst_mtime;
3063 oh->yst_ctime = in->yst_ctime;
3064 oh->yst_rdev = in->yst_rdev;
3067 oh->parentObjectId = in->parent->objectId;
3069 oh->parentObjectId = 0;
3072 if (name && *name) {
3073 memset(oh->name, 0, sizeof(oh->name));
3074 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3075 } else if (prevChunkId) {
3076 memcpy(oh->name, oldName, sizeof(oh->name));
3078 memset(oh->name, 0, sizeof(oh->name));
3081 oh->isShrink = isShrink;
3083 switch (in->variantType) {
3084 case YAFFS_OBJECT_TYPE_UNKNOWN:
3085 /* Should not happen */
3087 case YAFFS_OBJECT_TYPE_FILE:
3089 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3090 || oh->parentObjectId ==
3091 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3092 fileVariant.fileSize;
3094 case YAFFS_OBJECT_TYPE_HARDLINK:
3095 oh->equivalentObjectId =
3096 in->variant.hardLinkVariant.equivalentObjectId;
3098 case YAFFS_OBJECT_TYPE_SPECIAL:
3101 case YAFFS_OBJECT_TYPE_DIRECTORY:
3104 case YAFFS_OBJECT_TYPE_SYMLINK:
3105 yaffs_strncpy(oh->alias,
3106 in->variant.symLinkVariant.alias,
3107 YAFFS_MAX_ALIAS_LENGTH);
3108 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3113 yaffs_InitialiseTags(&newTags);
3115 newTags.chunkId = 0;
3116 newTags.objectId = in->objectId;
3117 newTags.serialNumber = in->serial;
3119 /* Add extra info for file header */
3121 newTags.extraHeaderInfoAvailable = 1;
3122 newTags.extraParentObjectId = oh->parentObjectId;
3123 newTags.extraFileLength = oh->fileSize;
3124 newTags.extraIsShrinkHeader = oh->isShrink;
3125 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3126 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3127 newTags.extraObjectType = in->variantType;
3129 /* Create new chunk in NAND */
3131 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3132 (prevChunkId >= 0) ? 1 : 0);
3134 if (newChunkId >= 0) {
3136 in->chunkId = newChunkId;
3138 if (prevChunkId >= 0) {
3139 yaffs_DeleteChunk(dev, prevChunkId, 1,
3143 if(!yaffs_ObjectHasCachedWriteData(in))
3146 /* If this was a shrink, then mark the block that the chunk lives on */
3148 bi = yaffs_GetBlockInfo(in->myDev,
3149 newChunkId /in->myDev-> nChunksPerBlock);
3150 bi->hasShrinkHeader = 1;
3155 retVal = newChunkId;
3160 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3165 /*------------------------ Short Operations Cache ----------------------------------------
3166 * In many situations where there is no high level buffering (eg WinCE) a lot of
3167 * reads might be short sequential reads, and a lot of writes may be short
3168 * sequential writes. eg. scanning/writing a jpeg file.
3169 * In these cases, a short read/write cache can provide a huge perfomance benefit
3170 * with dumb-as-a-rock code.
3171 * In Linux, the page cache provides read buffering aand the short op cache provides write
3174 * There are a limited number (~10) of cache chunks per device so that we don't
3175 * need a very intelligent search.
3178 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3180 yaffs_Device *dev = obj->myDev;
3182 yaffs_ChunkCache *cache;
3183 int nCaches = obj->myDev->nShortOpCaches;
3185 for(i = 0; i < nCaches; i++){
3186 cache = &dev->srCache[i];
3187 if (cache->object == obj &&
3196 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3198 yaffs_Device *dev = obj->myDev;
3199 int lowest = -99; /* Stop compiler whining. */
3201 yaffs_ChunkCache *cache;
3202 int chunkWritten = 0;
3203 int nCaches = obj->myDev->nShortOpCaches;
3209 /* Find the dirty cache for this object with the lowest chunk id. */
3210 for (i = 0; i < nCaches; i++) {
3211 if (dev->srCache[i].object == obj &&
3212 dev->srCache[i].dirty) {
3214 || dev->srCache[i].chunkId <
3216 cache = &dev->srCache[i];
3217 lowest = cache->chunkId;
3222 if (cache && !cache->locked) {
3223 /* Write it out and free it up */
3226 yaffs_WriteChunkDataToObject(cache->object,
3232 cache->object = NULL;
3235 } while (cache && chunkWritten > 0);
3238 /* Hoosterman, disk full while writing cache out. */
3239 T(YAFFS_TRACE_ERROR,
3240 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3247 /*yaffs_FlushEntireDeviceCache(dev)
3252 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3255 int nCaches = dev->nShortOpCaches;
3258 /* Find a dirty object in the cache and flush it...
3259 * until there are no further dirty objects.
3263 for( i = 0; i < nCaches && !obj; i++) {
3264 if (dev->srCache[i].object &&
3265 dev->srCache[i].dirty)
3266 obj = dev->srCache[i].object;
3270 yaffs_FlushFilesChunkCache(obj);
3277 /* Grab us a cache chunk for use.
3278 * First look for an empty one.
3279 * Then look for the least recently used non-dirty one.
3280 * Then look for the least recently used dirty one...., flush and look again.
3282 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3288 if (dev->nShortOpCaches > 0) {
3289 for (i = 0; i < dev->nShortOpCaches; i++) {
3290 if (!dev->srCache[i].object)
3291 return &dev->srCache[i];
3297 usage = 0; /* just to stop the compiler grizzling */
3299 for (i = 0; i < dev->nShortOpCaches; i++) {
3300 if (!dev->srCache[i].dirty &&
3301 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3303 usage = dev->srCache[i].lastUse;
3309 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3316 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3318 yaffs_ChunkCache *cache;
3319 yaffs_Object *theObj;
3324 if (dev->nShortOpCaches > 0) {
3325 /* Try find a non-dirty one... */
3327 cache = yaffs_GrabChunkCacheWorker(dev);
3330 /* They were all dirty, find the last recently used object and flush
3331 * its cache, then find again.
3332 * NB what's here is not very accurate, we actually flush the object
3333 * the last recently used page.
3336 /* With locking we can't assume we can use entry zero */
3343 for (i = 0; i < dev->nShortOpCaches; i++) {
3344 if (dev->srCache[i].object &&
3345 !dev->srCache[i].locked &&
3346 (dev->srCache[i].lastUse < usage || !cache))
3348 usage = dev->srCache[i].lastUse;
3349 theObj = dev->srCache[i].object;
3350 cache = &dev->srCache[i];
3355 if (!cache || cache->dirty) {
3356 /* Flush and try again */
3357 yaffs_FlushFilesChunkCache(theObj);
3358 cache = yaffs_GrabChunkCacheWorker(dev);
3368 /* Find a cached chunk */
3369 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3372 yaffs_Device *dev = obj->myDev;
3374 if (dev->nShortOpCaches > 0) {
3375 for (i = 0; i < dev->nShortOpCaches; i++) {
3376 if (dev->srCache[i].object == obj &&
3377 dev->srCache[i].chunkId == chunkId) {
3380 return &dev->srCache[i];
3387 /* Mark the chunk for the least recently used algorithym */
3388 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3392 if (dev->nShortOpCaches > 0) {
3393 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3394 /* Reset the cache usages */
3396 for (i = 1; i < dev->nShortOpCaches; i++) {
3397 dev->srCache[i].lastUse = 0;
3404 cache->lastUse = dev->srLastUse;
3412 /* Invalidate a single cache page.
3413 * Do this when a whole page gets written,
3414 * ie the short cache for this page is no longer valid.
3416 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3418 if (object->myDev->nShortOpCaches > 0) {
3419 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3422 cache->object = NULL;
3427 /* Invalidate all the cache pages associated with this object
3428 * Do this whenever ther file is deleted or resized.
3430 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3433 yaffs_Device *dev = in->myDev;
3435 if (dev->nShortOpCaches > 0) {
3436 /* Invalidate it. */
3437 for (i = 0; i < dev->nShortOpCaches; i++) {
3438 if (dev->srCache[i].object == in) {
3439 dev->srCache[i].object = NULL;
3445 /*--------------------- Checkpointing --------------------*/
3448 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3450 yaffs_CheckpointValidity cp;
3451 cp.structType = sizeof(cp);
3452 cp.magic = YAFFS_MAGIC;
3453 cp.version = YAFFS_CHECKPOINT_VERSION;
3454 cp.head = (head) ? 1 : 0;
3456 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3460 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3462 yaffs_CheckpointValidity cp;
3465 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3468 ok = (cp.structType == sizeof(cp)) &&
3469 (cp.magic == YAFFS_MAGIC) &&
3470 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
3471 (cp.head == ((head) ? 1 : 0));
3475 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3478 cp->nErasedBlocks = dev->nErasedBlocks;
3479 cp->allocationBlock = dev->allocationBlock;
3480 cp->allocationPage = dev->allocationPage;
3481 cp->nFreeChunks = dev->nFreeChunks;
3483 cp->nDeletedFiles = dev->nDeletedFiles;
3484 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3485 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3486 cp->sequenceNumber = dev->sequenceNumber;
3487 cp->oldestDirtySequence = dev->oldestDirtySequence;
3491 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3492 yaffs_CheckpointDevice *cp)
3494 dev->nErasedBlocks = cp->nErasedBlocks;
3495 dev->allocationBlock = cp->allocationBlock;
3496 dev->allocationPage = cp->allocationPage;
3497 dev->nFreeChunks = cp->nFreeChunks;
3499 dev->nDeletedFiles = cp->nDeletedFiles;
3500 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3501 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3502 dev->sequenceNumber = cp->sequenceNumber;
3503 dev->oldestDirtySequence = cp->oldestDirtySequence;
3507 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3509 yaffs_CheckpointDevice cp;
3511 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3515 /* Write device runtime values*/
3516 yaffs_DeviceToCheckpointDevice(&cp,dev);
3517 cp.structType = sizeof(cp);
3519 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3521 /* Write block info */
3523 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3524 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3527 /* Write chunk bits */
3529 nBytes = nBlocks * dev->chunkBitmapStride;
3530 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3536 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3538 yaffs_CheckpointDevice cp;
3540 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3544 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3548 if(cp.structType != sizeof(cp))
3552 yaffs_CheckpointDeviceToDevice(dev,&cp);
3554 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3556 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3560 nBytes = nBlocks * dev->chunkBitmapStride;
3562 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3567 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3571 cp->objectId = obj->objectId;
3572 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3573 cp->chunkId = obj->chunkId;
3574 cp->variantType = obj->variantType;
3575 cp->deleted = obj->deleted;
3576 cp->softDeleted = obj->softDeleted;
3577 cp->unlinked = obj->unlinked;
3578 cp->fake = obj->fake;
3579 cp->renameAllowed = obj->renameAllowed;
3580 cp->unlinkAllowed = obj->unlinkAllowed;
3581 cp->serial = obj->serial;
3582 cp->nDataChunks = obj->nDataChunks;
3584 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3585 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3586 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3587 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3590 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3593 yaffs_Object *parent;
3595 obj->objectId = cp->objectId;
3598 parent = yaffs_FindOrCreateObjectByNumber(
3601 YAFFS_OBJECT_TYPE_DIRECTORY);
3606 yaffs_AddObjectToDirectory(parent, obj);
3608 obj->chunkId = cp->chunkId;
3609 obj->variantType = cp->variantType;
3610 obj->deleted = cp->deleted;
3611 obj->softDeleted = cp->softDeleted;
3612 obj->unlinked = cp->unlinked;
3613 obj->fake = cp->fake;
3614 obj->renameAllowed = cp->renameAllowed;
3615 obj->unlinkAllowed = cp->unlinkAllowed;
3616 obj->serial = cp->serial;
3617 obj->nDataChunks = cp->nDataChunks;
3619 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3620 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3621 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3622 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3624 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3625 obj->lazyLoaded = 1;
3630 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3631 __u32 level, int chunkOffset)
3634 yaffs_Device *dev = in->myDev;
3636 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3641 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3642 if (tn->internal[i]) {
3643 ok = yaffs_CheckpointTnodeWorker(in,
3646 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3649 } else if (level == 0) {
3650 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3651 /* printf("write tnode at %d\n",baseOffset); */
3652 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3654 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3662 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3664 __u32 endMarker = ~0;
3667 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3668 ok = yaffs_CheckpointTnodeWorker(obj,
3669 obj->variant.fileVariant.top,
3670 obj->variant.fileVariant.topLevel,
3673 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3680 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3684 yaffs_Device *dev = obj->myDev;
3685 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3688 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3690 while(ok && (~baseChunk)){
3691 /* Read level 0 tnode */
3693 /* printf("read tnode at %d\n",baseChunk); */
3694 tn = yaffs_GetTnodeRaw(dev);
3696 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3697 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3702 ok = yaffs_AddOrFindLevel0Tnode(dev,
3709 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3717 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3720 yaffs_CheckpointObject cp;
3723 struct list_head *lh;
3726 /* Iterate through the objects in each hash entry,
3727 * dumping them to the checkpointing stream.
3730 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3731 list_for_each(lh, &dev->objectBucket[i].list) {
3733 obj = list_entry(lh, yaffs_Object, hashLink);
3734 if (!obj->deferedFree) {
3735 yaffs_ObjectToCheckpointObject(&cp,obj);
3736 cp.structType = sizeof(cp);
3738 T(YAFFS_TRACE_CHECKPOINT,(
3739 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3740 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3742 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3744 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3745 ok = yaffs_WriteCheckpointTnodes(obj);
3752 /* Dump end of list */
3753 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3754 cp.structType = sizeof(cp);
3757 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3762 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3765 yaffs_CheckpointObject cp;
3768 yaffs_Object *hardList = NULL;
3770 while(ok && !done) {
3771 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3772 if(cp.structType != sizeof(cp)) {
3773 /* printf("structure parsing failed\n"); */
3777 if(ok && cp.objectId == ~0)
3780 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3781 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3782 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3784 yaffs_CheckpointObjectToObject(obj,&cp);
3785 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3786 ok = yaffs_ReadCheckpointTnodes(obj);
3787 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3788 obj->hardLinks.next =
3789 (struct list_head *)
3799 yaffs_HardlinkFixup(dev,hardList);
3804 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3809 ok = yaffs_CheckpointOpen(dev,1);
3812 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3814 ok = yaffs_WriteCheckpointDevice(dev);
3816 ok = yaffs_WriteCheckpointObjects(dev);
3818 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3820 if(!yaffs_CheckpointClose(dev))
3824 dev->isCheckpointed = 1;
3826 dev->isCheckpointed = 0;
3828 return dev->isCheckpointed;
3831 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3835 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3838 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3840 ok = yaffs_ReadCheckpointDevice(dev);
3842 ok = yaffs_ReadCheckpointObjects(dev);
3844 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3848 if(!yaffs_CheckpointClose(dev))
3852 dev->isCheckpointed = 1;
3854 dev->isCheckpointed = 0;
3860 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3862 if(dev->isCheckpointed ||
3863 dev->blocksInCheckpoint > 0){
3864 dev->isCheckpointed = 0;
3865 yaffs_CheckpointInvalidateStream(dev);
3866 if(dev->superBlock && dev->markSuperBlockDirty)
3867 dev->markSuperBlockDirty(dev->superBlock);
3872 int yaffs_CheckpointSave(yaffs_Device *dev)
3874 yaffs_ReportOddballBlocks(dev);
3875 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3877 if(!dev->isCheckpointed)
3878 yaffs_WriteCheckpointData(dev);
3880 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3882 return dev->isCheckpointed;
3885 int yaffs_CheckpointRestore(yaffs_Device *dev)
3888 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3890 retval = yaffs_ReadCheckpointData(dev);
3892 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3894 yaffs_ReportOddballBlocks(dev);
3899 /*--------------------- File read/write ------------------------
3900 * Read and write have very similar structures.
3901 * In general the read/write has three parts to it
3902 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3903 * Some complete chunks
3904 * An incomplete chunk to end off with
3906 * Curve-balls: the first chunk might also be the last chunk.
3909 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
3918 yaffs_ChunkCache *cache;
3925 //chunk = offset / dev->nDataBytesPerChunk + 1;
3926 //start = offset % dev->nDataBytesPerChunk;
3927 yaffs_AddrToChunk(dev,offset,&chunk,&start);
3930 /* OK now check for the curveball where the start and end are in
3933 if ((start + n) < dev->nDataBytesPerChunk) {
3936 nToCopy = dev->nDataBytesPerChunk - start;
3939 cache = yaffs_FindChunkCache(in, chunk);
3941 /* If the chunk is already in the cache or it is less than a whole chunk
3942 * then use the cache (if there is caching)
3943 * else bypass the cache.
3945 if (cache || nToCopy != dev->nDataBytesPerChunk) {
3946 if (dev->nShortOpCaches > 0) {
3948 /* If we can't find the data in the cache, then load it up. */
3951 cache = yaffs_GrabChunkCache(in->myDev);
3953 cache->chunkId = chunk;
3956 yaffs_ReadChunkDataFromObject(in, chunk,
3962 yaffs_UseChunkCache(dev, cache, 0);
3966 #ifdef CONFIG_YAFFS_WINCE
3967 yfsd_UnlockYAFFS(TRUE);
3969 memcpy(buffer, &cache->data[start], nToCopy);
3971 #ifdef CONFIG_YAFFS_WINCE
3972 yfsd_LockYAFFS(TRUE);
3976 /* Read into the local buffer then copy..*/
3979 yaffs_GetTempBuffer(dev, __LINE__);
3980 yaffs_ReadChunkDataFromObject(in, chunk,
3982 #ifdef CONFIG_YAFFS_WINCE
3983 yfsd_UnlockYAFFS(TRUE);
3985 memcpy(buffer, &localBuffer[start], nToCopy);
3987 #ifdef CONFIG_YAFFS_WINCE
3988 yfsd_LockYAFFS(TRUE);
3990 yaffs_ReleaseTempBuffer(dev, localBuffer,
3995 #ifdef CONFIG_YAFFS_WINCE
3996 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3998 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3999 * This is because we otherwise screw up WinCE's memory mapper
4001 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4003 #ifdef CONFIG_YAFFS_WINCE
4004 yfsd_UnlockYAFFS(TRUE);
4006 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4008 #ifdef CONFIG_YAFFS_WINCE
4009 yfsd_LockYAFFS(TRUE);
4010 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4014 /* A full chunk. Read directly into the supplied buffer. */
4015 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4029 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4030 int nBytes, int writeThrough)
4039 int startOfWrite = offset;
4040 int chunkWritten = 0;
4047 while (n > 0 && chunkWritten >= 0) {
4048 //chunk = offset / dev->nDataBytesPerChunk + 1;
4049 //start = offset % dev->nDataBytesPerChunk;
4050 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4053 /* OK now check for the curveball where the start and end are in
4057 if ((start + n) < dev->nDataBytesPerChunk) {
4060 /* Now folks, to calculate how many bytes to write back....
4061 * If we're overwriting and not writing to then end of file then
4062 * we need to write back as much as was there before.
4066 in->variant.fileVariant.fileSize -
4067 ((chunk - 1) * dev->nDataBytesPerChunk);
4069 if (nBytesRead > dev->nDataBytesPerChunk) {
4070 nBytesRead = dev->nDataBytesPerChunk;
4075 (start + n)) ? nBytesRead : (start + n);
4078 nToCopy = dev->nDataBytesPerChunk - start;
4079 nToWriteBack = dev->nDataBytesPerChunk;
4082 if (nToCopy != dev->nDataBytesPerChunk) {
4083 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4084 if (dev->nShortOpCaches > 0) {
4085 yaffs_ChunkCache *cache;
4086 /* If we can't find the data in the cache, then load the cache */
4087 cache = yaffs_FindChunkCache(in, chunk);
4090 && yaffs_CheckSpaceForAllocation(in->
4092 cache = yaffs_GrabChunkCache(in->myDev);
4094 cache->chunkId = chunk;
4097 yaffs_ReadChunkDataFromObject(in, chunk,
4103 !yaffs_CheckSpaceForAllocation(in->myDev)){
4104 /* Drop the cache if it was a read cache item and
4105 * no space check has been made for it.
4111 yaffs_UseChunkCache(dev, cache, 1);
4113 #ifdef CONFIG_YAFFS_WINCE
4114 yfsd_UnlockYAFFS(TRUE);
4117 memcpy(&cache->data[start], buffer,
4120 #ifdef CONFIG_YAFFS_WINCE
4121 yfsd_LockYAFFS(TRUE);
4124 cache->nBytes = nToWriteBack;
4128 yaffs_WriteChunkDataToObject
4131 cache->data, cache->nBytes,
4137 chunkWritten = -1; /* fail the write */
4140 /* An incomplete start or end chunk (or maybe both start and end chunk)
4141 * Read into the local buffer then copy, then copy over and write back.
4145 yaffs_GetTempBuffer(dev, __LINE__);
4147 yaffs_ReadChunkDataFromObject(in, chunk,
4150 #ifdef CONFIG_YAFFS_WINCE
4151 yfsd_UnlockYAFFS(TRUE);
4154 memcpy(&localBuffer[start], buffer, nToCopy);
4156 #ifdef CONFIG_YAFFS_WINCE
4157 yfsd_LockYAFFS(TRUE);
4160 yaffs_WriteChunkDataToObject(in, chunk,
4165 yaffs_ReleaseTempBuffer(dev, localBuffer,
4172 #ifdef CONFIG_YAFFS_WINCE
4173 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4174 * This is because we otherwise screw up WinCE's memory mapper
4176 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4177 #ifdef CONFIG_YAFFS_WINCE
4178 yfsd_UnlockYAFFS(TRUE);
4180 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4181 #ifdef CONFIG_YAFFS_WINCE
4182 yfsd_LockYAFFS(TRUE);
4185 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4186 dev->nDataBytesPerChunk,
4188 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4190 /* A full chunk. Write directly from the supplied buffer. */
4192 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4193 dev->nDataBytesPerChunk,
4196 /* Since we've overwritten the cached data, we better invalidate it. */
4197 yaffs_InvalidateChunkCache(in, chunk);
4200 if (chunkWritten >= 0) {
4209 /* Update file object */
4211 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4212 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4221 /* ---------------------- File resizing stuff ------------------ */
4223 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4226 yaffs_Device *dev = in->myDev;
4227 int oldFileSize = in->variant.fileVariant.fileSize;
4229 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4231 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4232 dev->nDataBytesPerChunk;
4236 /* Delete backwards so that we don't end up with holes if
4237 * power is lost part-way through the operation.
4239 for (i = lastDel; i >= startDel; i--) {
4240 /* NB this could be optimised somewhat,
4241 * eg. could retrieve the tags and write them without
4242 * using yaffs_DeleteChunk
4245 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4248 (dev->internalStartBlock * dev->nChunksPerBlock)
4250 ((dev->internalEndBlock +
4251 1) * dev->nChunksPerBlock)) {
4252 T(YAFFS_TRACE_ALWAYS,
4253 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4257 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4264 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4267 int oldFileSize = in->variant.fileVariant.fileSize;
4268 int newSizeOfPartialChunk;
4271 yaffs_Device *dev = in->myDev;
4273 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4275 yaffs_FlushFilesChunkCache(in);
4276 yaffs_InvalidateWholeChunkCache(in);
4278 yaffs_CheckGarbageCollection(dev);
4280 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4281 return yaffs_GetFileSize(in);
4284 if (newSize == oldFileSize) {
4288 if (newSize < oldFileSize) {
4290 yaffs_PruneResizedChunks(in, newSize);
4292 if (newSizeOfPartialChunk != 0) {
4293 int lastChunk = 1 + newFullChunks;
4295 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4297 /* Got to read and rewrite the last chunk with its new size and zero pad */
4298 yaffs_ReadChunkDataFromObject(in, lastChunk,
4301 memset(localBuffer + newSizeOfPartialChunk, 0,
4302 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4304 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4305 newSizeOfPartialChunk, 1);
4307 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4310 in->variant.fileVariant.fileSize = newSize;
4312 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4314 /* Write a new object header.
4315 * show we've shrunk the file, if need be
4316 * Do this only if the file is not in the deleted directories.
4318 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4319 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4320 yaffs_UpdateObjectHeader(in, NULL, 0,
4321 (newSize < oldFileSize) ? 1 : 0, 0);
4327 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4329 obj = yaffs_GetEquivalentObject(obj);
4331 switch (obj->variantType) {
4332 case YAFFS_OBJECT_TYPE_FILE:
4333 return obj->variant.fileVariant.fileSize;
4334 case YAFFS_OBJECT_TYPE_SYMLINK:
4335 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4343 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4347 yaffs_FlushFilesChunkCache(in);
4349 #ifdef CONFIG_YAFFS_WINCE
4350 yfsd_WinFileTimeNow(in->win_mtime);
4353 in->yst_mtime = Y_CURRENT_TIME;
4359 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4360 0) ? YAFFS_OK : YAFFS_FAIL;
4369 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4372 /* First off, invalidate the file's data in the cache, without flushing. */
4373 yaffs_InvalidateWholeChunkCache(in);
4375 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4376 /* Move to the unlinked directory so we have a record that it was deleted. */
4377 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4381 yaffs_RemoveObjectFromDirectory(in);
4382 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4385 yaffs_FreeObject(in);
4390 /* yaffs_DeleteFile deletes the whole file data
4391 * and the inode associated with the file.
4392 * It does not delete the links associated with the file.
4394 static int yaffs_UnlinkFile(yaffs_Object * in)
4398 int immediateDeletion = 0;
4403 immediateDeletion = 1;
4407 if (in->inUse <= 0) {
4408 immediateDeletion = 1;
4412 if (immediateDeletion) {
4414 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4416 T(YAFFS_TRACE_TRACING,
4417 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4420 in->myDev->nDeletedFiles++;
4421 if (0 && in->myDev->isYaffs2) {
4422 yaffs_ResizeFile(in, 0);
4424 yaffs_SoftDeleteFile(in);
4427 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4435 int yaffs_DeleteFile(yaffs_Object * in)
4437 int retVal = YAFFS_OK;
4439 if (in->nDataChunks > 0) {
4440 /* Use soft deletion if there is data in the file */
4441 if (!in->unlinked) {
4442 retVal = yaffs_UnlinkFile(in);
4444 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4446 in->myDev->nDeletedFiles++;
4447 yaffs_SoftDeleteFile(in);
4449 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4451 /* The file has no data chunks so we toss it immediately */
4452 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4453 in->variant.fileVariant.top = NULL;
4454 yaffs_DoGenericObjectDeletion(in);
4460 static int yaffs_DeleteDirectory(yaffs_Object * in)
4462 /* First check that the directory is empty. */
4463 if (list_empty(&in->variant.directoryVariant.children)) {
4464 return yaffs_DoGenericObjectDeletion(in);
4471 static int yaffs_DeleteSymLink(yaffs_Object * in)
4473 YFREE(in->variant.symLinkVariant.alias);
4475 return yaffs_DoGenericObjectDeletion(in);
4478 static int yaffs_DeleteHardLink(yaffs_Object * in)
4480 /* remove this hardlink from the list assocaited with the equivalent
4483 list_del(&in->hardLinks);
4484 return yaffs_DoGenericObjectDeletion(in);
4487 static void yaffs_DestroyObject(yaffs_Object * obj)
4489 switch (obj->variantType) {
4490 case YAFFS_OBJECT_TYPE_FILE:
4491 yaffs_DeleteFile(obj);
4493 case YAFFS_OBJECT_TYPE_DIRECTORY:
4494 yaffs_DeleteDirectory(obj);
4496 case YAFFS_OBJECT_TYPE_SYMLINK:
4497 yaffs_DeleteSymLink(obj);
4499 case YAFFS_OBJECT_TYPE_HARDLINK:
4500 yaffs_DeleteHardLink(obj);
4502 case YAFFS_OBJECT_TYPE_SPECIAL:
4503 yaffs_DoGenericObjectDeletion(obj);
4505 case YAFFS_OBJECT_TYPE_UNKNOWN:
4506 break; /* should not happen. */
4510 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4513 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4514 return yaffs_DeleteHardLink(obj);
4515 } else if (!list_empty(&obj->hardLinks)) {
4516 /* Curve ball: We're unlinking an object that has a hardlink.
4518 * This problem arises because we are not strictly following
4519 * The Linux link/inode model.
4521 * We can't really delete the object.
4522 * Instead, we do the following:
4523 * - Select a hardlink.
4524 * - Unhook it from the hard links
4525 * - Unhook it from its parent directory (so that the rename can work)
4526 * - Rename the object to the hardlink's name.
4527 * - Delete the hardlink
4532 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4534 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4536 list_del_init(&hl->hardLinks);
4537 list_del_init(&hl->siblings);
4539 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4541 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4543 if (retVal == YAFFS_OK) {
4544 retVal = yaffs_DoGenericObjectDeletion(hl);
4549 switch (obj->variantType) {
4550 case YAFFS_OBJECT_TYPE_FILE:
4551 return yaffs_UnlinkFile(obj);
4553 case YAFFS_OBJECT_TYPE_DIRECTORY:
4554 return yaffs_DeleteDirectory(obj);
4556 case YAFFS_OBJECT_TYPE_SYMLINK:
4557 return yaffs_DeleteSymLink(obj);
4559 case YAFFS_OBJECT_TYPE_SPECIAL:
4560 return yaffs_DoGenericObjectDeletion(obj);
4562 case YAFFS_OBJECT_TYPE_HARDLINK:
4563 case YAFFS_OBJECT_TYPE_UNKNOWN:
4571 static int yaffs_UnlinkObject( yaffs_Object *obj)
4574 if (obj && obj->unlinkAllowed) {
4575 return yaffs_UnlinkWorker(obj);
4581 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4585 obj = yaffs_FindObjectByName(dir, name);
4586 return yaffs_UnlinkObject(obj);
4589 /*----------------------- Initialisation Scanning ---------------------- */
4591 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4592 int backwardScanning)
4596 if (!backwardScanning) {
4597 /* Handle YAFFS1 forward scanning case
4598 * For YAFFS1 we always do the deletion
4602 /* Handle YAFFS2 case (backward scanning)
4603 * If the shadowed object exists then ignore.
4605 if (yaffs_FindObjectByNumber(dev, objId)) {
4610 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4611 * We put it in unlinked dir to be cleaned up after the scanning
4614 yaffs_FindOrCreateObjectByNumber(dev, objId,
4615 YAFFS_OBJECT_TYPE_FILE);
4616 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4617 obj->variant.fileVariant.shrinkSize = 0;
4618 obj->valid = 1; /* So that we don't read any other info for this file */
4628 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4635 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4637 in = yaffs_FindObjectByNumber(dev,
4638 hl->variant.hardLinkVariant.
4639 equivalentObjectId);
4642 /* Add the hardlink pointers */
4643 hl->variant.hardLinkVariant.equivalentObject = in;
4644 list_add(&hl->hardLinks, &in->hardLinks);
4646 /* Todo Need to report/handle this better.
4647 * Got a problem... hardlink to a non-existant object
4649 hl->variant.hardLinkVariant.equivalentObject = NULL;
4650 INIT_LIST_HEAD(&hl->hardLinks);
4662 static int ybicmp(const void *a, const void *b){
4663 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4664 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4665 register int ablock = ((yaffs_BlockIndex *)a)->block;
4666 register int bblock = ((yaffs_BlockIndex *)b)->block;
4668 return ablock - bblock;
4674 static int yaffs_Scan(yaffs_Device * dev)
4676 yaffs_ExtendedTags tags;
4681 int nBlocksToScan = 0;
4687 yaffs_BlockState state;
4688 yaffs_Object *hardList = NULL;
4690 yaffs_BlockInfo *bi;
4692 yaffs_ObjectHeader *oh;
4694 yaffs_Object *parent;
4695 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4699 yaffs_BlockIndex *blockIndex = NULL;
4701 if (dev->isYaffs2) {
4703 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4707 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4710 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4711 dev->internalStartBlock, dev->internalEndBlock));
4713 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4715 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4717 if (dev->isYaffs2) {
4718 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4721 /* Scan all the blocks to determine their state */
4722 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4723 bi = yaffs_GetBlockInfo(dev, blk);
4724 yaffs_ClearChunkBits(dev, blk);
4726 bi->softDeletions = 0;
4728 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4730 bi->blockState = state;
4731 bi->sequenceNumber = sequenceNumber;
4733 T(YAFFS_TRACE_SCAN_DEBUG,
4734 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4735 state, sequenceNumber));
4737 if (state == YAFFS_BLOCK_STATE_DEAD) {
4738 T(YAFFS_TRACE_BAD_BLOCKS,
4739 (TSTR("block %d is bad" TENDSTR), blk));
4740 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4741 T(YAFFS_TRACE_SCAN_DEBUG,
4742 (TSTR("Block empty " TENDSTR)));
4743 dev->nErasedBlocks++;
4744 dev->nFreeChunks += dev->nChunksPerBlock;
4745 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4747 /* Determine the highest sequence number */
4748 if (dev->isYaffs2 &&
4749 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4750 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4752 blockIndex[nBlocksToScan].seq = sequenceNumber;
4753 blockIndex[nBlocksToScan].block = blk;
4757 if (sequenceNumber >= dev->sequenceNumber) {
4758 dev->sequenceNumber = sequenceNumber;
4760 } else if (dev->isYaffs2) {
4761 /* TODO: Nasty sequence number! */
4764 ("Block scanning block %d has bad sequence number %d"
4765 TENDSTR), blk, sequenceNumber));
4772 * Dungy old bubble sort for now...
4774 if (dev->isYaffs2) {
4775 yaffs_BlockIndex temp;
4779 for (i = 0; i < nBlocksToScan; i++)
4780 for (j = i + 1; j < nBlocksToScan; j++)
4781 if (blockIndex[i].seq > blockIndex[j].seq) {
4782 temp = blockIndex[j];
4783 blockIndex[j] = blockIndex[i];
4784 blockIndex[i] = temp;
4788 /* Now scan the blocks looking at the data. */
4789 if (dev->isYaffs2) {
4791 endIterator = nBlocksToScan - 1;
4792 T(YAFFS_TRACE_SCAN_DEBUG,
4793 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4795 startIterator = dev->internalStartBlock;
4796 endIterator = dev->internalEndBlock;
4799 /* For each block.... */
4800 for (blockIterator = startIterator; blockIterator <= endIterator;
4803 if (dev->isYaffs2) {
4804 /* get the block to scan in the correct order */
4805 blk = blockIndex[blockIterator].block;
4807 blk = blockIterator;
4810 bi = yaffs_GetBlockInfo(dev, blk);
4811 state = bi->blockState;
4815 /* For each chunk in each block that needs scanning....*/
4816 for (c = 0; c < dev->nChunksPerBlock &&
4817 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4818 /* Read the tags and decide what to do */
4819 chunk = blk * dev->nChunksPerBlock + c;
4821 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4824 /* Let's have a good look at this chunk... */
4826 if (!dev->isYaffs2 && tags.chunkDeleted) {
4832 /*T((" %d %d deleted\n",blk,c)); */
4833 } else if (!tags.chunkUsed) {
4834 /* An unassigned chunk in the block
4835 * This means that either the block is empty or
4836 * this is the one being allocated from
4840 /* We're looking at the first chunk in the block so the block is unused */
4841 state = YAFFS_BLOCK_STATE_EMPTY;
4842 dev->nErasedBlocks++;
4844 /* this is the block being allocated from */
4847 (" Allocating from %d %d" TENDSTR),
4849 state = YAFFS_BLOCK_STATE_ALLOCATING;
4850 dev->allocationBlock = blk;
4851 dev->allocationPage = c;
4852 dev->allocationBlockFinder = blk;
4853 /* Set it to here to encourage the allocator to go forth from here. */
4855 /* Yaffs2 sanity check:
4856 * This should be the one with the highest sequence number
4859 && (dev->sequenceNumber !=
4860 bi->sequenceNumber)) {
4861 T(YAFFS_TRACE_ALWAYS,
4863 ("yaffs: Allocation block %d was not highest sequence id:"
4864 " block seq = %d, dev seq = %d"
4865 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4869 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4870 } else if (tags.chunkId > 0) {
4871 /* chunkId > 0 so it is a data chunk... */
4872 unsigned int endpos;
4874 yaffs_SetChunkBit(dev, blk, c);
4877 in = yaffs_FindOrCreateObjectByNumber(dev,
4880 YAFFS_OBJECT_TYPE_FILE);
4881 /* PutChunkIntoFile checks for a clash (two data chunks with
4882 * the same chunkId).
4884 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4887 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
4889 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4890 && in->variant.fileVariant.scannedFileSize <
4892 in->variant.fileVariant.
4893 scannedFileSize = endpos;
4894 if (!dev->useHeaderFileSize) {
4895 in->variant.fileVariant.
4897 in->variant.fileVariant.
4902 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4904 /* chunkId == 0, so it is an ObjectHeader.
4905 * Thus, we read in the object header and make the object
4907 yaffs_SetChunkBit(dev, blk, c);
4910 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4914 oh = (yaffs_ObjectHeader *) chunkData;
4916 in = yaffs_FindObjectByNumber(dev,
4918 if (in && in->variantType != oh->type) {
4919 /* This should not happen, but somehow
4920 * Wev'e ended up with an objectId that has been reused but not yet
4921 * deleted, and worse still it has changed type. Delete the old object.
4924 yaffs_DestroyObject(in);
4929 in = yaffs_FindOrCreateObjectByNumber(dev,
4934 if (oh->shadowsObject > 0) {
4935 yaffs_HandleShadowedObject(dev,
4942 /* We have already filled this one. We have a duplicate and need to resolve it. */
4944 unsigned existingSerial = in->serial;
4945 unsigned newSerial = tags.serialNumber;
4947 if (dev->isYaffs2 ||
4948 ((existingSerial + 1) & 3) ==
4950 /* Use new one - destroy the exisiting one */
4951 yaffs_DeleteChunk(dev,
4956 /* Use existing - destroy this one. */
4957 yaffs_DeleteChunk(dev, chunk, 1,
4963 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4964 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4965 /* We only load some info, don't fiddle with directory structure */
4967 in->variantType = oh->type;
4969 in->yst_mode = oh->yst_mode;
4970 #ifdef CONFIG_YAFFS_WINCE
4971 in->win_atime[0] = oh->win_atime[0];
4972 in->win_ctime[0] = oh->win_ctime[0];
4973 in->win_mtime[0] = oh->win_mtime[0];
4974 in->win_atime[1] = oh->win_atime[1];
4975 in->win_ctime[1] = oh->win_ctime[1];
4976 in->win_mtime[1] = oh->win_mtime[1];
4978 in->yst_uid = oh->yst_uid;
4979 in->yst_gid = oh->yst_gid;
4980 in->yst_atime = oh->yst_atime;
4981 in->yst_mtime = oh->yst_mtime;
4982 in->yst_ctime = oh->yst_ctime;
4983 in->yst_rdev = oh->yst_rdev;
4985 in->chunkId = chunk;
4987 } else if (!in->valid) {
4988 /* we need to load this info */
4991 in->variantType = oh->type;
4993 in->yst_mode = oh->yst_mode;
4994 #ifdef CONFIG_YAFFS_WINCE
4995 in->win_atime[0] = oh->win_atime[0];
4996 in->win_ctime[0] = oh->win_ctime[0];
4997 in->win_mtime[0] = oh->win_mtime[0];
4998 in->win_atime[1] = oh->win_atime[1];
4999 in->win_ctime[1] = oh->win_ctime[1];
5000 in->win_mtime[1] = oh->win_mtime[1];
5002 in->yst_uid = oh->yst_uid;
5003 in->yst_gid = oh->yst_gid;
5004 in->yst_atime = oh->yst_atime;
5005 in->yst_mtime = oh->yst_mtime;
5006 in->yst_ctime = oh->yst_ctime;
5007 in->yst_rdev = oh->yst_rdev;
5009 in->chunkId = chunk;
5011 yaffs_SetObjectName(in, oh->name);
5014 /* directory stuff...
5019 yaffs_FindOrCreateObjectByNumber
5020 (dev, oh->parentObjectId,
5021 YAFFS_OBJECT_TYPE_DIRECTORY);
5022 if (parent->variantType ==
5023 YAFFS_OBJECT_TYPE_UNKNOWN) {
5024 /* Set up as a directory */
5025 parent->variantType =
5026 YAFFS_OBJECT_TYPE_DIRECTORY;
5027 INIT_LIST_HEAD(&parent->variant.
5030 } else if (parent->variantType !=
5031 YAFFS_OBJECT_TYPE_DIRECTORY)
5033 /* Hoosterman, another problem....
5034 * We're trying to use a non-directory as a directory
5037 T(YAFFS_TRACE_ERROR,
5039 ("yaffs tragedy: attempting to use non-directory as"
5040 " a directory in scan. Put in lost+found."
5042 parent = dev->lostNFoundDir;
5045 yaffs_AddObjectToDirectory(parent, in);
5047 if (0 && (parent == dev->deletedDir ||
5048 parent == dev->unlinkedDir)) {
5049 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5050 dev->nDeletedFiles++;
5052 /* Note re hardlinks.
5053 * Since we might scan a hardlink before its equivalent object is scanned
5054 * we put them all in a list.
5055 * After scanning is complete, we should have all the objects, so we run through this
5056 * list and fix up all the chains.
5059 switch (in->variantType) {
5060 case YAFFS_OBJECT_TYPE_UNKNOWN:
5061 /* Todo got a problem */
5063 case YAFFS_OBJECT_TYPE_FILE:
5066 /* Prune back the shrunken chunks */
5067 yaffs_PruneResizedChunks
5069 /* Mark the block as having a shrinkHeader */
5070 bi->hasShrinkHeader = 1;
5073 if (dev->useHeaderFileSize)
5075 in->variant.fileVariant.
5080 case YAFFS_OBJECT_TYPE_HARDLINK:
5081 in->variant.hardLinkVariant.
5082 equivalentObjectId =
5083 oh->equivalentObjectId;
5084 in->hardLinks.next =
5085 (struct list_head *)
5089 case YAFFS_OBJECT_TYPE_DIRECTORY:
5092 case YAFFS_OBJECT_TYPE_SPECIAL:
5095 case YAFFS_OBJECT_TYPE_SYMLINK:
5096 in->variant.symLinkVariant.
5098 yaffs_CloneString(oh->alias);
5102 if (parent == dev->deletedDir) {
5103 yaffs_DestroyObject(in);
5104 bi->hasShrinkHeader = 1;
5110 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5111 /* If we got this far while scanning, then the block is fully allocated.*/
5112 state = YAFFS_BLOCK_STATE_FULL;
5115 bi->blockState = state;
5117 /* Now let's see if it was dirty */
5118 if (bi->pagesInUse == 0 &&
5119 !bi->hasShrinkHeader &&
5120 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5121 yaffs_BlockBecameDirty(dev, blk);
5131 /* Ok, we've done all the scanning.
5132 * Fix up the hard link chains.
5133 * We should now have scanned all the objects, now it's time to add these
5137 yaffs_HardlinkFixup(dev,hardList);
5139 /* Handle the unlinked files. Since they were left in an unlinked state we should
5143 struct list_head *i;
5144 struct list_head *n;
5147 /* Soft delete all the unlinked files */
5148 list_for_each_safe(i, n,
5149 &dev->unlinkedDir->variant.directoryVariant.
5152 l = list_entry(i, yaffs_Object, siblings);
5153 yaffs_DestroyObject(l);
5158 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5160 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5165 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5168 yaffs_ObjectHeader *oh;
5169 yaffs_Device *dev = in->myDev;
5170 yaffs_ExtendedTags tags;
5174 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5176 in->lazyLoaded ? "not yet" : "already"));
5181 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5183 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5184 oh = (yaffs_ObjectHeader *) chunkData;
5186 in->yst_mode = oh->yst_mode;
5187 #ifdef CONFIG_YAFFS_WINCE
5188 in->win_atime[0] = oh->win_atime[0];
5189 in->win_ctime[0] = oh->win_ctime[0];
5190 in->win_mtime[0] = oh->win_mtime[0];
5191 in->win_atime[1] = oh->win_atime[1];
5192 in->win_ctime[1] = oh->win_ctime[1];
5193 in->win_mtime[1] = oh->win_mtime[1];
5195 in->yst_uid = oh->yst_uid;
5196 in->yst_gid = oh->yst_gid;
5197 in->yst_atime = oh->yst_atime;
5198 in->yst_mtime = oh->yst_mtime;
5199 in->yst_ctime = oh->yst_ctime;
5200 in->yst_rdev = oh->yst_rdev;
5203 yaffs_SetObjectName(in, oh->name);
5205 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5206 in->variant.symLinkVariant.alias =
5207 yaffs_CloneString(oh->alias);
5209 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5213 static int yaffs_ScanBackwards(yaffs_Device * dev)
5215 yaffs_ExtendedTags tags;
5220 int nBlocksToScan = 0;
5226 yaffs_BlockState state;
5227 yaffs_Object *hardList = NULL;
5228 yaffs_BlockInfo *bi;
5230 yaffs_ObjectHeader *oh;
5232 yaffs_Object *parent;
5233 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5239 int foundChunksInBlock;
5240 int equivalentObjectId;
5243 yaffs_BlockIndex *blockIndex = NULL;
5244 int altBlockIndex = 0;
5246 if (!dev->isYaffs2) {
5248 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5254 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5255 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5258 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5260 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5263 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5269 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5273 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5275 /* Scan all the blocks to determine their state */
5276 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5277 bi = yaffs_GetBlockInfo(dev, blk);
5278 yaffs_ClearChunkBits(dev, blk);
5280 bi->softDeletions = 0;
5282 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5284 bi->blockState = state;
5285 bi->sequenceNumber = sequenceNumber;
5287 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5288 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5290 T(YAFFS_TRACE_SCAN_DEBUG,
5291 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5292 state, sequenceNumber));
5295 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5296 /* todo .. fix free space ? */
5298 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5299 T(YAFFS_TRACE_BAD_BLOCKS,
5300 (TSTR("block %d is bad" TENDSTR), blk));
5301 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5302 T(YAFFS_TRACE_SCAN_DEBUG,
5303 (TSTR("Block empty " TENDSTR)));
5304 dev->nErasedBlocks++;
5305 dev->nFreeChunks += dev->nChunksPerBlock;
5306 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5308 /* Determine the highest sequence number */
5309 if (dev->isYaffs2 &&
5310 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5311 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5313 blockIndex[nBlocksToScan].seq = sequenceNumber;
5314 blockIndex[nBlocksToScan].block = blk;
5318 if (sequenceNumber >= dev->sequenceNumber) {
5319 dev->sequenceNumber = sequenceNumber;
5321 } else if (dev->isYaffs2) {
5322 /* TODO: Nasty sequence number! */
5325 ("Block scanning block %d has bad sequence number %d"
5326 TENDSTR), blk, sequenceNumber));
5333 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5339 /* Sort the blocks */
5340 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5342 /* Use qsort now. */
5343 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5347 /* Dungy old bubble sort... */
5349 yaffs_BlockIndex temp;
5353 for (i = 0; i < nBlocksToScan; i++)
5354 for (j = i + 1; j < nBlocksToScan; j++)
5355 if (blockIndex[i].seq > blockIndex[j].seq) {
5356 temp = blockIndex[j];
5357 blockIndex[j] = blockIndex[i];
5358 blockIndex[i] = temp;
5365 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5367 /* Now scan the blocks looking at the data. */
5369 endIterator = nBlocksToScan - 1;
5370 T(YAFFS_TRACE_SCAN_DEBUG,
5371 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5373 /* For each block.... backwards */
5374 for (blockIterator = endIterator; blockIterator >= startIterator;
5376 /* Cooperative multitasking! This loop can run for so
5377 long that watchdog timers expire. */
5380 /* get the block to scan in the correct order */
5381 blk = blockIndex[blockIterator].block;
5383 bi = yaffs_GetBlockInfo(dev, blk);
5384 state = bi->blockState;
5388 /* For each chunk in each block that needs scanning.... */
5389 foundChunksInBlock = 0;
5390 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5391 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5392 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5393 /* Scan backwards...
5394 * Read the tags and decide what to do
5396 chunk = blk * dev->nChunksPerBlock + c;
5398 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5401 /* Let's have a good look at this chunk... */
5403 if (!tags.chunkUsed) {
5404 /* An unassigned chunk in the block.
5405 * If there are used chunks after this one, then
5406 * it is a chunk that was skipped due to failing the erased
5407 * check. Just skip it so that it can be deleted.
5408 * But, more typically, We get here when this is an unallocated
5409 * chunk and his means that either the block is empty or
5410 * this is the one being allocated from
5413 if(foundChunksInBlock)
5415 /* This is a chunk that was skipped due to failing the erased check */
5417 } else if (c == 0) {
5418 /* We're looking at the first chunk in the block so the block is unused */
5419 state = YAFFS_BLOCK_STATE_EMPTY;
5420 dev->nErasedBlocks++;
5422 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5423 state == YAFFS_BLOCK_STATE_ALLOCATING) {
5424 if(dev->sequenceNumber == bi->sequenceNumber) {
5425 /* this is the block being allocated from */
5429 (" Allocating from %d %d"
5432 state = YAFFS_BLOCK_STATE_ALLOCATING;
5433 dev->allocationBlock = blk;
5434 dev->allocationPage = c;
5435 dev->allocationBlockFinder = blk;
5438 /* This is a partially written block that is not
5439 * the current allocation block. This block must have
5440 * had a write failure, so set up for retirement.
5443 bi->needsRetiring = 1;
5444 bi->gcPrioritise = 1;
5446 T(YAFFS_TRACE_ALWAYS,
5447 (TSTR("Partially written block %d being set for retirement" TENDSTR),
5457 } else if (tags.chunkId > 0) {
5458 /* chunkId > 0 so it is a data chunk... */
5459 unsigned int endpos;
5461 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
5463 foundChunksInBlock = 1;
5466 yaffs_SetChunkBit(dev, blk, c);
5469 in = yaffs_FindOrCreateObjectByNumber(dev,
5472 YAFFS_OBJECT_TYPE_FILE);
5473 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5475 in->variant.fileVariant.shrinkSize) {
5476 /* This has not been invalidated by a resize */
5477 yaffs_PutChunkIntoFile(in, tags.chunkId,
5480 /* File size is calculated by looking at the data chunks if we have not
5481 * seen an object header yet. Stop this practice once we find an object header.
5485 1) * dev->nDataBytesPerChunk +
5488 if (!in->valid && /* have not got an object header yet */
5489 in->variant.fileVariant.
5490 scannedFileSize < endpos) {
5491 in->variant.fileVariant.
5492 scannedFileSize = endpos;
5493 in->variant.fileVariant.
5495 in->variant.fileVariant.
5500 /* This chunk has been invalidated by a resize, so delete */
5501 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5505 /* chunkId == 0, so it is an ObjectHeader.
5506 * Thus, we read in the object header and make the object
5508 foundChunksInBlock = 1;
5510 yaffs_SetChunkBit(dev, blk, c);
5516 if (tags.extraHeaderInfoAvailable) {
5517 in = yaffs_FindOrCreateObjectByNumber
5518 (dev, tags.objectId,
5519 tags.extraObjectType);
5523 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5526 tags.extraShadows ||
5528 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5529 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5532 /* If we don't have valid info then we need to read the chunk
5533 * TODO In future we can probably defer reading the chunk and
5534 * living with invalid data until needed.
5537 result = yaffs_ReadChunkWithTagsFromNAND(dev,
5542 oh = (yaffs_ObjectHeader *) chunkData;
5545 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5550 /* TODO Hoosterman we have a problem! */
5551 T(YAFFS_TRACE_ERROR,
5553 ("yaffs tragedy: Could not make object for object %d "
5554 "at chunk %d during scan"
5555 TENDSTR), tags.objectId, chunk));
5560 /* We have already filled this one.
5561 * We have a duplicate that will be discarded, but
5562 * we first have to suck out resize info if it is a file.
5565 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5567 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5568 (tags.extraHeaderInfoAvailable &&
5569 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5572 (oh) ? oh->fileSize : tags.
5574 __u32 parentObjectId =
5576 parentObjectId : tags.
5577 extraParentObjectId;
5579 (oh) ? oh->isShrink : tags.
5580 extraIsShrinkHeader;
5582 /* If it is deleted (unlinked at start also means deleted)
5583 * we treat the file size as being zeroed at this point.
5585 if (parentObjectId ==
5586 YAFFS_OBJECTID_DELETED
5587 || parentObjectId ==
5588 YAFFS_OBJECTID_UNLINKED) {
5594 in->variant.fileVariant.
5595 shrinkSize > thisSize) {
5596 in->variant.fileVariant.
5602 bi->hasShrinkHeader = 1;
5606 /* Use existing - destroy this one. */
5607 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5612 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5614 YAFFS_OBJECTID_LOSTNFOUND)) {
5615 /* We only load some info, don't fiddle with directory structure */
5619 in->variantType = oh->type;
5621 in->yst_mode = oh->yst_mode;
5622 #ifdef CONFIG_YAFFS_WINCE
5623 in->win_atime[0] = oh->win_atime[0];
5624 in->win_ctime[0] = oh->win_ctime[0];
5625 in->win_mtime[0] = oh->win_mtime[0];
5626 in->win_atime[1] = oh->win_atime[1];
5627 in->win_ctime[1] = oh->win_ctime[1];
5628 in->win_mtime[1] = oh->win_mtime[1];
5630 in->yst_uid = oh->yst_uid;
5631 in->yst_gid = oh->yst_gid;
5632 in->yst_atime = oh->yst_atime;
5633 in->yst_mtime = oh->yst_mtime;
5634 in->yst_ctime = oh->yst_ctime;
5635 in->yst_rdev = oh->yst_rdev;
5639 in->variantType = tags.extraObjectType;
5643 in->chunkId = chunk;
5645 } else if (!in->valid) {
5646 /* we need to load this info */
5649 in->chunkId = chunk;
5652 in->variantType = oh->type;
5654 in->yst_mode = oh->yst_mode;
5655 #ifdef CONFIG_YAFFS_WINCE
5656 in->win_atime[0] = oh->win_atime[0];
5657 in->win_ctime[0] = oh->win_ctime[0];
5658 in->win_mtime[0] = oh->win_mtime[0];
5659 in->win_atime[1] = oh->win_atime[1];
5660 in->win_ctime[1] = oh->win_ctime[1];
5661 in->win_mtime[1] = oh->win_mtime[1];
5663 in->yst_uid = oh->yst_uid;
5664 in->yst_gid = oh->yst_gid;
5665 in->yst_atime = oh->yst_atime;
5666 in->yst_mtime = oh->yst_mtime;
5667 in->yst_ctime = oh->yst_ctime;
5668 in->yst_rdev = oh->yst_rdev;
5671 if (oh->shadowsObject > 0)
5672 yaffs_HandleShadowedObject(dev,
5678 yaffs_SetObjectName(in, oh->name);
5680 yaffs_FindOrCreateObjectByNumber
5681 (dev, oh->parentObjectId,
5682 YAFFS_OBJECT_TYPE_DIRECTORY);
5684 fileSize = oh->fileSize;
5685 isShrink = oh->isShrink;
5686 equivalentObjectId = oh->equivalentObjectId;
5690 in->variantType = tags.extraObjectType;
5692 yaffs_FindOrCreateObjectByNumber
5693 (dev, tags.extraParentObjectId,
5694 YAFFS_OBJECT_TYPE_DIRECTORY);
5695 fileSize = tags.extraFileLength;
5696 isShrink = tags.extraIsShrinkHeader;
5697 equivalentObjectId = tags.extraEquivalentObjectId;
5703 /* directory stuff...
5707 if (parent->variantType ==
5708 YAFFS_OBJECT_TYPE_UNKNOWN) {
5709 /* Set up as a directory */
5710 parent->variantType =
5711 YAFFS_OBJECT_TYPE_DIRECTORY;
5712 INIT_LIST_HEAD(&parent->variant.
5715 } else if (parent->variantType !=
5716 YAFFS_OBJECT_TYPE_DIRECTORY)
5718 /* Hoosterman, another problem....
5719 * We're trying to use a non-directory as a directory
5722 T(YAFFS_TRACE_ERROR,
5724 ("yaffs tragedy: attempting to use non-directory as"
5725 " a directory in scan. Put in lost+found."
5727 parent = dev->lostNFoundDir;
5730 yaffs_AddObjectToDirectory(parent, in);
5732 itsUnlinked = (parent == dev->deletedDir) ||
5733 (parent == dev->unlinkedDir);
5736 /* Mark the block as having a shrinkHeader */
5737 bi->hasShrinkHeader = 1;
5740 /* Note re hardlinks.
5741 * Since we might scan a hardlink before its equivalent object is scanned
5742 * we put them all in a list.
5743 * After scanning is complete, we should have all the objects, so we run
5744 * through this list and fix up all the chains.
5747 switch (in->variantType) {
5748 case YAFFS_OBJECT_TYPE_UNKNOWN:
5749 /* Todo got a problem */
5751 case YAFFS_OBJECT_TYPE_FILE:
5753 if (in->variant.fileVariant.
5754 scannedFileSize < fileSize) {
5755 /* This covers the case where the file size is greater
5756 * than where the data is
5757 * This will happen if the file is resized to be larger
5758 * than its current data extents.
5760 in->variant.fileVariant.fileSize = fileSize;
5761 in->variant.fileVariant.scannedFileSize =
5762 in->variant.fileVariant.fileSize;
5766 in->variant.fileVariant.shrinkSize > fileSize) {
5767 in->variant.fileVariant.shrinkSize = fileSize;
5771 case YAFFS_OBJECT_TYPE_HARDLINK:
5773 in->variant.hardLinkVariant.equivalentObjectId =
5775 in->hardLinks.next =
5776 (struct list_head *) hardList;
5780 case YAFFS_OBJECT_TYPE_DIRECTORY:
5783 case YAFFS_OBJECT_TYPE_SPECIAL:
5786 case YAFFS_OBJECT_TYPE_SYMLINK:
5788 in->variant.symLinkVariant.alias =
5789 yaffs_CloneString(oh->
5798 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5799 /* If we got this far while scanning, then the block is fully allocated. */
5800 state = YAFFS_BLOCK_STATE_FULL;
5803 bi->blockState = state;
5805 /* Now let's see if it was dirty */
5806 if (bi->pagesInUse == 0 &&
5807 !bi->hasShrinkHeader &&
5808 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5809 yaffs_BlockBecameDirty(dev, blk);
5815 YFREE_ALT(blockIndex);
5819 /* Ok, we've done all the scanning.
5820 * Fix up the hard link chains.
5821 * We should now have scanned all the objects, now it's time to add these
5824 yaffs_HardlinkFixup(dev,hardList);
5828 * Sort out state of unlinked and deleted objects.
5831 struct list_head *i;
5832 struct list_head *n;
5836 /* Soft delete all the unlinked files */
5837 list_for_each_safe(i, n,
5838 &dev->unlinkedDir->variant.directoryVariant.
5841 l = list_entry(i, yaffs_Object, siblings);
5842 yaffs_DestroyObject(l);
5846 /* Soft delete all the deletedDir files */
5847 list_for_each_safe(i, n,
5848 &dev->deletedDir->variant.directoryVariant.
5851 l = list_entry(i, yaffs_Object, siblings);
5852 yaffs_DestroyObject(l);
5858 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5860 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5865 /*------------------------------ Directory Functions ----------------------------- */
5867 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5869 yaffs_Device *dev = obj->myDev;
5871 if(dev && dev->removeObjectCallback)
5872 dev->removeObjectCallback(obj);
5874 list_del_init(&obj->siblings);
5879 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5884 T(YAFFS_TRACE_ALWAYS,
5886 ("tragedy: Trying to add an object to a null pointer directory"
5890 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5891 T(YAFFS_TRACE_ALWAYS,
5893 ("tragedy: Trying to add an object to a non-directory"
5898 if (obj->siblings.prev == NULL) {
5899 /* Not initialised */
5900 INIT_LIST_HEAD(&obj->siblings);
5902 } else if (!list_empty(&obj->siblings)) {
5903 /* If it is holed up somewhere else, un hook it */
5904 yaffs_RemoveObjectFromDirectory(obj);
5907 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5908 obj->parent = directory;
5910 if (directory == obj->myDev->unlinkedDir
5911 || directory == obj->myDev->deletedDir) {
5913 obj->myDev->nUnlinkedFiles++;
5914 obj->renameAllowed = 0;
5918 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5923 struct list_head *i;
5924 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5933 T(YAFFS_TRACE_ALWAYS,
5935 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5939 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5940 T(YAFFS_TRACE_ALWAYS,
5942 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5946 sum = yaffs_CalcNameSum(name);
5948 list_for_each(i, &directory->variant.directoryVariant.children) {
5950 l = list_entry(i, yaffs_Object, siblings);
5952 yaffs_CheckObjectDetailsLoaded(l);
5954 /* Special case for lost-n-found */
5955 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5956 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5959 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5961 /* LostnFound cunk called Objxxx
5964 yaffs_GetObjectName(l, buffer,
5965 YAFFS_MAX_NAME_LENGTH);
5966 if (yaffs_strcmp(name, buffer) == 0) {
5979 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5980 int (*fn) (yaffs_Object *))
5982 struct list_head *i;
5986 T(YAFFS_TRACE_ALWAYS,
5988 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5992 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5993 T(YAFFS_TRACE_ALWAYS,
5995 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5999 list_for_each(i, &theDir->variant.directoryVariant.children) {
6001 l = list_entry(i, yaffs_Object, siblings);
6013 /* GetEquivalentObject dereferences any hard links to get to the
6017 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6019 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6020 /* We want the object id of the equivalent object, not this one */
6021 obj = obj->variant.hardLinkVariant.equivalentObject;
6027 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6029 memset(name, 0, buffSize * sizeof(YCHAR));
6031 yaffs_CheckObjectDetailsLoaded(obj);
6033 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6034 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6035 } else if (obj->chunkId <= 0) {
6037 /* make up a name */
6038 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6040 yaffs_strncpy(name, locName, buffSize - 1);
6043 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6044 else if (obj->shortName[0]) {
6045 yaffs_strcpy(name, obj->shortName);
6050 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6052 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6054 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6056 if (obj->chunkId >= 0) {
6057 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6058 obj->chunkId, buffer,
6061 yaffs_strncpy(name, oh->name, buffSize - 1);
6063 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6066 return yaffs_strlen(name);
6069 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6072 /* Dereference any hard linking */
6073 obj = yaffs_GetEquivalentObject(obj);
6075 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6076 return obj->variant.fileVariant.fileSize;
6078 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6079 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6081 /* Only a directory should drop through to here */
6082 return obj->myDev->nDataBytesPerChunk;
6086 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6089 struct list_head *i;
6091 if (!obj->unlinked) {
6092 count++; /* the object itself */
6094 list_for_each(i, &obj->hardLinks) {
6095 count++; /* add the hard links; */
6101 int yaffs_GetObjectInode(yaffs_Object * obj)
6103 obj = yaffs_GetEquivalentObject(obj);
6105 return obj->objectId;
6108 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6110 obj = yaffs_GetEquivalentObject(obj);
6112 switch (obj->variantType) {
6113 case YAFFS_OBJECT_TYPE_FILE:
6116 case YAFFS_OBJECT_TYPE_DIRECTORY:
6119 case YAFFS_OBJECT_TYPE_SYMLINK:
6122 case YAFFS_OBJECT_TYPE_HARDLINK:
6125 case YAFFS_OBJECT_TYPE_SPECIAL:
6126 if (S_ISFIFO(obj->yst_mode))
6128 if (S_ISCHR(obj->yst_mode))
6130 if (S_ISBLK(obj->yst_mode))
6132 if (S_ISSOCK(obj->yst_mode))
6140 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6142 obj = yaffs_GetEquivalentObject(obj);
6143 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6144 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6146 return yaffs_CloneString(_Y(""));
6150 #ifndef CONFIG_YAFFS_WINCE
6152 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6154 unsigned int valid = attr->ia_valid;
6156 if (valid & ATTR_MODE)
6157 obj->yst_mode = attr->ia_mode;
6158 if (valid & ATTR_UID)
6159 obj->yst_uid = attr->ia_uid;
6160 if (valid & ATTR_GID)
6161 obj->yst_gid = attr->ia_gid;
6163 if (valid & ATTR_ATIME)
6164 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6165 if (valid & ATTR_CTIME)
6166 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6167 if (valid & ATTR_MTIME)
6168 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6170 if (valid & ATTR_SIZE)
6171 yaffs_ResizeFile(obj, attr->ia_size);
6173 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6178 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6180 unsigned int valid = 0;
6182 attr->ia_mode = obj->yst_mode;
6184 attr->ia_uid = obj->yst_uid;
6186 attr->ia_gid = obj->yst_gid;
6189 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6190 valid |= ATTR_ATIME;
6191 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6192 valid |= ATTR_CTIME;
6193 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6194 valid |= ATTR_MTIME;
6196 attr->ia_size = yaffs_GetFileSize(obj);
6199 attr->ia_valid = valid;
6208 int yaffs_DumpObject(yaffs_Object * obj)
6212 yaffs_GetObjectName(obj, name, 256);
6214 T(YAFFS_TRACE_ALWAYS,
6216 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6217 " chunk %d type %d size %d\n"
6218 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6219 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6220 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6226 /*---------------------------- Initialisation code -------------------------------------- */
6228 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6231 /* Common functions, gotta have */
6232 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6235 #ifdef CONFIG_YAFFS_YAFFS2
6237 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6238 if (dev->writeChunkWithTagsToNAND &&
6239 dev->readChunkWithTagsFromNAND &&
6240 !dev->writeChunkToNAND &&
6241 !dev->readChunkFromNAND &&
6242 dev->markNANDBlockBad && dev->queryNANDBlock)
6246 /* Can use the "spare" style interface for yaffs1 */
6247 if (!dev->isYaffs2 &&
6248 !dev->writeChunkWithTagsToNAND &&
6249 !dev->readChunkWithTagsFromNAND &&
6250 dev->writeChunkToNAND &&
6251 dev->readChunkFromNAND &&
6252 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6259 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6261 /* Initialise the unlinked, deleted, root and lost and found directories */
6263 dev->lostNFoundDir = dev->rootDir = NULL;
6264 dev->unlinkedDir = dev->deletedDir = NULL;
6267 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6269 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6272 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6273 YAFFS_ROOT_MODE | S_IFDIR);
6274 dev->lostNFoundDir =
6275 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6276 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6277 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6280 int yaffs_GutsInitialise(yaffs_Device * dev)
6285 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6287 /* Check stuff that must be set */
6290 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6294 dev->internalStartBlock = dev->startBlock;
6295 dev->internalEndBlock = dev->endBlock;
6296 dev->blockOffset = 0;
6297 dev->chunkOffset = 0;
6298 dev->nFreeChunks = 0;
6300 if (dev->startBlock == 0) {
6301 dev->internalStartBlock = dev->startBlock + 1;
6302 dev->internalEndBlock = dev->endBlock + 1;
6303 dev->blockOffset = 1;
6304 dev->chunkOffset = dev->nChunksPerBlock;
6307 /* Check geometry parameters. */
6309 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
6310 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
6311 dev->nChunksPerBlock < 2 ||
6312 dev->nReservedBlocks < 2 ||
6313 dev->internalStartBlock <= 0 ||
6314 dev->internalEndBlock <= 0 ||
6315 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6317 T(YAFFS_TRACE_ALWAYS,
6319 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6320 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6324 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6325 T(YAFFS_TRACE_ALWAYS,
6326 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6330 /* Got the right mix of functions? */
6331 if (!yaffs_CheckDevFunctions(dev)) {
6332 /* Function missing */
6333 T(YAFFS_TRACE_ALWAYS,
6335 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6340 /* This is really a compilation check. */
6341 if (!yaffs_CheckStructures()) {
6342 T(YAFFS_TRACE_ALWAYS,
6343 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6347 if (dev->isMounted) {
6348 T(YAFFS_TRACE_ALWAYS,
6349 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6353 /* Finished with most checks. One or two more checks happen later on too. */
6359 /* OK now calculate a few things for the device */
6362 * Calculate all the chunk size manipulation numbers:
6364 /* Start off assuming it is a power of 2 */
6365 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
6366 dev->chunkMask = (1<<dev->chunkShift) - 1;
6368 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
6369 /* Yes it is a power of 2, disable crumbs */
6371 dev->crumbShift = 0;
6372 dev->crumbsPerChunk = 0;
6374 /* Not a power of 2, use crumbs instead */
6375 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
6376 dev->crumbMask = (1<<dev->crumbShift)-1;
6377 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
6378 dev->chunkShift = 0;
6384 * Calculate chunkGroupBits.
6385 * We need to find the next power of 2 > than internalEndBlock
6388 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6392 /* Set up tnode width if wide tnodes are enabled. */
6393 if(!dev->wideTnodesDisabled){
6394 /* bits must be even so that we end up with 32-bit words */
6398 dev->tnodeWidth = 16;
6400 dev->tnodeWidth = bits;
6403 dev->tnodeWidth = 16;
6405 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6407 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6408 * so if the bitwidth of the
6409 * chunk range we're using is greater than 16 we need
6410 * to figure out chunk shift and chunkGroupSize
6413 if (bits <= dev->tnodeWidth)
6414 dev->chunkGroupBits = 0;
6416 dev->chunkGroupBits = bits - dev->tnodeWidth;
6419 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6421 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6422 /* We have a problem because the soft delete won't work if
6423 * the chunk group size > chunks per block.
6424 * This can be remedied by using larger "virtual blocks".
6426 T(YAFFS_TRACE_ALWAYS,
6427 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6432 /* OK, we've finished verifying the device, lets continue with initialisation */
6434 /* More device initialisation */
6435 dev->garbageCollections = 0;
6436 dev->passiveGarbageCollections = 0;
6437 dev->currentDirtyChecker = 0;
6438 dev->bufferedBlock = -1;
6439 dev->doingBufferedBlockRewrite = 0;
6440 dev->nDeletedFiles = 0;
6441 dev->nBackgroundDeletions = 0;
6442 dev->nUnlinkedFiles = 0;
6444 dev->eccUnfixed = 0;
6445 dev->tagsEccFixed = 0;
6446 dev->tagsEccUnfixed = 0;
6447 dev->nErasureFailures = 0;
6448 dev->nErasedBlocks = 0;
6450 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
6452 /* Initialise temporary buffers and caches. */
6455 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6456 dev->tempBuffer[i].line = 0; /* not in use */
6457 dev->tempBuffer[i].buffer =
6458 YMALLOC_DMA(dev->nDataBytesPerChunk);
6462 if (dev->nShortOpCaches > 0) {
6465 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6466 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6470 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6472 for (i = 0; i < dev->nShortOpCaches; i++) {
6473 dev->srCache[i].object = NULL;
6474 dev->srCache[i].lastUse = 0;
6475 dev->srCache[i].dirty = 0;
6476 dev->srCache[i].data = YMALLOC_DMA(dev->nDataBytesPerChunk);
6483 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6485 if (dev->isYaffs2) {
6486 dev->useHeaderFileSize = 1;
6489 yaffs_InitialiseBlocks(dev);
6490 yaffs_InitialiseTnodes(dev);
6491 yaffs_InitialiseObjects(dev);
6493 yaffs_CreateInitialDirectories(dev);
6496 /* Now scan the flash. */
6497 if (dev->isYaffs2) {
6498 if(yaffs_CheckpointRestore(dev)) {
6499 T(YAFFS_TRACE_ALWAYS,
6500 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6503 /* Clean up the mess caused by an aborted checkpoint load
6504 * and scan backwards.
6506 yaffs_DeinitialiseBlocks(dev);
6507 yaffs_DeinitialiseTnodes(dev);
6508 yaffs_DeinitialiseObjects(dev);
6509 yaffs_InitialiseBlocks(dev);
6510 yaffs_InitialiseTnodes(dev);
6511 yaffs_InitialiseObjects(dev);
6512 yaffs_CreateInitialDirectories(dev);
6514 yaffs_ScanBackwards(dev);
6519 /* Zero out stats */
6520 dev->nPageReads = 0;
6521 dev->nPageWrites = 0;
6522 dev->nBlockErasures = 0;
6524 dev->nRetriedWrites = 0;
6526 dev->nRetiredBlocks = 0;
6528 yaffs_VerifyFreeChunks(dev);
6530 T(YAFFS_TRACE_TRACING,
6531 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6536 void yaffs_Deinitialise(yaffs_Device * dev)
6538 if (dev->isMounted) {
6541 yaffs_DeinitialiseBlocks(dev);
6542 yaffs_DeinitialiseTnodes(dev);
6543 yaffs_DeinitialiseObjects(dev);
6544 if (dev->nShortOpCaches > 0) {
6546 for (i = 0; i < dev->nShortOpCaches; i++) {
6547 YFREE(dev->srCache[i].data);
6550 YFREE(dev->srCache);
6553 YFREE(dev->gcCleanupList);
6555 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6556 YFREE(dev->tempBuffer[i].buffer);
6564 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6569 yaffs_BlockInfo *blk;
6571 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6573 blk = yaffs_GetBlockInfo(dev, b);
6575 switch (blk->blockState) {
6576 case YAFFS_BLOCK_STATE_EMPTY:
6577 case YAFFS_BLOCK_STATE_ALLOCATING:
6578 case YAFFS_BLOCK_STATE_COLLECTING:
6579 case YAFFS_BLOCK_STATE_FULL:
6581 (dev->nChunksPerBlock - blk->pagesInUse +
6582 blk->softDeletions);
6593 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6595 /* This is what we report to the outside world */
6598 int nDirtyCacheChunks;
6599 int blocksForCheckpoint;
6602 nFree = dev->nFreeChunks;
6604 nFree = yaffs_CountFreeChunks(dev);
6607 nFree += dev->nDeletedFiles;
6609 /* Now count the number of dirty chunks in the cache and subtract those */
6613 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6614 if (dev->srCache[i].dirty)
6615 nDirtyCacheChunks++;
6619 nFree -= nDirtyCacheChunks;
6621 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6623 /* Now we figure out how much to reserve for the checkpoint and report that... */
6624 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6625 if(blocksForCheckpoint < 0)
6626 blocksForCheckpoint = 0;
6628 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6637 static int yaffs_freeVerificationFailures;
6639 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6641 int counted = yaffs_CountFreeChunks(dev);
6643 int difference = dev->nFreeChunks - counted;
6646 T(YAFFS_TRACE_ALWAYS,
6647 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6648 dev->nFreeChunks, counted, difference));
6649 yaffs_freeVerificationFailures++;
6653 /*---------------------------------------- YAFFS test code ----------------------*/
6655 #define yaffs_CheckStruct(structure,syze, name) \
6656 if(sizeof(structure) != syze) \
6658 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6659 name,syze,sizeof(structure))); \
6660 return YAFFS_FAIL; \
6663 static int yaffs_CheckStructures(void)
6665 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6666 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6667 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6668 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6669 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6671 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")