2 * YAFFS: Yet another FFS. A NAND-flash specific file system.
4 * Copyright (C) 2002 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
15 const char *yaffs_guts_c_version =
16 "$Id: yaffs_guts.c,v 1.44 2006-11-11 23:27:44 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #ifdef CONFIG_YAFFS_WINCE
37 void yfsd_LockYAFFS(BOOL fsLockOnly);
38 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
41 #define YAFFS_PASSIVE_GC_CHUNKS 2
43 #include "yaffs_ecc.h"
46 /* Robustification (if it ever comes about...) */
47 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
48 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
49 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
51 const yaffs_ExtendedTags * tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
53 const yaffs_ExtendedTags * tags);
55 /* Other local prototypes */
56 static int yaffs_UnlinkObject( yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
61 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
63 yaffs_ExtendedTags * tags,
65 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
66 int chunkInNAND, int inScan);
68 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
69 yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
72 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
73 int force, int isShrink, int shadows);
74 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
75 static int yaffs_CheckStructures(void);
76 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
77 int chunkOffset, int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
82 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
83 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
86 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
89 static int yaffs_UnlinkWorker(yaffs_Object * obj);
90 static void yaffs_DestroyObject(yaffs_Object * obj);
92 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
95 loff_t yaffs_GetFileSize(yaffs_Object * obj);
97 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
99 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
101 #ifdef YAFFS_PARANOID
102 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #define yaffs_CheckFileSanity(in)
107 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
108 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
114 /* Function to calculate chunk and offset */
116 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
119 /* Easy-peasy power of 2 case */
120 *chunk = (__u32)(addr >> dev->chunkShift);
121 *offset = (__u32)(addr & dev->chunkMask);
123 else if(dev->crumbsPerChunk)
125 /* Case where we're using "crumbs" */
126 *offset = (__u32)(addr & dev->crumbMask);
127 addr >>= dev->crumbShift;
128 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
129 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
135 /* Function to return the number of shifts for a power of 2 greater than or equal
136 * to the given number
137 * Note we don't try to cater for all possible numbers and this does not have to
138 * be hellishly efficient.
141 static __u32 ShiftsGE(__u32 x)
146 nShifts = extraBits = 0;
149 if(x & 1) extraBits++;
160 /* Function to return the number of shifts to get a 1 in bit 0
163 static __u32 ShiftDiv(__u32 x)
182 * Temporary buffer manipulations.
185 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
188 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
189 if (dev->tempBuffer[i].line == 0) {
190 dev->tempBuffer[i].line = lineNo;
191 if ((i + 1) > dev->maxTemp) {
192 dev->maxTemp = i + 1;
193 for (j = 0; j <= i; j++)
194 dev->tempBuffer[j].maxLine =
195 dev->tempBuffer[j].line;
198 return dev->tempBuffer[i].buffer;
202 T(YAFFS_TRACE_BUFFERS,
203 (TSTR("Out of temp buffers at line %d, other held by lines:"),
205 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
206 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
208 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
211 * If we got here then we have to allocate an unmanaged one
215 dev->unmanagedTempAllocations++;
216 return YMALLOC(dev->nDataBytesPerChunk);
220 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
224 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
225 if (dev->tempBuffer[i].buffer == buffer) {
226 dev->tempBuffer[i].line = 0;
232 /* assume it is an unmanaged one. */
233 T(YAFFS_TRACE_BUFFERS,
234 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
237 dev->unmanagedTempDeallocations++;
243 * Determine if we have a managed buffer.
245 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
248 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
249 if (dev->tempBuffer[i].buffer == buffer)
254 for (i = 0; i < dev->nShortOpCaches; i++) {
255 if( dev->srCache[i].data == buffer )
260 if (buffer == dev->checkpointBuffer)
263 T(YAFFS_TRACE_ALWAYS,
264 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
269 * Chunk bitmap manipulations
272 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
274 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
276 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
280 return dev->chunkBits +
281 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
284 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
286 __u8 *blkBits = yaffs_BlockBits(dev, blk);
288 memset(blkBits, 0, dev->chunkBitmapStride);
291 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
293 __u8 *blkBits = yaffs_BlockBits(dev, blk);
295 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
298 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
300 __u8 *blkBits = yaffs_BlockBits(dev, blk);
302 blkBits[chunk / 8] |= (1 << (chunk & 7));
305 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
307 __u8 *blkBits = yaffs_BlockBits(dev, blk);
308 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
311 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
313 __u8 *blkBits = yaffs_BlockBits(dev, blk);
315 for (i = 0; i < dev->chunkBitmapStride; i++) {
324 * Simple hash function. Needs to have a reasonable spread
327 static Y_INLINE int yaffs_HashFunction(int n)
330 return (n % YAFFS_NOBJECT_BUCKETS);
334 * Access functions to useful fake objects
337 yaffs_Object *yaffs_Root(yaffs_Device * dev)
342 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
344 return dev->lostNFoundDir;
349 * Erased NAND checking functions
352 int yaffs_CheckFF(__u8 * buffer, int nBytes)
354 /* Horrible, slow implementation */
363 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
367 int retval = YAFFS_OK;
368 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
369 yaffs_ExtendedTags tags;
372 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
374 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
378 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
379 T(YAFFS_TRACE_NANDACCESS,
380 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
384 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
390 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
392 yaffs_ExtendedTags * tags,
402 yaffs_InvalidateCheckpoint(dev);
405 chunk = yaffs_AllocateChunk(dev, useReserve,&bi);
408 /* First check this chunk is erased, if it needs checking.
409 * The checking policy (unless forced always on) is as follows:
410 * Check the first page we try to write in a block.
411 * - If the check passes then we don't need to check any more.
412 * - If the check fails, we check again...
413 * If the block has been erased, we don't need to check.
415 * However, if the block has been prioritised for gc, then
416 * we think there might be something odd about this block
420 * We should only ever see chunks that have not been erased
421 * if there was a partially written chunk due to power loss
422 * This checking policy should catch that case with very
423 * few checks and thus save a lot of checks that are most likely not
427 if(bi->gcPrioritise){
428 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
430 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
432 bi->skipErasedCheck = 0;
435 if(!bi->skipErasedCheck){
436 erasedOk = yaffs_CheckChunkErased(dev, chunk);
437 if(erasedOk && !bi->gcPrioritise)
438 bi->skipErasedCheck = 1;
444 ("**>> yaffs chunk %d was not erased"
448 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
456 * Copy the data into the robustification buffer.
457 * NB We do this at the end to prevent duplicates in the case of a write error.
460 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
463 /* The erased check or write failed */
464 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
469 } while (chunk >= 0 && !writeOk);
473 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
475 dev->nRetriedWrites += (attempts - 1);
482 * Block retiring for handling a broken block.
485 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
487 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
489 yaffs_InvalidateCheckpoint(dev);
491 yaffs_MarkBlockBad(dev, blockInNAND);
493 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
494 bi->gcPrioritise = 0;
495 bi->needsRetiring = 0;
497 dev->nRetiredBlocks++;
501 * Functions for robustisizing TODO
505 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
507 const yaffs_ExtendedTags * tags)
511 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
512 const yaffs_ExtendedTags * tags)
516 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
518 if(!bi->gcPrioritise){
519 bi->gcPrioritise = 1;
520 dev->hasPendingPrioritisedGCs = 1;
521 bi->chunkErrorStrikes ++;
523 if(bi->chunkErrorStrikes > 3){
524 bi->needsRetiring = 1; /* Too many stikes, so retire this */
525 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
532 static void yaffs_ReportOddballBlocks(yaffs_Device *dev)
536 for(i = dev->internalStartBlock; i <= dev->internalEndBlock && (yaffs_traceMask & YAFFS_TRACE_BAD_BLOCKS); i++){
537 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
538 if(bi->needsRetiring || bi->gcPrioritise)
539 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("yaffs block %d%s%s" TENDSTR),
541 bi->needsRetiring ? " needs retiring" : "",
542 bi->gcPrioritise ? " gc prioritised" : ""));
547 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
550 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
551 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
553 yaffs_HandleChunkError(dev,bi);
557 /* Was an actual write failure, so mark the block for retirement */
558 bi->needsRetiring = 1;
559 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
560 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
565 /* Delete the chunk */
566 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
570 /*---------------- Name handling functions ------------*/
572 static __u16 yaffs_CalcNameSum(const YCHAR * name)
577 YUCHAR *bname = (YUCHAR *) name;
579 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
581 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
582 sum += yaffs_toupper(*bname) * i;
593 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
595 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
596 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
597 yaffs_strcpy(obj->shortName, name);
599 obj->shortName[0] = _Y('\0');
602 obj->sum = yaffs_CalcNameSum(name);
605 /*-------------------- TNODES -------------------
607 * List of spare tnodes
608 * The list is hooked together using the first pointer
612 /* yaffs_CreateTnodes creates a bunch more tnodes and
613 * adds them to the tnode free list.
614 * Don't use this function directly
617 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
621 yaffs_Tnode *newTnodes;
625 yaffs_TnodeList *tnl;
630 /* Calculate the tnode size in bytes for variable width tnode support.
631 * Must be a multiple of 32-bits */
632 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
634 /* make these things */
636 newTnodes = YMALLOC(nTnodes * tnodeSize);
637 mem = (__u8 *)newTnodes;
641 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
645 /* Hook them into the free list */
647 for (i = 0; i < nTnodes - 1; i++) {
648 newTnodes[i].internal[0] = &newTnodes[i + 1];
649 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
650 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
654 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
655 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
656 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
658 dev->freeTnodes = newTnodes;
660 /* New hookup for wide tnodes */
661 for(i = 0; i < nTnodes -1; i++) {
662 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
663 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
664 curr->internal[0] = next;
667 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
668 curr->internal[0] = dev->freeTnodes;
669 dev->freeTnodes = (yaffs_Tnode *)mem;
674 dev->nFreeTnodes += nTnodes;
675 dev->nTnodesCreated += nTnodes;
677 /* Now add this bunch of tnodes to a list for freeing up.
678 * NB If we can't add this to the management list it isn't fatal
679 * but it just means we can't free this bunch of tnodes later.
682 tnl = YMALLOC(sizeof(yaffs_TnodeList));
686 ("yaffs: Could not add tnodes to management list" TENDSTR)));
689 tnl->tnodes = newTnodes;
690 tnl->next = dev->allocatedTnodeList;
691 dev->allocatedTnodeList = tnl;
694 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
699 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
701 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
703 yaffs_Tnode *tn = NULL;
705 /* If there are none left make more */
706 if (!dev->freeTnodes) {
707 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
710 if (dev->freeTnodes) {
711 tn = dev->freeTnodes;
712 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
713 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
714 /* Hoosterman, this thing looks like it isn't in the list */
715 T(YAFFS_TRACE_ALWAYS,
716 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
719 dev->freeTnodes = dev->freeTnodes->internal[0];
726 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
728 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
731 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
736 /* FreeTnode frees up a tnode and puts it back on the free list */
737 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
740 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
741 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
742 /* Hoosterman, this thing looks like it is already in the list */
743 T(YAFFS_TRACE_ALWAYS,
744 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
746 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
748 tn->internal[0] = dev->freeTnodes;
749 dev->freeTnodes = tn;
754 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
756 /* Free the list of allocated tnodes */
757 yaffs_TnodeList *tmp;
759 while (dev->allocatedTnodeList) {
760 tmp = dev->allocatedTnodeList->next;
762 YFREE(dev->allocatedTnodeList->tnodes);
763 YFREE(dev->allocatedTnodeList);
764 dev->allocatedTnodeList = tmp;
768 dev->freeTnodes = NULL;
769 dev->nFreeTnodes = 0;
772 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
774 dev->allocatedTnodeList = NULL;
775 dev->freeTnodes = NULL;
776 dev->nFreeTnodes = 0;
777 dev->nTnodesCreated = 0;
782 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
784 __u32 *map = (__u32 *)tn;
790 pos &= YAFFS_TNODES_LEVEL0_MASK;
791 val >>= dev->chunkGroupBits;
793 bitInMap = pos * dev->tnodeWidth;
794 wordInMap = bitInMap /32;
795 bitInWord = bitInMap & (32 -1);
797 mask = dev->tnodeMask << bitInWord;
799 map[wordInMap] &= ~mask;
800 map[wordInMap] |= (mask & (val << bitInWord));
802 if(dev->tnodeWidth > (32-bitInWord)) {
803 bitInWord = (32 - bitInWord);
805 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
806 map[wordInMap] &= ~mask;
807 map[wordInMap] |= (mask & (val >> bitInWord));
811 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
813 __u32 *map = (__u32 *)tn;
819 pos &= YAFFS_TNODES_LEVEL0_MASK;
821 bitInMap = pos * dev->tnodeWidth;
822 wordInMap = bitInMap /32;
823 bitInWord = bitInMap & (32 -1);
825 val = map[wordInMap] >> bitInWord;
827 if(dev->tnodeWidth > (32-bitInWord)) {
828 bitInWord = (32 - bitInWord);
830 val |= (map[wordInMap] << bitInWord);
833 val &= dev->tnodeMask;
834 val <<= dev->chunkGroupBits;
839 /* ------------------- End of individual tnode manipulation -----------------*/
841 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
842 * The look up tree is represented by the top tnode and the number of topLevel
843 * in the tree. 0 means only the level 0 tnode is in the tree.
846 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
847 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
848 yaffs_FileStructure * fStruct,
852 yaffs_Tnode *tn = fStruct->top;
854 int requiredTallness;
855 int level = fStruct->topLevel;
857 /* Check sane level and chunk Id */
858 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
862 if (chunkId > YAFFS_MAX_CHUNK_ID) {
866 /* First check we're tall enough (ie enough topLevel) */
868 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
869 requiredTallness = 0;
871 i >>= YAFFS_TNODES_INTERNAL_BITS;
875 if (requiredTallness > fStruct->topLevel) {
876 /* Not tall enough, so we can't find it, return NULL. */
880 /* Traverse down to level 0 */
881 while (level > 0 && tn) {
884 ( YAFFS_TNODES_LEVEL0_BITS +
886 YAFFS_TNODES_INTERNAL_BITS)
888 YAFFS_TNODES_INTERNAL_MASK];
896 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
897 * This happens in two steps:
898 * 1. If the tree isn't tall enough, then make it taller.
899 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
901 * Used when modifying the tree.
903 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
904 * be plugged into the ttree.
907 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
908 yaffs_FileStructure * fStruct,
910 yaffs_Tnode *passedTn)
913 int requiredTallness;
921 /* Check sane level and page Id */
922 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
926 if (chunkId > YAFFS_MAX_CHUNK_ID) {
930 /* First check we're tall enough (ie enough topLevel) */
932 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
933 requiredTallness = 0;
935 x >>= YAFFS_TNODES_INTERNAL_BITS;
940 if (requiredTallness > fStruct->topLevel) {
941 /* Not tall enough,gotta make the tree taller */
942 for (i = fStruct->topLevel; i < requiredTallness; i++) {
944 tn = yaffs_GetTnode(dev);
947 tn->internal[0] = fStruct->top;
951 (TSTR("yaffs: no more tnodes" TENDSTR)));
955 fStruct->topLevel = requiredTallness;
958 /* Traverse down to level 0, adding anything we need */
960 l = fStruct->topLevel;
964 while (l > 0 && tn) {
966 ( YAFFS_TNODES_LEVEL0_BITS +
967 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
968 YAFFS_TNODES_INTERNAL_MASK;
971 if((l>1) && !tn->internal[x]){
972 /* Add missing non-level-zero tnode */
973 tn->internal[x] = yaffs_GetTnode(dev);
976 /* Looking from level 1 at level 0 */
978 /* If we already have one, then release it.*/
980 yaffs_FreeTnode(dev,tn->internal[x]);
981 tn->internal[x] = passedTn;
983 } else if(!tn->internal[x]) {
984 /* Don't have one, none passed in */
985 tn->internal[x] = yaffs_GetTnode(dev);
989 tn = tn->internal[x];
995 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
996 yaffs_FreeTnode(dev,passedTn);
1003 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1004 yaffs_ExtendedTags * tags, int objectId,
1009 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1010 if (yaffs_CheckChunkBit
1011 (dev, theChunk / dev->nChunksPerBlock,
1012 theChunk % dev->nChunksPerBlock)) {
1013 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1015 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1027 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1028 * chunks and tnodes in the file
1029 * Returns 1 if the tree was deleted.
1030 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1033 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1034 int chunkOffset, int *limit)
1039 yaffs_ExtendedTags tags;
1041 yaffs_Device *dev = in->myDev;
1048 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1050 if (tn->internal[i]) {
1051 if (limit && (*limit) < 0) {
1055 yaffs_DeleteWorker(in,
1063 YAFFS_TNODES_INTERNAL_BITS)
1068 yaffs_FreeTnode(dev,
1071 tn->internal[i] = NULL;
1076 return (allDone) ? 1 : 0;
1077 } else if (level == 0) {
1080 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1082 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1087 YAFFS_TNODES_LEVEL0_BITS) + i;
1090 yaffs_FindChunkInGroup(dev,
1096 if (foundChunk > 0) {
1097 yaffs_DeleteChunk(dev,
1102 *limit = *limit - 1;
1110 yaffs_PutLevel0Tnode(dev,tn,i,0);
1114 return (i < 0) ? 1 : 0;
1124 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1127 yaffs_BlockInfo *theBlock;
1129 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1131 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1133 theBlock->softDeletions++;
1138 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1139 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1141 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1144 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1145 __u32 level, int chunkOffset)
1150 yaffs_Device *dev = in->myDev;
1155 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1157 if (tn->internal[i]) {
1159 yaffs_SoftDeleteWorker(in,
1165 YAFFS_TNODES_INTERNAL_BITS)
1168 yaffs_FreeTnode(dev,
1171 tn->internal[i] = NULL;
1173 /* Hoosterman... how could this happen? */
1177 return (allDone) ? 1 : 0;
1178 } else if (level == 0) {
1180 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1181 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1183 /* Note this does not find the real chunk, only the chunk group.
1184 * We make an assumption that a chunk group is not larger than
1187 yaffs_SoftDeleteChunk(dev, theChunk);
1188 yaffs_PutLevel0Tnode(dev,tn,i,0);
1202 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1205 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1206 if (obj->nDataChunks <= 0) {
1207 /* Empty file with no duplicate object headers, just delete it immediately */
1208 yaffs_FreeTnode(obj->myDev,
1209 obj->variant.fileVariant.top);
1210 obj->variant.fileVariant.top = NULL;
1211 T(YAFFS_TRACE_TRACING,
1212 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1214 yaffs_DoGenericObjectDeletion(obj);
1216 yaffs_SoftDeleteWorker(obj,
1217 obj->variant.fileVariant.top,
1218 obj->variant.fileVariant.
1220 obj->softDeleted = 1;
1225 /* Pruning removes any part of the file structure tree that is beyond the
1226 * bounds of the file (ie that does not point to chunks).
1228 * A file should only get pruned when its size is reduced.
1230 * Before pruning, the chunks must be pulled from the tree and the
1231 * level 0 tnode entries must be zeroed out.
1232 * Could also use this for file deletion, but that's probably better handled
1233 * by a special case.
1236 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1237 __u32 level, int del0)
1245 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1246 if (tn->internal[i] && level > 0) {
1248 yaffs_PruneWorker(dev, tn->internal[i],
1250 (i == 0) ? del0 : 1);
1253 if (tn->internal[i]) {
1258 if (hasData == 0 && del0) {
1259 /* Free and return NULL */
1261 yaffs_FreeTnode(dev, tn);
1271 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1272 yaffs_FileStructure * fStruct)
1279 if (fStruct->topLevel > 0) {
1281 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1283 /* Now we have a tree with all the non-zero branches NULL but the height
1284 * is the same as it was.
1285 * Let's see if we can trim internal tnodes to shorten the tree.
1286 * We can do this if only the 0th element in the tnode is in use
1287 * (ie all the non-zero are NULL)
1290 while (fStruct->topLevel && !done) {
1294 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1295 if (tn->internal[i]) {
1301 fStruct->top = tn->internal[0];
1302 fStruct->topLevel--;
1303 yaffs_FreeTnode(dev, tn);
1313 /*-------------------- End of File Structure functions.-------------------*/
1315 /* yaffs_CreateFreeObjects creates a bunch more objects and
1316 * adds them to the object free list.
1318 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1321 yaffs_Object *newObjects;
1322 yaffs_ObjectList *list;
1327 /* make these things */
1328 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1331 T(YAFFS_TRACE_ALLOCATE,
1332 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1336 /* Hook them into the free list */
1337 for (i = 0; i < nObjects - 1; i++) {
1338 newObjects[i].siblings.next =
1339 (struct list_head *)(&newObjects[i + 1]);
1342 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1343 dev->freeObjects = newObjects;
1344 dev->nFreeObjects += nObjects;
1345 dev->nObjectsCreated += nObjects;
1347 /* Now add this bunch of Objects to a list for freeing up. */
1349 list = YMALLOC(sizeof(yaffs_ObjectList));
1351 T(YAFFS_TRACE_ALLOCATE,
1352 (TSTR("Could not add objects to management list" TENDSTR)));
1354 list->objects = newObjects;
1355 list->next = dev->allocatedObjectList;
1356 dev->allocatedObjectList = list;
1363 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1364 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1366 yaffs_Object *tn = NULL;
1368 /* If there are none left make more */
1369 if (!dev->freeObjects) {
1370 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1373 if (dev->freeObjects) {
1374 tn = dev->freeObjects;
1376 (yaffs_Object *) (dev->freeObjects->siblings.next);
1377 dev->nFreeObjects--;
1379 /* Now sweeten it up... */
1381 memset(tn, 0, sizeof(yaffs_Object));
1384 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1385 INIT_LIST_HEAD(&(tn->hardLinks));
1386 INIT_LIST_HEAD(&(tn->hashLink));
1387 INIT_LIST_HEAD(&tn->siblings);
1389 /* Add it to the lost and found directory.
1390 * NB Can't put root or lostNFound in lostNFound so
1391 * check if lostNFound exists first
1393 if (dev->lostNFoundDir) {
1394 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1401 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1406 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1408 obj->fake = 1; /* it is fake so it has no NAND presence... */
1409 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1410 obj->unlinkAllowed = 0; /* ... or unlink it */
1413 obj->yst_mode = mode;
1415 obj->chunkId = 0; /* Not a valid chunk. */
1422 static void yaffs_UnhashObject(yaffs_Object * tn)
1425 yaffs_Device *dev = tn->myDev;
1427 /* If it is still linked into the bucket list, free from the list */
1428 if (!list_empty(&tn->hashLink)) {
1429 list_del_init(&tn->hashLink);
1430 bucket = yaffs_HashFunction(tn->objectId);
1431 dev->objectBucket[bucket].count--;
1436 /* FreeObject frees up a Object and puts it back on the free list */
1437 static void yaffs_FreeObject(yaffs_Object * tn)
1440 yaffs_Device *dev = tn->myDev;
1444 /* We're still hooked up to a cached inode.
1445 * Don't delete now, but mark for later deletion
1447 tn->deferedFree = 1;
1452 yaffs_UnhashObject(tn);
1454 /* Link into the free list. */
1455 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1456 dev->freeObjects = tn;
1457 dev->nFreeObjects++;
1462 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1464 if (obj->deferedFree) {
1465 yaffs_FreeObject(obj);
1471 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1473 /* Free the list of allocated Objects */
1475 yaffs_ObjectList *tmp;
1477 while (dev->allocatedObjectList) {
1478 tmp = dev->allocatedObjectList->next;
1479 YFREE(dev->allocatedObjectList->objects);
1480 YFREE(dev->allocatedObjectList);
1482 dev->allocatedObjectList = tmp;
1485 dev->freeObjects = NULL;
1486 dev->nFreeObjects = 0;
1489 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1493 dev->allocatedObjectList = NULL;
1494 dev->freeObjects = NULL;
1495 dev->nFreeObjects = 0;
1497 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1498 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1499 dev->objectBucket[i].count = 0;
1504 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1509 int lowest = 999999;
1511 /* First let's see if we can find one that's empty. */
1513 for (i = 0; i < 10 && lowest > 0; i++) {
1515 x %= YAFFS_NOBJECT_BUCKETS;
1516 if (dev->objectBucket[x].count < lowest) {
1517 lowest = dev->objectBucket[x].count;
1523 /* If we didn't find an empty list, then try
1524 * looking a bit further for a short one
1527 for (i = 0; i < 10 && lowest > 3; i++) {
1529 x %= YAFFS_NOBJECT_BUCKETS;
1530 if (dev->objectBucket[x].count < lowest) {
1531 lowest = dev->objectBucket[x].count;
1540 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1542 int bucket = yaffs_FindNiceObjectBucket(dev);
1544 /* Now find an object value that has not already been taken
1545 * by scanning the list.
1549 struct list_head *i;
1551 __u32 n = (__u32) bucket;
1553 /* yaffs_CheckObjectHashSanity(); */
1557 n += YAFFS_NOBJECT_BUCKETS;
1558 if (1 || dev->objectBucket[bucket].count > 0) {
1559 list_for_each(i, &dev->objectBucket[bucket].list) {
1560 /* If there is already one in the list */
1562 && list_entry(i, yaffs_Object,
1563 hashLink)->objectId == n) {
1574 static void yaffs_HashObject(yaffs_Object * in)
1576 int bucket = yaffs_HashFunction(in->objectId);
1577 yaffs_Device *dev = in->myDev;
1579 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1580 dev->objectBucket[bucket].count++;
1584 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1586 int bucket = yaffs_HashFunction(number);
1587 struct list_head *i;
1590 list_for_each(i, &dev->objectBucket[bucket].list) {
1591 /* Look if it is in the list */
1593 in = list_entry(i, yaffs_Object, hashLink);
1594 if (in->objectId == number) {
1596 /* Don't tell the VFS about this one if it is defered free */
1597 if (in->deferedFree)
1609 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1610 yaffs_ObjectType type)
1613 yaffs_Object *theObject;
1616 number = yaffs_CreateNewObjectNumber(dev);
1619 theObject = yaffs_AllocateEmptyObject(dev);
1622 theObject->fake = 0;
1623 theObject->renameAllowed = 1;
1624 theObject->unlinkAllowed = 1;
1625 theObject->objectId = number;
1626 yaffs_HashObject(theObject);
1627 theObject->variantType = type;
1628 #ifdef CONFIG_YAFFS_WINCE
1629 yfsd_WinFileTimeNow(theObject->win_atime);
1630 theObject->win_ctime[0] = theObject->win_mtime[0] =
1631 theObject->win_atime[0];
1632 theObject->win_ctime[1] = theObject->win_mtime[1] =
1633 theObject->win_atime[1];
1637 theObject->yst_atime = theObject->yst_mtime =
1638 theObject->yst_ctime = Y_CURRENT_TIME;
1641 case YAFFS_OBJECT_TYPE_FILE:
1642 theObject->variant.fileVariant.fileSize = 0;
1643 theObject->variant.fileVariant.scannedFileSize = 0;
1644 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1645 theObject->variant.fileVariant.topLevel = 0;
1646 theObject->variant.fileVariant.top =
1647 yaffs_GetTnode(dev);
1649 case YAFFS_OBJECT_TYPE_DIRECTORY:
1650 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1653 case YAFFS_OBJECT_TYPE_SYMLINK:
1654 case YAFFS_OBJECT_TYPE_HARDLINK:
1655 case YAFFS_OBJECT_TYPE_SPECIAL:
1656 /* No action required */
1658 case YAFFS_OBJECT_TYPE_UNKNOWN:
1659 /* todo this should not happen */
1667 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1669 yaffs_ObjectType type)
1671 yaffs_Object *theObject = NULL;
1674 theObject = yaffs_FindObjectByNumber(dev, number);
1678 theObject = yaffs_CreateNewObject(dev, number, type);
1686 static YCHAR *yaffs_CloneString(const YCHAR * str)
1688 YCHAR *newStr = NULL;
1691 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1692 yaffs_strcpy(newStr, str);
1700 * Mknod (create) a new object.
1701 * equivalentObject only has meaning for a hard link;
1702 * aliasString only has meaning for a sumlink.
1703 * rdev only has meaning for devices (a subset of special objects)
1706 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1707 yaffs_Object * parent,
1712 yaffs_Object * equivalentObject,
1713 const YCHAR * aliasString, __u32 rdev)
1717 yaffs_Device *dev = parent->myDev;
1719 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1720 if (yaffs_FindObjectByName(parent, name)) {
1724 in = yaffs_CreateNewObject(dev, -1, type);
1729 in->variantType = type;
1731 in->yst_mode = mode;
1733 #ifdef CONFIG_YAFFS_WINCE
1734 yfsd_WinFileTimeNow(in->win_atime);
1735 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1736 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1739 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1741 in->yst_rdev = rdev;
1745 in->nDataChunks = 0;
1747 yaffs_SetObjectName(in, name);
1750 yaffs_AddObjectToDirectory(parent, in);
1752 in->myDev = parent->myDev;
1755 case YAFFS_OBJECT_TYPE_SYMLINK:
1756 in->variant.symLinkVariant.alias =
1757 yaffs_CloneString(aliasString);
1759 case YAFFS_OBJECT_TYPE_HARDLINK:
1760 in->variant.hardLinkVariant.equivalentObject =
1762 in->variant.hardLinkVariant.equivalentObjectId =
1763 equivalentObject->objectId;
1764 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1766 case YAFFS_OBJECT_TYPE_FILE:
1767 case YAFFS_OBJECT_TYPE_DIRECTORY:
1768 case YAFFS_OBJECT_TYPE_SPECIAL:
1769 case YAFFS_OBJECT_TYPE_UNKNOWN:
1774 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1775 /* Could not create the object header, fail the creation */
1776 yaffs_DestroyObject(in);
1785 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1786 __u32 mode, __u32 uid, __u32 gid)
1788 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1789 uid, gid, NULL, NULL, 0);
1792 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1793 __u32 mode, __u32 uid, __u32 gid)
1795 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1796 mode, uid, gid, NULL, NULL, 0);
1799 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1800 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1802 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1803 uid, gid, NULL, NULL, rdev);
1806 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1807 __u32 mode, __u32 uid, __u32 gid,
1808 const YCHAR * alias)
1810 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1811 uid, gid, NULL, alias, 0);
1814 /* yaffs_Link returns the object id of the equivalent object.*/
1815 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1816 yaffs_Object * equivalentObject)
1818 /* Get the real object in case we were fed a hard link as an equivalent object */
1819 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1821 if (yaffs_MknodObject
1822 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1823 equivalentObject, NULL, 0)) {
1824 return equivalentObject;
1831 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1832 const YCHAR * newName, int force, int shadows)
1837 yaffs_Object *existingTarget;
1839 if (newDir == NULL) {
1840 newDir = obj->parent; /* use the old directory */
1843 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1844 T(YAFFS_TRACE_ALWAYS,
1846 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1851 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1852 if (obj->myDev->isYaffs2) {
1853 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1855 unlinkOp = (newDir == obj->myDev->unlinkedDir
1856 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1859 deleteOp = (newDir == obj->myDev->deletedDir);
1861 existingTarget = yaffs_FindObjectByName(newDir, newName);
1863 /* If the object is a file going into the unlinked directory,
1864 * then it is OK to just stuff it in since duplicate names are allowed.
1865 * else only proceed if the new name does not exist and if we're putting
1866 * it into a directory.
1873 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1874 yaffs_SetObjectName(obj, newName);
1877 yaffs_AddObjectToDirectory(newDir, obj);
1882 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1883 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1890 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1891 yaffs_Object * newDir, const YCHAR * newName)
1894 yaffs_Object *existingTarget;
1897 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1898 /* Special case for case insemsitive systems (eg. WinCE).
1899 * While look-up is case insensitive, the name isn't.
1900 * Therefore we might want to change x.txt to X.txt
1902 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1907 obj = yaffs_FindObjectByName(oldDir, oldName);
1908 /* Check new name to long. */
1909 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1910 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1913 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1914 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1918 if (obj && obj->renameAllowed) {
1920 /* Now do the handling for an existing target, if there is one */
1922 existingTarget = yaffs_FindObjectByName(newDir, newName);
1923 if (existingTarget &&
1924 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1925 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1926 /* There is a target that is a non-empty directory, so we fail */
1927 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1928 } else if (existingTarget && existingTarget != obj) {
1929 /* Nuke the target first, using shadowing,
1930 * but only if it isn't the same object
1932 yaffs_ChangeObjectName(obj, newDir, newName, force,
1933 existingTarget->objectId);
1934 yaffs_UnlinkObject(existingTarget);
1937 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1942 /*------------------------- Block Management and Page Allocation ----------------*/
1944 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1946 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1948 dev->allocationBlock = -1; /* force it to get a new one */
1950 /* Todo we're assuming the malloc will pass. */
1951 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1952 if(!dev->blockInfo){
1953 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1954 dev->blockInfoAlt = 1;
1957 dev->blockInfoAlt = 0;
1959 /* Set up dynamic blockinfo stuff. */
1960 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
1961 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1962 if(!dev->chunkBits){
1963 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1964 dev->chunkBitsAlt = 1;
1967 dev->chunkBitsAlt = 0;
1969 if (dev->blockInfo && dev->chunkBits) {
1970 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1971 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1979 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1981 if(dev->blockInfoAlt)
1982 YFREE_ALT(dev->blockInfo);
1984 YFREE(dev->blockInfo);
1985 dev->blockInfoAlt = 0;
1987 dev->blockInfo = NULL;
1989 if(dev->chunkBitsAlt)
1990 YFREE_ALT(dev->chunkBits);
1992 YFREE(dev->chunkBits);
1993 dev->chunkBitsAlt = 0;
1994 dev->chunkBits = NULL;
1997 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1998 yaffs_BlockInfo * bi)
2005 return 1; /* disqualification only applies to yaffs2. */
2007 if (!bi->hasShrinkHeader)
2008 return 1; /* can gc */
2010 /* Find the oldest dirty sequence number if we don't know it and save it
2011 * so we don't have to keep recomputing it.
2013 if (!dev->oldestDirtySequence) {
2014 seq = dev->sequenceNumber;
2016 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2018 b = yaffs_GetBlockInfo(dev, i);
2019 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2020 (b->pagesInUse - b->softDeletions) <
2021 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2022 seq = b->sequenceNumber;
2025 dev->oldestDirtySequence = seq;
2028 /* Can't do gc of this block if there are any blocks older than this one that have
2031 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2035 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2036 * for garbage collection.
2039 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2043 int b = dev->currentDirtyChecker;
2050 yaffs_BlockInfo *bi;
2051 static int nonAggressiveSkip = 0;
2052 int pendingPrioritisedExist = 0;
2054 /* First let's see if we need to grab a prioritised block */
2055 if(dev->hasPendingPrioritisedGCs){
2056 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2058 bi = yaffs_GetBlockInfo(dev, i);
2059 if(bi->gcPrioritise) {
2060 pendingPrioritisedExist = 1;
2061 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2062 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2063 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2066 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2071 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2072 dev->hasPendingPrioritisedGCs = 0;
2075 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2077 * else (we're doing a leasurely gc), then we only bother to do this if the
2078 * block has only a few pages in use.
2081 nonAggressiveSkip--;
2083 if (!aggressive && (nonAggressiveSkip > 0)) {
2089 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2093 dev->internalEndBlock - dev->internalStartBlock + 1;
2096 dev->internalEndBlock - dev->internalStartBlock + 1;
2097 iterations = iterations / 16;
2098 if (iterations > 200) {
2103 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2105 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2106 b = dev->internalStartBlock;
2109 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2110 T(YAFFS_TRACE_ERROR,
2111 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2115 bi = yaffs_GetBlockInfo(dev, b);
2118 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2125 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2126 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2127 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2129 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2133 dev->currentDirtyChecker = b;
2137 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2138 dev->nChunksPerBlock - pagesInUse,prioritised));
2141 dev->oldestDirtySequence = 0;
2144 nonAggressiveSkip = 4;
2150 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2152 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2156 /* If the block is still healthy erase it and mark as clean.
2157 * If the block has had a data failure, then retire it.
2160 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2161 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2162 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2164 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2166 if (!bi->needsRetiring) {
2167 yaffs_InvalidateCheckpoint(dev);
2168 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2170 dev->nErasureFailures++;
2171 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2172 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2176 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2178 for (i = 0; i < dev->nChunksPerBlock; i++) {
2179 if (!yaffs_CheckChunkErased
2180 (dev, blockNo * dev->nChunksPerBlock + i)) {
2181 T(YAFFS_TRACE_ERROR,
2183 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2184 TENDSTR), blockNo, i));
2190 /* Clean it up... */
2191 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2192 dev->nErasedBlocks++;
2194 bi->softDeletions = 0;
2195 bi->hasShrinkHeader = 0;
2196 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2197 bi->gcPrioritise = 0;
2198 yaffs_ClearChunkBits(dev, blockNo);
2200 T(YAFFS_TRACE_ERASE,
2201 (TSTR("Erased block %d" TENDSTR), blockNo));
2203 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2205 yaffs_RetireBlock(dev, blockNo);
2206 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2207 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2211 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2215 yaffs_BlockInfo *bi;
2217 if (dev->nErasedBlocks < 1) {
2218 /* Hoosterman we've got a problem.
2219 * Can't get space to gc
2221 T(YAFFS_TRACE_ERROR,
2222 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2227 /* Find an empty block. */
2229 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2230 dev->allocationBlockFinder++;
2231 if (dev->allocationBlockFinder < dev->internalStartBlock
2232 || dev->allocationBlockFinder > dev->internalEndBlock) {
2233 dev->allocationBlockFinder = dev->internalStartBlock;
2236 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2238 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2239 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2240 dev->sequenceNumber++;
2241 bi->sequenceNumber = dev->sequenceNumber;
2242 dev->nErasedBlocks--;
2243 T(YAFFS_TRACE_ALLOCATE,
2244 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2245 dev->allocationBlockFinder, dev->sequenceNumber,
2246 dev->nErasedBlocks));
2247 return dev->allocationBlockFinder;
2251 T(YAFFS_TRACE_ALWAYS,
2253 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2254 TENDSTR), dev->nErasedBlocks));
2260 // Check if there's space to allocate...
2261 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2262 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2265 int reservedBlocks = dev->nReservedBlocks;
2266 int checkpointBlocks;
2268 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2269 if(checkpointBlocks < 0)
2270 checkpointBlocks = 0;
2272 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2274 return (dev->nFreeChunks > reservedChunks);
2277 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2280 yaffs_BlockInfo *bi;
2282 if (dev->allocationBlock < 0) {
2283 /* Get next block to allocate off */
2284 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2285 dev->allocationPage = 0;
2288 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2289 /* Not enough space to allocate unless we're allowed to use the reserve. */
2293 if (dev->nErasedBlocks < dev->nReservedBlocks
2294 && dev->allocationPage == 0) {
2295 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2298 /* Next page please.... */
2299 if (dev->allocationBlock >= 0) {
2300 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2302 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2303 dev->allocationPage;
2305 yaffs_SetChunkBit(dev, dev->allocationBlock,
2306 dev->allocationPage);
2308 dev->allocationPage++;
2312 /* If the block is full set the state to full */
2313 if (dev->allocationPage >= dev->nChunksPerBlock) {
2314 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2315 dev->allocationBlock = -1;
2324 T(YAFFS_TRACE_ERROR,
2325 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2330 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2334 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2336 if (dev->allocationBlock > 0) {
2337 n += (dev->nChunksPerBlock - dev->allocationPage);
2344 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2350 int retVal = YAFFS_OK;
2353 int isCheckpointBlock;
2355 int chunksBefore = yaffs_GetErasedChunks(dev);
2358 yaffs_ExtendedTags tags;
2360 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2362 yaffs_Object *object;
2364 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2366 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2368 T(YAFFS_TRACE_TRACING,
2369 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2370 bi->pagesInUse, bi->hasShrinkHeader));
2372 /*yaffs_VerifyFreeChunks(dev); */
2374 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2376 /* Take off the number of soft deleted entries because
2377 * they're going to get really deleted during GC.
2379 dev->nFreeChunks -= bi->softDeletions;
2383 if (isCheckpointBlock ||
2384 !yaffs_StillSomeChunkBits(dev, block)) {
2385 T(YAFFS_TRACE_TRACING,
2387 ("Collecting block %d that has no chunks in use" TENDSTR),
2389 yaffs_BlockBecameDirty(dev, block);
2392 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2394 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2395 chunkInBlock < dev->nChunksPerBlock
2396 && yaffs_StillSomeChunkBits(dev, block);
2397 chunkInBlock++, oldChunk++) {
2398 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2400 /* This page is in use and might need to be copied off */
2404 yaffs_InitialiseTags(&tags);
2406 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2410 yaffs_FindObjectByNumber(dev,
2413 T(YAFFS_TRACE_GC_DETAIL,
2415 ("Collecting page %d, %d %d %d " TENDSTR),
2416 chunkInBlock, tags.objectId, tags.chunkId,
2420 T(YAFFS_TRACE_ERROR,
2422 ("page %d in gc has no object "
2423 TENDSTR), oldChunk));
2426 if (object && object->deleted
2427 && tags.chunkId != 0) {
2428 /* Data chunk in a deleted file, throw it away
2429 * It's a soft deleted data chunk,
2430 * No need to copy this, just forget about it and
2431 * fix up the object.
2434 object->nDataChunks--;
2436 if (object->nDataChunks <= 0) {
2437 /* remeber to clean up the object */
2438 dev->gcCleanupList[cleanups] =
2444 /* Todo object && object->deleted && object->nDataChunks == 0 */
2446 /* Deleted object header with no data chunks.
2447 * Can be discarded and the file deleted.
2449 object->chunkId = 0;
2450 yaffs_FreeTnode(object->myDev,
2453 object->variant.fileVariant.top = NULL;
2454 yaffs_DoGenericObjectDeletion(object);
2456 } else if (object) {
2457 /* It's either a data chunk in a live file or
2458 * an ObjectHeader, so we're interested in it.
2459 * NB Need to keep the ObjectHeaders of deleted files
2460 * until the whole file has been deleted off
2462 tags.serialNumber++;
2466 if (tags.chunkId == 0) {
2467 /* It is an object Id,
2468 * We need to nuke the shrinkheader flags first
2469 * We no longer want the shrinkHeader flag since its work is done
2470 * and if it is left in place it will mess up scanning.
2471 * Also, clear out any shadowing stuff
2474 yaffs_ObjectHeader *oh;
2475 oh = (yaffs_ObjectHeader *)buffer;
2477 oh->shadowsObject = -1;
2478 tags.extraShadows = 0;
2479 tags.extraIsShrinkHeader = 0;
2483 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2486 retVal = YAFFS_FAIL;
2489 /* Ok, now fix up the Tnodes etc. */
2491 if (tags.chunkId == 0) {
2493 object->chunkId = newChunk;
2494 object->serial = tags.serialNumber;
2496 /* It's a data chunk */
2497 yaffs_PutChunkIntoFile
2505 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2510 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2513 /* Do any required cleanups */
2514 for (i = 0; i < cleanups; i++) {
2515 /* Time to delete the file too */
2517 yaffs_FindObjectByNumber(dev,
2518 dev->gcCleanupList[i]);
2520 yaffs_FreeTnode(dev,
2521 object->variant.fileVariant.
2523 object->variant.fileVariant.top = NULL;
2526 ("yaffs: About to finally delete object %d"
2527 TENDSTR), object->objectId));
2528 yaffs_DoGenericObjectDeletion(object);
2529 object->myDev->nDeletedFiles--;
2536 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2539 ("gc did not increase free chunks before %d after %d"
2540 TENDSTR), chunksBefore, chunksAfter));
2548 /* New garbage collector
2549 * If we're very low on erased blocks then we do aggressive garbage collection
2550 * otherwise we do "leasurely" garbage collection.
2551 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2552 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2554 * The idea is to help clear out space in a more spread-out manner.
2555 * Dunno if it really does anything useful.
2557 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2561 int gcOk = YAFFS_OK;
2564 int checkpointBlockAdjust;
2566 if (dev->isDoingGC) {
2567 /* Bail out so we don't get recursive gc */
2571 /* This loop should pass the first time.
2572 * We'll only see looping here if the erase of the collected block fails.
2578 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2579 if(checkpointBlockAdjust < 0)
2580 checkpointBlockAdjust = 0;
2582 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2583 /* We need a block soon...*/
2586 /* We're in no hurry */
2590 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2593 dev->garbageCollections++;
2595 dev->passiveGarbageCollections++;
2600 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2601 dev->nErasedBlocks, aggressive));
2603 gcOk = yaffs_GarbageCollectBlock(dev, block);
2606 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2609 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2610 TENDSTR), dev->nErasedBlocks, maxTries, block));
2612 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2615 return aggressive ? gcOk : YAFFS_OK;
2618 /*------------------------- TAGS --------------------------------*/
2620 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2623 return (tags->chunkId == chunkInObject &&
2624 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2629 /*-------------------- Data file manipulation -----------------*/
2631 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2632 yaffs_ExtendedTags * tags)
2634 /*Get the Tnode, then get the level 0 offset chunk offset */
2637 yaffs_ExtendedTags localTags;
2640 yaffs_Device *dev = in->myDev;
2643 /* Passed a NULL, so use our own tags space */
2647 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2650 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2653 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2659 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2660 yaffs_ExtendedTags * tags)
2662 /* Get the Tnode, then get the level 0 offset chunk offset */
2665 yaffs_ExtendedTags localTags;
2667 yaffs_Device *dev = in->myDev;
2671 /* Passed a NULL, so use our own tags space */
2675 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2679 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2682 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2685 /* Delete the entry in the filestructure (if found) */
2687 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2690 /*T(("No level 0 found for %d\n", chunkInInode)); */
2694 /* T(("Could not find %d to delete\n",chunkInInode)); */
2699 #ifdef YAFFS_PARANOID
2701 static int yaffs_CheckFileSanity(yaffs_Object * in)
2709 yaffs_Tags localTags;
2710 yaffs_Tags *tags = &localTags;
2714 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2715 /* T(("Object not a file\n")); */
2719 objId = in->objectId;
2720 fSize = in->variant.fileVariant.fileSize;
2722 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
2724 for (chunk = 1; chunk <= nChunks; chunk++) {
2725 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2730 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2732 if (yaffs_CheckChunkBits
2733 (dev, theChunk / dev->nChunksPerBlock,
2734 theChunk % dev->nChunksPerBlock)) {
2736 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2740 (tags, in->objectId, chunk, chunkDeleted)) {
2750 /* T(("No level 0 found for %d\n", chunk)); */
2754 return failed ? YAFFS_FAIL : YAFFS_OK;
2759 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2760 int chunkInNAND, int inScan)
2762 /* NB inScan is zero unless scanning.
2763 * For forward scanning, inScan is > 0;
2764 * for backward scanning inScan is < 0
2768 yaffs_Device *dev = in->myDev;
2770 yaffs_ExtendedTags existingTags;
2771 yaffs_ExtendedTags newTags;
2772 unsigned existingSerial, newSerial;
2774 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2775 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2776 * If it is not during Scanning then something went wrong!
2779 T(YAFFS_TRACE_ERROR,
2781 ("yaffs tragedy:attempt to put data chunk into a non-file"
2786 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2790 tn = yaffs_AddOrFindLevel0Tnode(dev,
2791 &in->variant.fileVariant,
2798 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2801 /* If we're scanning then we need to test for duplicates
2802 * NB This does not need to be efficient since it should only ever
2803 * happen when the power fails during a write, then only one
2804 * chunk should ever be affected.
2806 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2807 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2810 if (existingChunk != 0) {
2811 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2812 * thus we have to do a FindChunkInFile to get the real chunk id.
2814 * We have a duplicate now we need to decide which one to use:
2816 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2817 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2818 * YAFFS1: Get both sets of tags and compare serial numbers.
2822 /* Only do this for forward scanning */
2823 yaffs_ReadChunkWithTagsFromNAND(dev,
2827 /* Do a proper find */
2829 yaffs_FindChunkInFile(in, chunkInInode,
2833 if (existingChunk <= 0) {
2834 /*Hoosterman - how did this happen? */
2836 T(YAFFS_TRACE_ERROR,
2838 ("yaffs tragedy: existing chunk < 0 in scan"
2843 /* NB The deleted flags should be false, otherwise the chunks will
2844 * not be loaded during a scan
2847 newSerial = newTags.serialNumber;
2848 existingSerial = existingTags.serialNumber;
2851 (in->myDev->isYaffs2 ||
2852 existingChunk <= 0 ||
2853 ((existingSerial + 1) & 3) == newSerial)) {
2854 /* Forward scanning.
2856 * Delete the old one and drop through to update the tnode
2858 yaffs_DeleteChunk(dev, existingChunk, 1,
2861 /* Backward scanning or we want to use the existing one
2863 * Delete the new one and return early so that the tnode isn't changed
2865 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2873 if (existingChunk == 0) {
2877 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2882 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2885 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2887 if (chunkInNAND >= 0) {
2888 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2891 T(YAFFS_TRACE_NANDACCESS,
2892 (TSTR("Chunk %d not found zero instead" TENDSTR),
2894 /* get sane (zero) data if you read a hole */
2895 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2901 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2905 yaffs_ExtendedTags tags;
2906 yaffs_BlockInfo *bi;
2912 block = chunkId / dev->nChunksPerBlock;
2913 page = chunkId % dev->nChunksPerBlock;
2915 bi = yaffs_GetBlockInfo(dev, block);
2917 T(YAFFS_TRACE_DELETION,
2918 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2921 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2923 yaffs_InitialiseTags(&tags);
2925 tags.chunkDeleted = 1;
2927 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2928 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2930 dev->nUnmarkedDeletions++;
2933 /* Pull out of the management area.
2934 * If the whole block became dirty, this will kick off an erasure.
2936 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2937 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2938 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2939 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2942 yaffs_ClearChunkBit(dev, block, page);
2946 if (bi->pagesInUse == 0 &&
2947 !bi->hasShrinkHeader &&
2948 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2949 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2950 yaffs_BlockBecameDirty(dev, block);
2954 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2959 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2960 const __u8 * buffer, int nBytes,
2963 /* Find old chunk Need to do this to get serial number
2964 * Write new one and patch into tree.
2965 * Invalidate old tags.
2969 yaffs_ExtendedTags prevTags;
2972 yaffs_ExtendedTags newTags;
2974 yaffs_Device *dev = in->myDev;
2976 yaffs_CheckGarbageCollection(dev);
2978 /* Get the previous chunk at this location in the file if it exists */
2979 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2981 /* Set up new tags */
2982 yaffs_InitialiseTags(&newTags);
2984 newTags.chunkId = chunkInInode;
2985 newTags.objectId = in->objectId;
2986 newTags.serialNumber =
2987 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2988 newTags.byteCount = nBytes;
2991 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2994 if (newChunkId >= 0) {
2995 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2997 if (prevChunkId >= 0) {
2998 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3002 yaffs_CheckFileSanity(in);
3008 /* UpdateObjectHeader updates the header on NAND for an object.
3009 * If name is not NULL, then that new name is used.
3011 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3012 int isShrink, int shadows)
3015 yaffs_BlockInfo *bi;
3017 yaffs_Device *dev = in->myDev;
3024 yaffs_ExtendedTags newTags;
3026 __u8 *buffer = NULL;
3027 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3029 yaffs_ObjectHeader *oh = NULL;
3031 if (!in->fake || force) {
3033 yaffs_CheckGarbageCollection(dev);
3035 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3036 oh = (yaffs_ObjectHeader *) buffer;
3038 prevChunkId = in->chunkId;
3040 if (prevChunkId >= 0) {
3041 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3043 memcpy(oldName, oh->name, sizeof(oh->name));
3046 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3048 oh->type = in->variantType;
3049 oh->yst_mode = in->yst_mode;
3050 oh->shadowsObject = shadows;
3052 #ifdef CONFIG_YAFFS_WINCE
3053 oh->win_atime[0] = in->win_atime[0];
3054 oh->win_ctime[0] = in->win_ctime[0];
3055 oh->win_mtime[0] = in->win_mtime[0];
3056 oh->win_atime[1] = in->win_atime[1];
3057 oh->win_ctime[1] = in->win_ctime[1];
3058 oh->win_mtime[1] = in->win_mtime[1];
3060 oh->yst_uid = in->yst_uid;
3061 oh->yst_gid = in->yst_gid;
3062 oh->yst_atime = in->yst_atime;
3063 oh->yst_mtime = in->yst_mtime;
3064 oh->yst_ctime = in->yst_ctime;
3065 oh->yst_rdev = in->yst_rdev;
3068 oh->parentObjectId = in->parent->objectId;
3070 oh->parentObjectId = 0;
3073 if (name && *name) {
3074 memset(oh->name, 0, sizeof(oh->name));
3075 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3076 } else if (prevChunkId) {
3077 memcpy(oh->name, oldName, sizeof(oh->name));
3079 memset(oh->name, 0, sizeof(oh->name));
3082 oh->isShrink = isShrink;
3084 switch (in->variantType) {
3085 case YAFFS_OBJECT_TYPE_UNKNOWN:
3086 /* Should not happen */
3088 case YAFFS_OBJECT_TYPE_FILE:
3090 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3091 || oh->parentObjectId ==
3092 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3093 fileVariant.fileSize;
3095 case YAFFS_OBJECT_TYPE_HARDLINK:
3096 oh->equivalentObjectId =
3097 in->variant.hardLinkVariant.equivalentObjectId;
3099 case YAFFS_OBJECT_TYPE_SPECIAL:
3102 case YAFFS_OBJECT_TYPE_DIRECTORY:
3105 case YAFFS_OBJECT_TYPE_SYMLINK:
3106 yaffs_strncpy(oh->alias,
3107 in->variant.symLinkVariant.alias,
3108 YAFFS_MAX_ALIAS_LENGTH);
3109 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3114 yaffs_InitialiseTags(&newTags);
3116 newTags.chunkId = 0;
3117 newTags.objectId = in->objectId;
3118 newTags.serialNumber = in->serial;
3120 /* Add extra info for file header */
3122 newTags.extraHeaderInfoAvailable = 1;
3123 newTags.extraParentObjectId = oh->parentObjectId;
3124 newTags.extraFileLength = oh->fileSize;
3125 newTags.extraIsShrinkHeader = oh->isShrink;
3126 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3127 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3128 newTags.extraObjectType = in->variantType;
3130 /* Create new chunk in NAND */
3132 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3133 (prevChunkId >= 0) ? 1 : 0);
3135 if (newChunkId >= 0) {
3137 in->chunkId = newChunkId;
3139 if (prevChunkId >= 0) {
3140 yaffs_DeleteChunk(dev, prevChunkId, 1,
3144 if(!yaffs_ObjectHasCachedWriteData(in))
3147 /* If this was a shrink, then mark the block that the chunk lives on */
3149 bi = yaffs_GetBlockInfo(in->myDev,
3150 newChunkId /in->myDev-> nChunksPerBlock);
3151 bi->hasShrinkHeader = 1;
3156 retVal = newChunkId;
3161 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3166 /*------------------------ Short Operations Cache ----------------------------------------
3167 * In many situations where there is no high level buffering (eg WinCE) a lot of
3168 * reads might be short sequential reads, and a lot of writes may be short
3169 * sequential writes. eg. scanning/writing a jpeg file.
3170 * In these cases, a short read/write cache can provide a huge perfomance benefit
3171 * with dumb-as-a-rock code.
3172 * In Linux, the page cache provides read buffering aand the short op cache provides write
3175 * There are a limited number (~10) of cache chunks per device so that we don't
3176 * need a very intelligent search.
3179 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3181 yaffs_Device *dev = obj->myDev;
3183 yaffs_ChunkCache *cache;
3184 int nCaches = obj->myDev->nShortOpCaches;
3186 for(i = 0; i < nCaches; i++){
3187 cache = &dev->srCache[i];
3188 if (cache->object == obj &&
3197 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3199 yaffs_Device *dev = obj->myDev;
3200 int lowest = -99; /* Stop compiler whining. */
3202 yaffs_ChunkCache *cache;
3203 int chunkWritten = 0;
3204 int nCaches = obj->myDev->nShortOpCaches;
3210 /* Find the dirty cache for this object with the lowest chunk id. */
3211 for (i = 0; i < nCaches; i++) {
3212 if (dev->srCache[i].object == obj &&
3213 dev->srCache[i].dirty) {
3215 || dev->srCache[i].chunkId <
3217 cache = &dev->srCache[i];
3218 lowest = cache->chunkId;
3223 if (cache && !cache->locked) {
3224 /* Write it out and free it up */
3227 yaffs_WriteChunkDataToObject(cache->object,
3233 cache->object = NULL;
3236 } while (cache && chunkWritten > 0);
3239 /* Hoosterman, disk full while writing cache out. */
3240 T(YAFFS_TRACE_ERROR,
3241 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3248 /*yaffs_FlushEntireDeviceCache(dev)
3253 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3256 int nCaches = dev->nShortOpCaches;
3259 /* Find a dirty object in the cache and flush it...
3260 * until there are no further dirty objects.
3264 for( i = 0; i < nCaches && !obj; i++) {
3265 if (dev->srCache[i].object &&
3266 dev->srCache[i].dirty)
3267 obj = dev->srCache[i].object;
3271 yaffs_FlushFilesChunkCache(obj);
3278 /* Grab us a cache chunk for use.
3279 * First look for an empty one.
3280 * Then look for the least recently used non-dirty one.
3281 * Then look for the least recently used dirty one...., flush and look again.
3283 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3289 if (dev->nShortOpCaches > 0) {
3290 for (i = 0; i < dev->nShortOpCaches; i++) {
3291 if (!dev->srCache[i].object)
3292 return &dev->srCache[i];
3298 usage = 0; /* just to stop the compiler grizzling */
3300 for (i = 0; i < dev->nShortOpCaches; i++) {
3301 if (!dev->srCache[i].dirty &&
3302 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3304 usage = dev->srCache[i].lastUse;
3310 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3317 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3319 yaffs_ChunkCache *cache;
3320 yaffs_Object *theObj;
3325 if (dev->nShortOpCaches > 0) {
3326 /* Try find a non-dirty one... */
3328 cache = yaffs_GrabChunkCacheWorker(dev);
3331 /* They were all dirty, find the last recently used object and flush
3332 * its cache, then find again.
3333 * NB what's here is not very accurate, we actually flush the object
3334 * the last recently used page.
3337 /* With locking we can't assume we can use entry zero */
3344 for (i = 0; i < dev->nShortOpCaches; i++) {
3345 if (dev->srCache[i].object &&
3346 !dev->srCache[i].locked &&
3347 (dev->srCache[i].lastUse < usage || !cache))
3349 usage = dev->srCache[i].lastUse;
3350 theObj = dev->srCache[i].object;
3351 cache = &dev->srCache[i];
3356 if (!cache || cache->dirty) {
3357 /* Flush and try again */
3358 yaffs_FlushFilesChunkCache(theObj);
3359 cache = yaffs_GrabChunkCacheWorker(dev);
3369 /* Find a cached chunk */
3370 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3373 yaffs_Device *dev = obj->myDev;
3375 if (dev->nShortOpCaches > 0) {
3376 for (i = 0; i < dev->nShortOpCaches; i++) {
3377 if (dev->srCache[i].object == obj &&
3378 dev->srCache[i].chunkId == chunkId) {
3381 return &dev->srCache[i];
3388 /* Mark the chunk for the least recently used algorithym */
3389 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3393 if (dev->nShortOpCaches > 0) {
3394 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3395 /* Reset the cache usages */
3397 for (i = 1; i < dev->nShortOpCaches; i++) {
3398 dev->srCache[i].lastUse = 0;
3405 cache->lastUse = dev->srLastUse;
3413 /* Invalidate a single cache page.
3414 * Do this when a whole page gets written,
3415 * ie the short cache for this page is no longer valid.
3417 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3419 if (object->myDev->nShortOpCaches > 0) {
3420 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3423 cache->object = NULL;
3428 /* Invalidate all the cache pages associated with this object
3429 * Do this whenever ther file is deleted or resized.
3431 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3434 yaffs_Device *dev = in->myDev;
3436 if (dev->nShortOpCaches > 0) {
3437 /* Invalidate it. */
3438 for (i = 0; i < dev->nShortOpCaches; i++) {
3439 if (dev->srCache[i].object == in) {
3440 dev->srCache[i].object = NULL;
3446 /*--------------------- Checkpointing --------------------*/
3449 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3451 yaffs_CheckpointValidity cp;
3452 cp.structType = sizeof(cp);
3453 cp.magic = YAFFS_MAGIC;
3454 cp.version = YAFFS_CHECKPOINT_VERSION;
3455 cp.head = (head) ? 1 : 0;
3457 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3461 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3463 yaffs_CheckpointValidity cp;
3466 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3469 ok = (cp.structType == sizeof(cp)) &&
3470 (cp.magic == YAFFS_MAGIC) &&
3471 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
3472 (cp.head == ((head) ? 1 : 0));
3476 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3479 cp->nErasedBlocks = dev->nErasedBlocks;
3480 cp->allocationBlock = dev->allocationBlock;
3481 cp->allocationPage = dev->allocationPage;
3482 cp->nFreeChunks = dev->nFreeChunks;
3484 cp->nDeletedFiles = dev->nDeletedFiles;
3485 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3486 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3487 cp->sequenceNumber = dev->sequenceNumber;
3488 cp->oldestDirtySequence = dev->oldestDirtySequence;
3492 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3493 yaffs_CheckpointDevice *cp)
3495 dev->nErasedBlocks = cp->nErasedBlocks;
3496 dev->allocationBlock = cp->allocationBlock;
3497 dev->allocationPage = cp->allocationPage;
3498 dev->nFreeChunks = cp->nFreeChunks;
3500 dev->nDeletedFiles = cp->nDeletedFiles;
3501 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3502 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3503 dev->sequenceNumber = cp->sequenceNumber;
3504 dev->oldestDirtySequence = cp->oldestDirtySequence;
3508 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3510 yaffs_CheckpointDevice cp;
3512 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3516 /* Write device runtime values*/
3517 yaffs_DeviceToCheckpointDevice(&cp,dev);
3518 cp.structType = sizeof(cp);
3520 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3522 /* Write block info */
3524 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3525 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3528 /* Write chunk bits */
3530 nBytes = nBlocks * dev->chunkBitmapStride;
3531 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3537 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3539 yaffs_CheckpointDevice cp;
3541 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3545 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3549 if(cp.structType != sizeof(cp))
3553 yaffs_CheckpointDeviceToDevice(dev,&cp);
3555 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3557 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3561 nBytes = nBlocks * dev->chunkBitmapStride;
3563 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3568 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3572 cp->objectId = obj->objectId;
3573 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3574 cp->chunkId = obj->chunkId;
3575 cp->variantType = obj->variantType;
3576 cp->deleted = obj->deleted;
3577 cp->softDeleted = obj->softDeleted;
3578 cp->unlinked = obj->unlinked;
3579 cp->fake = obj->fake;
3580 cp->renameAllowed = obj->renameAllowed;
3581 cp->unlinkAllowed = obj->unlinkAllowed;
3582 cp->serial = obj->serial;
3583 cp->nDataChunks = obj->nDataChunks;
3585 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3586 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3587 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3588 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3591 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3594 yaffs_Object *parent;
3596 obj->objectId = cp->objectId;
3599 parent = yaffs_FindOrCreateObjectByNumber(
3602 YAFFS_OBJECT_TYPE_DIRECTORY);
3607 yaffs_AddObjectToDirectory(parent, obj);
3609 obj->chunkId = cp->chunkId;
3610 obj->variantType = cp->variantType;
3611 obj->deleted = cp->deleted;
3612 obj->softDeleted = cp->softDeleted;
3613 obj->unlinked = cp->unlinked;
3614 obj->fake = cp->fake;
3615 obj->renameAllowed = cp->renameAllowed;
3616 obj->unlinkAllowed = cp->unlinkAllowed;
3617 obj->serial = cp->serial;
3618 obj->nDataChunks = cp->nDataChunks;
3620 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3621 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3622 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3623 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3625 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3626 obj->lazyLoaded = 1;
3631 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3632 __u32 level, int chunkOffset)
3635 yaffs_Device *dev = in->myDev;
3637 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3642 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3643 if (tn->internal[i]) {
3644 ok = yaffs_CheckpointTnodeWorker(in,
3647 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3650 } else if (level == 0) {
3651 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3652 /* printf("write tnode at %d\n",baseOffset); */
3653 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3655 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3663 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3665 __u32 endMarker = ~0;
3668 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3669 ok = yaffs_CheckpointTnodeWorker(obj,
3670 obj->variant.fileVariant.top,
3671 obj->variant.fileVariant.topLevel,
3674 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3681 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3685 yaffs_Device *dev = obj->myDev;
3686 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3689 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3691 while(ok && (~baseChunk)){
3692 /* Read level 0 tnode */
3694 /* printf("read tnode at %d\n",baseChunk); */
3695 tn = yaffs_GetTnodeRaw(dev);
3697 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3698 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3703 ok = yaffs_AddOrFindLevel0Tnode(dev,
3710 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3718 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3721 yaffs_CheckpointObject cp;
3724 struct list_head *lh;
3727 /* Iterate through the objects in each hash entry,
3728 * dumping them to the checkpointing stream.
3731 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3732 list_for_each(lh, &dev->objectBucket[i].list) {
3734 obj = list_entry(lh, yaffs_Object, hashLink);
3735 if (!obj->deferedFree) {
3736 yaffs_ObjectToCheckpointObject(&cp,obj);
3737 cp.structType = sizeof(cp);
3739 T(YAFFS_TRACE_CHECKPOINT,(
3740 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3741 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3743 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3745 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3746 ok = yaffs_WriteCheckpointTnodes(obj);
3753 /* Dump end of list */
3754 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3755 cp.structType = sizeof(cp);
3758 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3763 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3766 yaffs_CheckpointObject cp;
3769 yaffs_Object *hardList = NULL;
3771 while(ok && !done) {
3772 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3773 if(cp.structType != sizeof(cp)) {
3774 /* printf("structure parsing failed\n"); */
3778 if(ok && cp.objectId == ~0)
3781 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3782 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3783 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3785 yaffs_CheckpointObjectToObject(obj,&cp);
3786 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3787 ok = yaffs_ReadCheckpointTnodes(obj);
3788 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3789 obj->hardLinks.next =
3790 (struct list_head *)
3800 yaffs_HardlinkFixup(dev,hardList);
3805 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3810 ok = yaffs_CheckpointOpen(dev,1);
3813 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3815 ok = yaffs_WriteCheckpointDevice(dev);
3817 ok = yaffs_WriteCheckpointObjects(dev);
3819 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3821 if(!yaffs_CheckpointClose(dev))
3825 dev->isCheckpointed = 1;
3827 dev->isCheckpointed = 0;
3829 return dev->isCheckpointed;
3832 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3836 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3839 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3841 ok = yaffs_ReadCheckpointDevice(dev);
3843 ok = yaffs_ReadCheckpointObjects(dev);
3845 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3849 if(!yaffs_CheckpointClose(dev))
3853 dev->isCheckpointed = 1;
3855 dev->isCheckpointed = 0;
3861 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3863 if(dev->isCheckpointed ||
3864 dev->blocksInCheckpoint > 0){
3865 dev->isCheckpointed = 0;
3866 yaffs_CheckpointInvalidateStream(dev);
3867 if(dev->superBlock && dev->markSuperBlockDirty)
3868 dev->markSuperBlockDirty(dev->superBlock);
3873 int yaffs_CheckpointSave(yaffs_Device *dev)
3875 yaffs_ReportOddballBlocks(dev);
3876 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3878 if(!dev->isCheckpointed)
3879 yaffs_WriteCheckpointData(dev);
3881 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3883 return dev->isCheckpointed;
3886 int yaffs_CheckpointRestore(yaffs_Device *dev)
3889 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3891 retval = yaffs_ReadCheckpointData(dev);
3893 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3895 yaffs_ReportOddballBlocks(dev);
3900 /*--------------------- File read/write ------------------------
3901 * Read and write have very similar structures.
3902 * In general the read/write has three parts to it
3903 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3904 * Some complete chunks
3905 * An incomplete chunk to end off with
3907 * Curve-balls: the first chunk might also be the last chunk.
3910 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
3919 yaffs_ChunkCache *cache;
3926 //chunk = offset / dev->nDataBytesPerChunk + 1;
3927 //start = offset % dev->nDataBytesPerChunk;
3928 yaffs_AddrToChunk(dev,offset,&chunk,&start);
3931 /* OK now check for the curveball where the start and end are in
3934 if ((start + n) < dev->nDataBytesPerChunk) {
3937 nToCopy = dev->nDataBytesPerChunk - start;
3940 cache = yaffs_FindChunkCache(in, chunk);
3942 /* If the chunk is already in the cache or it is less than a whole chunk
3943 * then use the cache (if there is caching)
3944 * else bypass the cache.
3946 if (cache || nToCopy != dev->nDataBytesPerChunk) {
3947 if (dev->nShortOpCaches > 0) {
3949 /* If we can't find the data in the cache, then load it up. */
3952 cache = yaffs_GrabChunkCache(in->myDev);
3954 cache->chunkId = chunk;
3957 yaffs_ReadChunkDataFromObject(in, chunk,
3963 yaffs_UseChunkCache(dev, cache, 0);
3967 #ifdef CONFIG_YAFFS_WINCE
3968 yfsd_UnlockYAFFS(TRUE);
3970 memcpy(buffer, &cache->data[start], nToCopy);
3972 #ifdef CONFIG_YAFFS_WINCE
3973 yfsd_LockYAFFS(TRUE);
3977 /* Read into the local buffer then copy..*/
3980 yaffs_GetTempBuffer(dev, __LINE__);
3981 yaffs_ReadChunkDataFromObject(in, chunk,
3983 #ifdef CONFIG_YAFFS_WINCE
3984 yfsd_UnlockYAFFS(TRUE);
3986 memcpy(buffer, &localBuffer[start], nToCopy);
3988 #ifdef CONFIG_YAFFS_WINCE
3989 yfsd_LockYAFFS(TRUE);
3991 yaffs_ReleaseTempBuffer(dev, localBuffer,
3996 #ifdef CONFIG_YAFFS_WINCE
3997 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3999 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4000 * This is because we otherwise screw up WinCE's memory mapper
4002 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4004 #ifdef CONFIG_YAFFS_WINCE
4005 yfsd_UnlockYAFFS(TRUE);
4007 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4009 #ifdef CONFIG_YAFFS_WINCE
4010 yfsd_LockYAFFS(TRUE);
4011 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4015 /* A full chunk. Read directly into the supplied buffer. */
4016 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4030 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4031 int nBytes, int writeThrough)
4040 int startOfWrite = offset;
4041 int chunkWritten = 0;
4048 while (n > 0 && chunkWritten >= 0) {
4049 //chunk = offset / dev->nDataBytesPerChunk + 1;
4050 //start = offset % dev->nDataBytesPerChunk;
4051 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4054 /* OK now check for the curveball where the start and end are in
4058 if ((start + n) < dev->nDataBytesPerChunk) {
4061 /* Now folks, to calculate how many bytes to write back....
4062 * If we're overwriting and not writing to then end of file then
4063 * we need to write back as much as was there before.
4067 in->variant.fileVariant.fileSize -
4068 ((chunk - 1) * dev->nDataBytesPerChunk);
4070 if (nBytesRead > dev->nDataBytesPerChunk) {
4071 nBytesRead = dev->nDataBytesPerChunk;
4076 (start + n)) ? nBytesRead : (start + n);
4079 nToCopy = dev->nDataBytesPerChunk - start;
4080 nToWriteBack = dev->nDataBytesPerChunk;
4083 if (nToCopy != dev->nDataBytesPerChunk) {
4084 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4085 if (dev->nShortOpCaches > 0) {
4086 yaffs_ChunkCache *cache;
4087 /* If we can't find the data in the cache, then load the cache */
4088 cache = yaffs_FindChunkCache(in, chunk);
4091 && yaffs_CheckSpaceForAllocation(in->
4093 cache = yaffs_GrabChunkCache(in->myDev);
4095 cache->chunkId = chunk;
4098 yaffs_ReadChunkDataFromObject(in, chunk,
4104 !yaffs_CheckSpaceForAllocation(in->myDev)){
4105 /* Drop the cache if it was a read cache item and
4106 * no space check has been made for it.
4112 yaffs_UseChunkCache(dev, cache, 1);
4114 #ifdef CONFIG_YAFFS_WINCE
4115 yfsd_UnlockYAFFS(TRUE);
4118 memcpy(&cache->data[start], buffer,
4121 #ifdef CONFIG_YAFFS_WINCE
4122 yfsd_LockYAFFS(TRUE);
4125 cache->nBytes = nToWriteBack;
4129 yaffs_WriteChunkDataToObject
4132 cache->data, cache->nBytes,
4138 chunkWritten = -1; /* fail the write */
4141 /* An incomplete start or end chunk (or maybe both start and end chunk)
4142 * Read into the local buffer then copy, then copy over and write back.
4146 yaffs_GetTempBuffer(dev, __LINE__);
4148 yaffs_ReadChunkDataFromObject(in, chunk,
4151 #ifdef CONFIG_YAFFS_WINCE
4152 yfsd_UnlockYAFFS(TRUE);
4155 memcpy(&localBuffer[start], buffer, nToCopy);
4157 #ifdef CONFIG_YAFFS_WINCE
4158 yfsd_LockYAFFS(TRUE);
4161 yaffs_WriteChunkDataToObject(in, chunk,
4166 yaffs_ReleaseTempBuffer(dev, localBuffer,
4173 #ifdef CONFIG_YAFFS_WINCE
4174 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4175 * This is because we otherwise screw up WinCE's memory mapper
4177 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4178 #ifdef CONFIG_YAFFS_WINCE
4179 yfsd_UnlockYAFFS(TRUE);
4181 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4182 #ifdef CONFIG_YAFFS_WINCE
4183 yfsd_LockYAFFS(TRUE);
4186 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4187 dev->nDataBytesPerChunk,
4189 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4191 /* A full chunk. Write directly from the supplied buffer. */
4193 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4194 dev->nDataBytesPerChunk,
4197 /* Since we've overwritten the cached data, we better invalidate it. */
4198 yaffs_InvalidateChunkCache(in, chunk);
4201 if (chunkWritten >= 0) {
4210 /* Update file object */
4212 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4213 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4222 /* ---------------------- File resizing stuff ------------------ */
4224 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4227 yaffs_Device *dev = in->myDev;
4228 int oldFileSize = in->variant.fileVariant.fileSize;
4230 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4232 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4233 dev->nDataBytesPerChunk;
4237 /* Delete backwards so that we don't end up with holes if
4238 * power is lost part-way through the operation.
4240 for (i = lastDel; i >= startDel; i--) {
4241 /* NB this could be optimised somewhat,
4242 * eg. could retrieve the tags and write them without
4243 * using yaffs_DeleteChunk
4246 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4249 (dev->internalStartBlock * dev->nChunksPerBlock)
4251 ((dev->internalEndBlock +
4252 1) * dev->nChunksPerBlock)) {
4253 T(YAFFS_TRACE_ALWAYS,
4254 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4258 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4265 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4268 int oldFileSize = in->variant.fileVariant.fileSize;
4269 int newSizeOfPartialChunk;
4272 yaffs_Device *dev = in->myDev;
4274 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4276 yaffs_FlushFilesChunkCache(in);
4277 yaffs_InvalidateWholeChunkCache(in);
4279 yaffs_CheckGarbageCollection(dev);
4281 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4282 return yaffs_GetFileSize(in);
4285 if (newSize == oldFileSize) {
4289 if (newSize < oldFileSize) {
4291 yaffs_PruneResizedChunks(in, newSize);
4293 if (newSizeOfPartialChunk != 0) {
4294 int lastChunk = 1 + newFullChunks;
4296 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4298 /* Got to read and rewrite the last chunk with its new size and zero pad */
4299 yaffs_ReadChunkDataFromObject(in, lastChunk,
4302 memset(localBuffer + newSizeOfPartialChunk, 0,
4303 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4305 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4306 newSizeOfPartialChunk, 1);
4308 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4311 in->variant.fileVariant.fileSize = newSize;
4313 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4315 /* Write a new object header.
4316 * show we've shrunk the file, if need be
4317 * Do this only if the file is not in the deleted directories.
4319 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4320 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4321 yaffs_UpdateObjectHeader(in, NULL, 0,
4322 (newSize < oldFileSize) ? 1 : 0, 0);
4328 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4330 obj = yaffs_GetEquivalentObject(obj);
4332 switch (obj->variantType) {
4333 case YAFFS_OBJECT_TYPE_FILE:
4334 return obj->variant.fileVariant.fileSize;
4335 case YAFFS_OBJECT_TYPE_SYMLINK:
4336 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4344 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4348 yaffs_FlushFilesChunkCache(in);
4350 #ifdef CONFIG_YAFFS_WINCE
4351 yfsd_WinFileTimeNow(in->win_mtime);
4354 in->yst_mtime = Y_CURRENT_TIME;
4360 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4361 0) ? YAFFS_OK : YAFFS_FAIL;
4370 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4373 /* First off, invalidate the file's data in the cache, without flushing. */
4374 yaffs_InvalidateWholeChunkCache(in);
4376 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4377 /* Move to the unlinked directory so we have a record that it was deleted. */
4378 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4382 yaffs_RemoveObjectFromDirectory(in);
4383 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4386 yaffs_FreeObject(in);
4391 /* yaffs_DeleteFile deletes the whole file data
4392 * and the inode associated with the file.
4393 * It does not delete the links associated with the file.
4395 static int yaffs_UnlinkFile(yaffs_Object * in)
4399 int immediateDeletion = 0;
4404 immediateDeletion = 1;
4408 if (in->inUse <= 0) {
4409 immediateDeletion = 1;
4413 if (immediateDeletion) {
4415 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4417 T(YAFFS_TRACE_TRACING,
4418 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4421 in->myDev->nDeletedFiles++;
4422 if (0 && in->myDev->isYaffs2) {
4423 yaffs_ResizeFile(in, 0);
4425 yaffs_SoftDeleteFile(in);
4428 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4436 int yaffs_DeleteFile(yaffs_Object * in)
4438 int retVal = YAFFS_OK;
4440 if (in->nDataChunks > 0) {
4441 /* Use soft deletion if there is data in the file */
4442 if (!in->unlinked) {
4443 retVal = yaffs_UnlinkFile(in);
4445 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4447 in->myDev->nDeletedFiles++;
4448 yaffs_SoftDeleteFile(in);
4450 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4452 /* The file has no data chunks so we toss it immediately */
4453 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4454 in->variant.fileVariant.top = NULL;
4455 yaffs_DoGenericObjectDeletion(in);
4461 static int yaffs_DeleteDirectory(yaffs_Object * in)
4463 /* First check that the directory is empty. */
4464 if (list_empty(&in->variant.directoryVariant.children)) {
4465 return yaffs_DoGenericObjectDeletion(in);
4472 static int yaffs_DeleteSymLink(yaffs_Object * in)
4474 YFREE(in->variant.symLinkVariant.alias);
4476 return yaffs_DoGenericObjectDeletion(in);
4479 static int yaffs_DeleteHardLink(yaffs_Object * in)
4481 /* remove this hardlink from the list assocaited with the equivalent
4484 list_del(&in->hardLinks);
4485 return yaffs_DoGenericObjectDeletion(in);
4488 static void yaffs_DestroyObject(yaffs_Object * obj)
4490 switch (obj->variantType) {
4491 case YAFFS_OBJECT_TYPE_FILE:
4492 yaffs_DeleteFile(obj);
4494 case YAFFS_OBJECT_TYPE_DIRECTORY:
4495 yaffs_DeleteDirectory(obj);
4497 case YAFFS_OBJECT_TYPE_SYMLINK:
4498 yaffs_DeleteSymLink(obj);
4500 case YAFFS_OBJECT_TYPE_HARDLINK:
4501 yaffs_DeleteHardLink(obj);
4503 case YAFFS_OBJECT_TYPE_SPECIAL:
4504 yaffs_DoGenericObjectDeletion(obj);
4506 case YAFFS_OBJECT_TYPE_UNKNOWN:
4507 break; /* should not happen. */
4511 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4514 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4515 return yaffs_DeleteHardLink(obj);
4516 } else if (!list_empty(&obj->hardLinks)) {
4517 /* Curve ball: We're unlinking an object that has a hardlink.
4519 * This problem arises because we are not strictly following
4520 * The Linux link/inode model.
4522 * We can't really delete the object.
4523 * Instead, we do the following:
4524 * - Select a hardlink.
4525 * - Unhook it from the hard links
4526 * - Unhook it from its parent directory (so that the rename can work)
4527 * - Rename the object to the hardlink's name.
4528 * - Delete the hardlink
4533 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4535 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4537 list_del_init(&hl->hardLinks);
4538 list_del_init(&hl->siblings);
4540 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4542 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4544 if (retVal == YAFFS_OK) {
4545 retVal = yaffs_DoGenericObjectDeletion(hl);
4550 switch (obj->variantType) {
4551 case YAFFS_OBJECT_TYPE_FILE:
4552 return yaffs_UnlinkFile(obj);
4554 case YAFFS_OBJECT_TYPE_DIRECTORY:
4555 return yaffs_DeleteDirectory(obj);
4557 case YAFFS_OBJECT_TYPE_SYMLINK:
4558 return yaffs_DeleteSymLink(obj);
4560 case YAFFS_OBJECT_TYPE_SPECIAL:
4561 return yaffs_DoGenericObjectDeletion(obj);
4563 case YAFFS_OBJECT_TYPE_HARDLINK:
4564 case YAFFS_OBJECT_TYPE_UNKNOWN:
4572 static int yaffs_UnlinkObject( yaffs_Object *obj)
4575 if (obj && obj->unlinkAllowed) {
4576 return yaffs_UnlinkWorker(obj);
4582 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4586 obj = yaffs_FindObjectByName(dir, name);
4587 return yaffs_UnlinkObject(obj);
4590 /*----------------------- Initialisation Scanning ---------------------- */
4592 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4593 int backwardScanning)
4597 if (!backwardScanning) {
4598 /* Handle YAFFS1 forward scanning case
4599 * For YAFFS1 we always do the deletion
4603 /* Handle YAFFS2 case (backward scanning)
4604 * If the shadowed object exists then ignore.
4606 if (yaffs_FindObjectByNumber(dev, objId)) {
4611 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4612 * We put it in unlinked dir to be cleaned up after the scanning
4615 yaffs_FindOrCreateObjectByNumber(dev, objId,
4616 YAFFS_OBJECT_TYPE_FILE);
4617 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4618 obj->variant.fileVariant.shrinkSize = 0;
4619 obj->valid = 1; /* So that we don't read any other info for this file */
4629 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4636 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4638 in = yaffs_FindObjectByNumber(dev,
4639 hl->variant.hardLinkVariant.
4640 equivalentObjectId);
4643 /* Add the hardlink pointers */
4644 hl->variant.hardLinkVariant.equivalentObject = in;
4645 list_add(&hl->hardLinks, &in->hardLinks);
4647 /* Todo Need to report/handle this better.
4648 * Got a problem... hardlink to a non-existant object
4650 hl->variant.hardLinkVariant.equivalentObject = NULL;
4651 INIT_LIST_HEAD(&hl->hardLinks);
4663 static int ybicmp(const void *a, const void *b){
4664 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4665 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4666 register int ablock = ((yaffs_BlockIndex *)a)->block;
4667 register int bblock = ((yaffs_BlockIndex *)b)->block;
4669 return ablock - bblock;
4675 static int yaffs_Scan(yaffs_Device * dev)
4677 yaffs_ExtendedTags tags;
4682 int nBlocksToScan = 0;
4688 yaffs_BlockState state;
4689 yaffs_Object *hardList = NULL;
4691 yaffs_BlockInfo *bi;
4693 yaffs_ObjectHeader *oh;
4695 yaffs_Object *parent;
4696 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4700 yaffs_BlockIndex *blockIndex = NULL;
4702 if (dev->isYaffs2) {
4704 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4708 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4711 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4712 dev->internalStartBlock, dev->internalEndBlock));
4714 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4716 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4718 if (dev->isYaffs2) {
4719 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4722 /* Scan all the blocks to determine their state */
4723 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4724 bi = yaffs_GetBlockInfo(dev, blk);
4725 yaffs_ClearChunkBits(dev, blk);
4727 bi->softDeletions = 0;
4729 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4731 bi->blockState = state;
4732 bi->sequenceNumber = sequenceNumber;
4734 T(YAFFS_TRACE_SCAN_DEBUG,
4735 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4736 state, sequenceNumber));
4738 if (state == YAFFS_BLOCK_STATE_DEAD) {
4739 T(YAFFS_TRACE_BAD_BLOCKS,
4740 (TSTR("block %d is bad" TENDSTR), blk));
4741 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4742 T(YAFFS_TRACE_SCAN_DEBUG,
4743 (TSTR("Block empty " TENDSTR)));
4744 dev->nErasedBlocks++;
4745 dev->nFreeChunks += dev->nChunksPerBlock;
4746 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4748 /* Determine the highest sequence number */
4749 if (dev->isYaffs2 &&
4750 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4751 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4753 blockIndex[nBlocksToScan].seq = sequenceNumber;
4754 blockIndex[nBlocksToScan].block = blk;
4758 if (sequenceNumber >= dev->sequenceNumber) {
4759 dev->sequenceNumber = sequenceNumber;
4761 } else if (dev->isYaffs2) {
4762 /* TODO: Nasty sequence number! */
4765 ("Block scanning block %d has bad sequence number %d"
4766 TENDSTR), blk, sequenceNumber));
4773 * Dungy old bubble sort for now...
4775 if (dev->isYaffs2) {
4776 yaffs_BlockIndex temp;
4780 for (i = 0; i < nBlocksToScan; i++)
4781 for (j = i + 1; j < nBlocksToScan; j++)
4782 if (blockIndex[i].seq > blockIndex[j].seq) {
4783 temp = blockIndex[j];
4784 blockIndex[j] = blockIndex[i];
4785 blockIndex[i] = temp;
4789 /* Now scan the blocks looking at the data. */
4790 if (dev->isYaffs2) {
4792 endIterator = nBlocksToScan - 1;
4793 T(YAFFS_TRACE_SCAN_DEBUG,
4794 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4796 startIterator = dev->internalStartBlock;
4797 endIterator = dev->internalEndBlock;
4800 /* For each block.... */
4801 for (blockIterator = startIterator; blockIterator <= endIterator;
4804 if (dev->isYaffs2) {
4805 /* get the block to scan in the correct order */
4806 blk = blockIndex[blockIterator].block;
4808 blk = blockIterator;
4811 bi = yaffs_GetBlockInfo(dev, blk);
4812 state = bi->blockState;
4816 /* For each chunk in each block that needs scanning....*/
4817 for (c = 0; c < dev->nChunksPerBlock &&
4818 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4819 /* Read the tags and decide what to do */
4820 chunk = blk * dev->nChunksPerBlock + c;
4822 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4825 /* Let's have a good look at this chunk... */
4827 if (!dev->isYaffs2 && tags.chunkDeleted) {
4833 /*T((" %d %d deleted\n",blk,c)); */
4834 } else if (!tags.chunkUsed) {
4835 /* An unassigned chunk in the block
4836 * This means that either the block is empty or
4837 * this is the one being allocated from
4841 /* We're looking at the first chunk in the block so the block is unused */
4842 state = YAFFS_BLOCK_STATE_EMPTY;
4843 dev->nErasedBlocks++;
4845 /* this is the block being allocated from */
4848 (" Allocating from %d %d" TENDSTR),
4850 state = YAFFS_BLOCK_STATE_ALLOCATING;
4851 dev->allocationBlock = blk;
4852 dev->allocationPage = c;
4853 dev->allocationBlockFinder = blk;
4854 /* Set it to here to encourage the allocator to go forth from here. */
4856 /* Yaffs2 sanity check:
4857 * This should be the one with the highest sequence number
4860 && (dev->sequenceNumber !=
4861 bi->sequenceNumber)) {
4862 T(YAFFS_TRACE_ALWAYS,
4864 ("yaffs: Allocation block %d was not highest sequence id:"
4865 " block seq = %d, dev seq = %d"
4866 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4870 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4871 } else if (tags.chunkId > 0) {
4872 /* chunkId > 0 so it is a data chunk... */
4873 unsigned int endpos;
4875 yaffs_SetChunkBit(dev, blk, c);
4878 in = yaffs_FindOrCreateObjectByNumber(dev,
4881 YAFFS_OBJECT_TYPE_FILE);
4882 /* PutChunkIntoFile checks for a clash (two data chunks with
4883 * the same chunkId).
4885 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4888 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
4890 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4891 && in->variant.fileVariant.scannedFileSize <
4893 in->variant.fileVariant.
4894 scannedFileSize = endpos;
4895 if (!dev->useHeaderFileSize) {
4896 in->variant.fileVariant.
4898 in->variant.fileVariant.
4903 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4905 /* chunkId == 0, so it is an ObjectHeader.
4906 * Thus, we read in the object header and make the object
4908 yaffs_SetChunkBit(dev, blk, c);
4911 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4915 oh = (yaffs_ObjectHeader *) chunkData;
4917 in = yaffs_FindObjectByNumber(dev,
4919 if (in && in->variantType != oh->type) {
4920 /* This should not happen, but somehow
4921 * Wev'e ended up with an objectId that has been reused but not yet
4922 * deleted, and worse still it has changed type. Delete the old object.
4925 yaffs_DestroyObject(in);
4930 in = yaffs_FindOrCreateObjectByNumber(dev,
4935 if (oh->shadowsObject > 0) {
4936 yaffs_HandleShadowedObject(dev,
4943 /* We have already filled this one. We have a duplicate and need to resolve it. */
4945 unsigned existingSerial = in->serial;
4946 unsigned newSerial = tags.serialNumber;
4948 if (dev->isYaffs2 ||
4949 ((existingSerial + 1) & 3) ==
4951 /* Use new one - destroy the exisiting one */
4952 yaffs_DeleteChunk(dev,
4957 /* Use existing - destroy this one. */
4958 yaffs_DeleteChunk(dev, chunk, 1,
4964 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4965 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4966 /* We only load some info, don't fiddle with directory structure */
4968 in->variantType = oh->type;
4970 in->yst_mode = oh->yst_mode;
4971 #ifdef CONFIG_YAFFS_WINCE
4972 in->win_atime[0] = oh->win_atime[0];
4973 in->win_ctime[0] = oh->win_ctime[0];
4974 in->win_mtime[0] = oh->win_mtime[0];
4975 in->win_atime[1] = oh->win_atime[1];
4976 in->win_ctime[1] = oh->win_ctime[1];
4977 in->win_mtime[1] = oh->win_mtime[1];
4979 in->yst_uid = oh->yst_uid;
4980 in->yst_gid = oh->yst_gid;
4981 in->yst_atime = oh->yst_atime;
4982 in->yst_mtime = oh->yst_mtime;
4983 in->yst_ctime = oh->yst_ctime;
4984 in->yst_rdev = oh->yst_rdev;
4986 in->chunkId = chunk;
4988 } else if (!in->valid) {
4989 /* we need to load this info */
4992 in->variantType = oh->type;
4994 in->yst_mode = oh->yst_mode;
4995 #ifdef CONFIG_YAFFS_WINCE
4996 in->win_atime[0] = oh->win_atime[0];
4997 in->win_ctime[0] = oh->win_ctime[0];
4998 in->win_mtime[0] = oh->win_mtime[0];
4999 in->win_atime[1] = oh->win_atime[1];
5000 in->win_ctime[1] = oh->win_ctime[1];
5001 in->win_mtime[1] = oh->win_mtime[1];
5003 in->yst_uid = oh->yst_uid;
5004 in->yst_gid = oh->yst_gid;
5005 in->yst_atime = oh->yst_atime;
5006 in->yst_mtime = oh->yst_mtime;
5007 in->yst_ctime = oh->yst_ctime;
5008 in->yst_rdev = oh->yst_rdev;
5010 in->chunkId = chunk;
5012 yaffs_SetObjectName(in, oh->name);
5015 /* directory stuff...
5020 yaffs_FindOrCreateObjectByNumber
5021 (dev, oh->parentObjectId,
5022 YAFFS_OBJECT_TYPE_DIRECTORY);
5023 if (parent->variantType ==
5024 YAFFS_OBJECT_TYPE_UNKNOWN) {
5025 /* Set up as a directory */
5026 parent->variantType =
5027 YAFFS_OBJECT_TYPE_DIRECTORY;
5028 INIT_LIST_HEAD(&parent->variant.
5031 } else if (parent->variantType !=
5032 YAFFS_OBJECT_TYPE_DIRECTORY)
5034 /* Hoosterman, another problem....
5035 * We're trying to use a non-directory as a directory
5038 T(YAFFS_TRACE_ERROR,
5040 ("yaffs tragedy: attempting to use non-directory as"
5041 " a directory in scan. Put in lost+found."
5043 parent = dev->lostNFoundDir;
5046 yaffs_AddObjectToDirectory(parent, in);
5048 if (0 && (parent == dev->deletedDir ||
5049 parent == dev->unlinkedDir)) {
5050 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5051 dev->nDeletedFiles++;
5053 /* Note re hardlinks.
5054 * Since we might scan a hardlink before its equivalent object is scanned
5055 * we put them all in a list.
5056 * After scanning is complete, we should have all the objects, so we run through this
5057 * list and fix up all the chains.
5060 switch (in->variantType) {
5061 case YAFFS_OBJECT_TYPE_UNKNOWN:
5062 /* Todo got a problem */
5064 case YAFFS_OBJECT_TYPE_FILE:
5067 /* Prune back the shrunken chunks */
5068 yaffs_PruneResizedChunks
5070 /* Mark the block as having a shrinkHeader */
5071 bi->hasShrinkHeader = 1;
5074 if (dev->useHeaderFileSize)
5076 in->variant.fileVariant.
5081 case YAFFS_OBJECT_TYPE_HARDLINK:
5082 in->variant.hardLinkVariant.
5083 equivalentObjectId =
5084 oh->equivalentObjectId;
5085 in->hardLinks.next =
5086 (struct list_head *)
5090 case YAFFS_OBJECT_TYPE_DIRECTORY:
5093 case YAFFS_OBJECT_TYPE_SPECIAL:
5096 case YAFFS_OBJECT_TYPE_SYMLINK:
5097 in->variant.symLinkVariant.
5099 yaffs_CloneString(oh->alias);
5103 if (parent == dev->deletedDir) {
5104 yaffs_DestroyObject(in);
5105 bi->hasShrinkHeader = 1;
5111 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5112 /* If we got this far while scanning, then the block is fully allocated.*/
5113 state = YAFFS_BLOCK_STATE_FULL;
5116 bi->blockState = state;
5118 /* Now let's see if it was dirty */
5119 if (bi->pagesInUse == 0 &&
5120 !bi->hasShrinkHeader &&
5121 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5122 yaffs_BlockBecameDirty(dev, blk);
5132 /* Ok, we've done all the scanning.
5133 * Fix up the hard link chains.
5134 * We should now have scanned all the objects, now it's time to add these
5138 yaffs_HardlinkFixup(dev,hardList);
5140 /* Handle the unlinked files. Since they were left in an unlinked state we should
5144 struct list_head *i;
5145 struct list_head *n;
5148 /* Soft delete all the unlinked files */
5149 list_for_each_safe(i, n,
5150 &dev->unlinkedDir->variant.directoryVariant.
5153 l = list_entry(i, yaffs_Object, siblings);
5154 yaffs_DestroyObject(l);
5159 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5161 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5166 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5169 yaffs_ObjectHeader *oh;
5170 yaffs_Device *dev = in->myDev;
5171 yaffs_ExtendedTags tags;
5175 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5177 in->lazyLoaded ? "not yet" : "already"));
5182 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5184 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5185 oh = (yaffs_ObjectHeader *) chunkData;
5187 in->yst_mode = oh->yst_mode;
5188 #ifdef CONFIG_YAFFS_WINCE
5189 in->win_atime[0] = oh->win_atime[0];
5190 in->win_ctime[0] = oh->win_ctime[0];
5191 in->win_mtime[0] = oh->win_mtime[0];
5192 in->win_atime[1] = oh->win_atime[1];
5193 in->win_ctime[1] = oh->win_ctime[1];
5194 in->win_mtime[1] = oh->win_mtime[1];
5196 in->yst_uid = oh->yst_uid;
5197 in->yst_gid = oh->yst_gid;
5198 in->yst_atime = oh->yst_atime;
5199 in->yst_mtime = oh->yst_mtime;
5200 in->yst_ctime = oh->yst_ctime;
5201 in->yst_rdev = oh->yst_rdev;
5204 yaffs_SetObjectName(in, oh->name);
5206 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5207 in->variant.symLinkVariant.alias =
5208 yaffs_CloneString(oh->alias);
5210 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5214 static int yaffs_ScanBackwards(yaffs_Device * dev)
5216 yaffs_ExtendedTags tags;
5221 int nBlocksToScan = 0;
5227 yaffs_BlockState state;
5228 yaffs_Object *hardList = NULL;
5229 yaffs_BlockInfo *bi;
5231 yaffs_ObjectHeader *oh;
5233 yaffs_Object *parent;
5234 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5240 int foundChunksInBlock;
5241 int equivalentObjectId;
5244 yaffs_BlockIndex *blockIndex = NULL;
5245 int altBlockIndex = 0;
5247 if (!dev->isYaffs2) {
5249 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5255 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5256 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5259 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5261 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5264 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5270 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5274 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5276 /* Scan all the blocks to determine their state */
5277 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5278 bi = yaffs_GetBlockInfo(dev, blk);
5279 yaffs_ClearChunkBits(dev, blk);
5281 bi->softDeletions = 0;
5283 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5285 bi->blockState = state;
5286 bi->sequenceNumber = sequenceNumber;
5288 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5289 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5291 T(YAFFS_TRACE_SCAN_DEBUG,
5292 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5293 state, sequenceNumber));
5296 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5297 /* todo .. fix free space ? */
5299 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5300 T(YAFFS_TRACE_BAD_BLOCKS,
5301 (TSTR("block %d is bad" TENDSTR), blk));
5302 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5303 T(YAFFS_TRACE_SCAN_DEBUG,
5304 (TSTR("Block empty " TENDSTR)));
5305 dev->nErasedBlocks++;
5306 dev->nFreeChunks += dev->nChunksPerBlock;
5307 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5309 /* Determine the highest sequence number */
5310 if (dev->isYaffs2 &&
5311 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5312 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5314 blockIndex[nBlocksToScan].seq = sequenceNumber;
5315 blockIndex[nBlocksToScan].block = blk;
5319 if (sequenceNumber >= dev->sequenceNumber) {
5320 dev->sequenceNumber = sequenceNumber;
5322 } else if (dev->isYaffs2) {
5323 /* TODO: Nasty sequence number! */
5326 ("Block scanning block %d has bad sequence number %d"
5327 TENDSTR), blk, sequenceNumber));
5334 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5340 /* Sort the blocks */
5341 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5343 /* Use qsort now. */
5344 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5348 /* Dungy old bubble sort... */
5350 yaffs_BlockIndex temp;
5354 for (i = 0; i < nBlocksToScan; i++)
5355 for (j = i + 1; j < nBlocksToScan; j++)
5356 if (blockIndex[i].seq > blockIndex[j].seq) {
5357 temp = blockIndex[j];
5358 blockIndex[j] = blockIndex[i];
5359 blockIndex[i] = temp;
5366 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5368 /* Now scan the blocks looking at the data. */
5370 endIterator = nBlocksToScan - 1;
5371 T(YAFFS_TRACE_SCAN_DEBUG,
5372 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5374 /* For each block.... backwards */
5375 for (blockIterator = endIterator; blockIterator >= startIterator;
5377 /* Cooperative multitasking! This loop can run for so
5378 long that watchdog timers expire. */
5381 /* get the block to scan in the correct order */
5382 blk = blockIndex[blockIterator].block;
5384 bi = yaffs_GetBlockInfo(dev, blk);
5385 state = bi->blockState;
5389 /* For each chunk in each block that needs scanning.... */
5390 foundChunksInBlock = 0;
5391 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5392 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5393 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5394 /* Scan backwards...
5395 * Read the tags and decide what to do
5397 chunk = blk * dev->nChunksPerBlock + c;
5399 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5402 /* Let's have a good look at this chunk... */
5404 if (!tags.chunkUsed) {
5405 /* An unassigned chunk in the block.
5406 * If there are used chunks after this one, then
5407 * it is a chunk that was skipped due to failing the erased
5408 * check. Just skip it so that it can be deleted.
5409 * But, more typically, We get here when this is an unallocated
5410 * chunk and his means that either the block is empty or
5411 * this is the one being allocated from
5414 if(foundChunksInBlock)
5416 /* This is a chunk that was skipped due to failing the erased check */
5418 } else if (c == 0) {
5419 /* We're looking at the first chunk in the block so the block is unused */
5420 state = YAFFS_BLOCK_STATE_EMPTY;
5421 dev->nErasedBlocks++;
5423 /* this is the block being allocated from */
5425 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5428 (" Allocating from %d %d"
5431 state = YAFFS_BLOCK_STATE_ALLOCATING;
5432 dev->allocationBlock = blk;
5433 dev->allocationPage = c;
5434 dev->allocationBlockFinder = blk;
5435 /* Set it to here to encourage the allocator to
5436 * go forth from here.
5439 /* Yaffs2 sanity check:
5440 * This should be the one with the highest sequence number
5443 && (dev->sequenceNumber !=
5444 bi->sequenceNumber)) {
5445 T(YAFFS_TRACE_ALWAYS,
5447 ("yaffs: Allocation block %d was not highest sequence "
5448 "id: block seq = %d, dev seq = %d"
5451 dev->sequenceNumber));
5456 } else if (tags.chunkId > 0) {
5457 /* chunkId > 0 so it is a data chunk... */
5458 unsigned int endpos;
5460 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
5462 foundChunksInBlock = 1;
5465 yaffs_SetChunkBit(dev, blk, c);
5468 in = yaffs_FindOrCreateObjectByNumber(dev,
5471 YAFFS_OBJECT_TYPE_FILE);
5472 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5474 in->variant.fileVariant.shrinkSize) {
5475 /* This has not been invalidated by a resize */
5476 yaffs_PutChunkIntoFile(in, tags.chunkId,
5479 /* File size is calculated by looking at the data chunks if we have not
5480 * seen an object header yet. Stop this practice once we find an object header.
5484 1) * dev->nDataBytesPerChunk +
5487 if (!in->valid && /* have not got an object header yet */
5488 in->variant.fileVariant.
5489 scannedFileSize < endpos) {
5490 in->variant.fileVariant.
5491 scannedFileSize = endpos;
5492 in->variant.fileVariant.
5494 in->variant.fileVariant.
5499 /* This chunk has been invalidated by a resize, so delete */
5500 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5504 /* chunkId == 0, so it is an ObjectHeader.
5505 * Thus, we read in the object header and make the object
5507 foundChunksInBlock = 1;
5509 yaffs_SetChunkBit(dev, blk, c);
5515 if (tags.extraHeaderInfoAvailable) {
5516 in = yaffs_FindOrCreateObjectByNumber
5517 (dev, tags.objectId,
5518 tags.extraObjectType);
5522 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5525 tags.extraShadows ||
5527 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5528 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5531 /* If we don't have valid info then we need to read the chunk
5532 * TODO In future we can probably defer reading the chunk and
5533 * living with invalid data until needed.
5536 result = yaffs_ReadChunkWithTagsFromNAND(dev,
5541 oh = (yaffs_ObjectHeader *) chunkData;
5544 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5549 /* TODO Hoosterman we have a problem! */
5550 T(YAFFS_TRACE_ERROR,
5552 ("yaffs tragedy: Could not make object for object %d "
5553 "at chunk %d during scan"
5554 TENDSTR), tags.objectId, chunk));
5559 /* We have already filled this one.
5560 * We have a duplicate that will be discarded, but
5561 * we first have to suck out resize info if it is a file.
5564 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5566 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5567 (tags.extraHeaderInfoAvailable &&
5568 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5571 (oh) ? oh->fileSize : tags.
5573 __u32 parentObjectId =
5575 parentObjectId : tags.
5576 extraParentObjectId;
5578 (oh) ? oh->isShrink : tags.
5579 extraIsShrinkHeader;
5581 /* If it is deleted (unlinked at start also means deleted)
5582 * we treat the file size as being zeroed at this point.
5584 if (parentObjectId ==
5585 YAFFS_OBJECTID_DELETED
5586 || parentObjectId ==
5587 YAFFS_OBJECTID_UNLINKED) {
5593 in->variant.fileVariant.
5594 shrinkSize > thisSize) {
5595 in->variant.fileVariant.
5601 bi->hasShrinkHeader = 1;
5605 /* Use existing - destroy this one. */
5606 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5611 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5613 YAFFS_OBJECTID_LOSTNFOUND)) {
5614 /* We only load some info, don't fiddle with directory structure */
5618 in->variantType = oh->type;
5620 in->yst_mode = oh->yst_mode;
5621 #ifdef CONFIG_YAFFS_WINCE
5622 in->win_atime[0] = oh->win_atime[0];
5623 in->win_ctime[0] = oh->win_ctime[0];
5624 in->win_mtime[0] = oh->win_mtime[0];
5625 in->win_atime[1] = oh->win_atime[1];
5626 in->win_ctime[1] = oh->win_ctime[1];
5627 in->win_mtime[1] = oh->win_mtime[1];
5629 in->yst_uid = oh->yst_uid;
5630 in->yst_gid = oh->yst_gid;
5631 in->yst_atime = oh->yst_atime;
5632 in->yst_mtime = oh->yst_mtime;
5633 in->yst_ctime = oh->yst_ctime;
5634 in->yst_rdev = oh->yst_rdev;
5638 in->variantType = tags.extraObjectType;
5642 in->chunkId = chunk;
5644 } else if (!in->valid) {
5645 /* we need to load this info */
5648 in->chunkId = chunk;
5651 in->variantType = oh->type;
5653 in->yst_mode = oh->yst_mode;
5654 #ifdef CONFIG_YAFFS_WINCE
5655 in->win_atime[0] = oh->win_atime[0];
5656 in->win_ctime[0] = oh->win_ctime[0];
5657 in->win_mtime[0] = oh->win_mtime[0];
5658 in->win_atime[1] = oh->win_atime[1];
5659 in->win_ctime[1] = oh->win_ctime[1];
5660 in->win_mtime[1] = oh->win_mtime[1];
5662 in->yst_uid = oh->yst_uid;
5663 in->yst_gid = oh->yst_gid;
5664 in->yst_atime = oh->yst_atime;
5665 in->yst_mtime = oh->yst_mtime;
5666 in->yst_ctime = oh->yst_ctime;
5667 in->yst_rdev = oh->yst_rdev;
5670 if (oh->shadowsObject > 0)
5671 yaffs_HandleShadowedObject(dev,
5677 yaffs_SetObjectName(in, oh->name);
5679 yaffs_FindOrCreateObjectByNumber
5680 (dev, oh->parentObjectId,
5681 YAFFS_OBJECT_TYPE_DIRECTORY);
5683 fileSize = oh->fileSize;
5684 isShrink = oh->isShrink;
5685 equivalentObjectId = oh->equivalentObjectId;
5689 in->variantType = tags.extraObjectType;
5691 yaffs_FindOrCreateObjectByNumber
5692 (dev, tags.extraParentObjectId,
5693 YAFFS_OBJECT_TYPE_DIRECTORY);
5694 fileSize = tags.extraFileLength;
5695 isShrink = tags.extraIsShrinkHeader;
5696 equivalentObjectId = tags.extraEquivalentObjectId;
5702 /* directory stuff...
5706 if (parent->variantType ==
5707 YAFFS_OBJECT_TYPE_UNKNOWN) {
5708 /* Set up as a directory */
5709 parent->variantType =
5710 YAFFS_OBJECT_TYPE_DIRECTORY;
5711 INIT_LIST_HEAD(&parent->variant.
5714 } else if (parent->variantType !=
5715 YAFFS_OBJECT_TYPE_DIRECTORY)
5717 /* Hoosterman, another problem....
5718 * We're trying to use a non-directory as a directory
5721 T(YAFFS_TRACE_ERROR,
5723 ("yaffs tragedy: attempting to use non-directory as"
5724 " a directory in scan. Put in lost+found."
5726 parent = dev->lostNFoundDir;
5729 yaffs_AddObjectToDirectory(parent, in);
5731 itsUnlinked = (parent == dev->deletedDir) ||
5732 (parent == dev->unlinkedDir);
5735 /* Mark the block as having a shrinkHeader */
5736 bi->hasShrinkHeader = 1;
5739 /* Note re hardlinks.
5740 * Since we might scan a hardlink before its equivalent object is scanned
5741 * we put them all in a list.
5742 * After scanning is complete, we should have all the objects, so we run
5743 * through this list and fix up all the chains.
5746 switch (in->variantType) {
5747 case YAFFS_OBJECT_TYPE_UNKNOWN:
5748 /* Todo got a problem */
5750 case YAFFS_OBJECT_TYPE_FILE:
5752 if (in->variant.fileVariant.
5753 scannedFileSize < fileSize) {
5754 /* This covers the case where the file size is greater
5755 * than where the data is
5756 * This will happen if the file is resized to be larger
5757 * than its current data extents.
5759 in->variant.fileVariant.fileSize = fileSize;
5760 in->variant.fileVariant.scannedFileSize =
5761 in->variant.fileVariant.fileSize;
5765 in->variant.fileVariant.shrinkSize > fileSize) {
5766 in->variant.fileVariant.shrinkSize = fileSize;
5770 case YAFFS_OBJECT_TYPE_HARDLINK:
5772 in->variant.hardLinkVariant.equivalentObjectId =
5774 in->hardLinks.next =
5775 (struct list_head *) hardList;
5779 case YAFFS_OBJECT_TYPE_DIRECTORY:
5782 case YAFFS_OBJECT_TYPE_SPECIAL:
5785 case YAFFS_OBJECT_TYPE_SYMLINK:
5787 in->variant.symLinkVariant.alias =
5788 yaffs_CloneString(oh->
5797 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5798 /* If we got this far while scanning, then the block is fully allocated. */
5799 state = YAFFS_BLOCK_STATE_FULL;
5802 bi->blockState = state;
5804 /* Now let's see if it was dirty */
5805 if (bi->pagesInUse == 0 &&
5806 !bi->hasShrinkHeader &&
5807 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5808 yaffs_BlockBecameDirty(dev, blk);
5814 YFREE_ALT(blockIndex);
5818 /* Ok, we've done all the scanning.
5819 * Fix up the hard link chains.
5820 * We should now have scanned all the objects, now it's time to add these
5823 yaffs_HardlinkFixup(dev,hardList);
5827 * Sort out state of unlinked and deleted objects.
5830 struct list_head *i;
5831 struct list_head *n;
5835 /* Soft delete all the unlinked files */
5836 list_for_each_safe(i, n,
5837 &dev->unlinkedDir->variant.directoryVariant.
5840 l = list_entry(i, yaffs_Object, siblings);
5841 yaffs_DestroyObject(l);
5845 /* Soft delete all the deletedDir files */
5846 list_for_each_safe(i, n,
5847 &dev->deletedDir->variant.directoryVariant.
5850 l = list_entry(i, yaffs_Object, siblings);
5851 yaffs_DestroyObject(l);
5857 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5859 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5864 /*------------------------------ Directory Functions ----------------------------- */
5866 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5868 yaffs_Device *dev = obj->myDev;
5870 if(dev && dev->removeObjectCallback)
5871 dev->removeObjectCallback(obj);
5873 list_del_init(&obj->siblings);
5878 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5883 T(YAFFS_TRACE_ALWAYS,
5885 ("tragedy: Trying to add an object to a null pointer directory"
5889 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5890 T(YAFFS_TRACE_ALWAYS,
5892 ("tragedy: Trying to add an object to a non-directory"
5897 if (obj->siblings.prev == NULL) {
5898 /* Not initialised */
5899 INIT_LIST_HEAD(&obj->siblings);
5901 } else if (!list_empty(&obj->siblings)) {
5902 /* If it is holed up somewhere else, un hook it */
5903 yaffs_RemoveObjectFromDirectory(obj);
5906 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5907 obj->parent = directory;
5909 if (directory == obj->myDev->unlinkedDir
5910 || directory == obj->myDev->deletedDir) {
5912 obj->myDev->nUnlinkedFiles++;
5913 obj->renameAllowed = 0;
5917 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5922 struct list_head *i;
5923 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5932 T(YAFFS_TRACE_ALWAYS,
5934 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5938 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5939 T(YAFFS_TRACE_ALWAYS,
5941 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5945 sum = yaffs_CalcNameSum(name);
5947 list_for_each(i, &directory->variant.directoryVariant.children) {
5949 l = list_entry(i, yaffs_Object, siblings);
5951 yaffs_CheckObjectDetailsLoaded(l);
5953 /* Special case for lost-n-found */
5954 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5955 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5958 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5960 /* LostnFound cunk called Objxxx
5963 yaffs_GetObjectName(l, buffer,
5964 YAFFS_MAX_NAME_LENGTH);
5965 if (yaffs_strcmp(name, buffer) == 0) {
5978 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5979 int (*fn) (yaffs_Object *))
5981 struct list_head *i;
5985 T(YAFFS_TRACE_ALWAYS,
5987 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5991 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5992 T(YAFFS_TRACE_ALWAYS,
5994 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5998 list_for_each(i, &theDir->variant.directoryVariant.children) {
6000 l = list_entry(i, yaffs_Object, siblings);
6012 /* GetEquivalentObject dereferences any hard links to get to the
6016 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6018 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6019 /* We want the object id of the equivalent object, not this one */
6020 obj = obj->variant.hardLinkVariant.equivalentObject;
6026 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6028 memset(name, 0, buffSize * sizeof(YCHAR));
6030 yaffs_CheckObjectDetailsLoaded(obj);
6032 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6033 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6034 } else if (obj->chunkId <= 0) {
6036 /* make up a name */
6037 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6039 yaffs_strncpy(name, locName, buffSize - 1);
6042 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6043 else if (obj->shortName[0]) {
6044 yaffs_strcpy(name, obj->shortName);
6049 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6051 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6053 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6055 if (obj->chunkId >= 0) {
6056 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6057 obj->chunkId, buffer,
6060 yaffs_strncpy(name, oh->name, buffSize - 1);
6062 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6065 return yaffs_strlen(name);
6068 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6071 /* Dereference any hard linking */
6072 obj = yaffs_GetEquivalentObject(obj);
6074 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6075 return obj->variant.fileVariant.fileSize;
6077 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6078 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6080 /* Only a directory should drop through to here */
6081 return obj->myDev->nDataBytesPerChunk;
6085 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6088 struct list_head *i;
6090 if (!obj->unlinked) {
6091 count++; /* the object itself */
6093 list_for_each(i, &obj->hardLinks) {
6094 count++; /* add the hard links; */
6100 int yaffs_GetObjectInode(yaffs_Object * obj)
6102 obj = yaffs_GetEquivalentObject(obj);
6104 return obj->objectId;
6107 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6109 obj = yaffs_GetEquivalentObject(obj);
6111 switch (obj->variantType) {
6112 case YAFFS_OBJECT_TYPE_FILE:
6115 case YAFFS_OBJECT_TYPE_DIRECTORY:
6118 case YAFFS_OBJECT_TYPE_SYMLINK:
6121 case YAFFS_OBJECT_TYPE_HARDLINK:
6124 case YAFFS_OBJECT_TYPE_SPECIAL:
6125 if (S_ISFIFO(obj->yst_mode))
6127 if (S_ISCHR(obj->yst_mode))
6129 if (S_ISBLK(obj->yst_mode))
6131 if (S_ISSOCK(obj->yst_mode))
6139 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6141 obj = yaffs_GetEquivalentObject(obj);
6142 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6143 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6145 return yaffs_CloneString(_Y(""));
6149 #ifndef CONFIG_YAFFS_WINCE
6151 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6153 unsigned int valid = attr->ia_valid;
6155 if (valid & ATTR_MODE)
6156 obj->yst_mode = attr->ia_mode;
6157 if (valid & ATTR_UID)
6158 obj->yst_uid = attr->ia_uid;
6159 if (valid & ATTR_GID)
6160 obj->yst_gid = attr->ia_gid;
6162 if (valid & ATTR_ATIME)
6163 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6164 if (valid & ATTR_CTIME)
6165 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6166 if (valid & ATTR_MTIME)
6167 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6169 if (valid & ATTR_SIZE)
6170 yaffs_ResizeFile(obj, attr->ia_size);
6172 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6177 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6179 unsigned int valid = 0;
6181 attr->ia_mode = obj->yst_mode;
6183 attr->ia_uid = obj->yst_uid;
6185 attr->ia_gid = obj->yst_gid;
6188 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6189 valid |= ATTR_ATIME;
6190 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6191 valid |= ATTR_CTIME;
6192 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6193 valid |= ATTR_MTIME;
6195 attr->ia_size = yaffs_GetFileSize(obj);
6198 attr->ia_valid = valid;
6207 int yaffs_DumpObject(yaffs_Object * obj)
6211 yaffs_GetObjectName(obj, name, 256);
6213 T(YAFFS_TRACE_ALWAYS,
6215 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6216 " chunk %d type %d size %d\n"
6217 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6218 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6219 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6225 /*---------------------------- Initialisation code -------------------------------------- */
6227 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6230 /* Common functions, gotta have */
6231 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6234 #ifdef CONFIG_YAFFS_YAFFS2
6236 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6237 if (dev->writeChunkWithTagsToNAND &&
6238 dev->readChunkWithTagsFromNAND &&
6239 !dev->writeChunkToNAND &&
6240 !dev->readChunkFromNAND &&
6241 dev->markNANDBlockBad && dev->queryNANDBlock)
6245 /* Can use the "spare" style interface for yaffs1 */
6246 if (!dev->isYaffs2 &&
6247 !dev->writeChunkWithTagsToNAND &&
6248 !dev->readChunkWithTagsFromNAND &&
6249 dev->writeChunkToNAND &&
6250 dev->readChunkFromNAND &&
6251 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6258 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6260 /* Initialise the unlinked, deleted, root and lost and found directories */
6262 dev->lostNFoundDir = dev->rootDir = NULL;
6263 dev->unlinkedDir = dev->deletedDir = NULL;
6266 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6268 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6271 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6272 YAFFS_ROOT_MODE | S_IFDIR);
6273 dev->lostNFoundDir =
6274 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6275 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6276 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6279 int yaffs_GutsInitialise(yaffs_Device * dev)
6284 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6286 /* Check stuff that must be set */
6289 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6293 dev->internalStartBlock = dev->startBlock;
6294 dev->internalEndBlock = dev->endBlock;
6295 dev->blockOffset = 0;
6296 dev->chunkOffset = 0;
6297 dev->nFreeChunks = 0;
6299 if (dev->startBlock == 0) {
6300 dev->internalStartBlock = dev->startBlock + 1;
6301 dev->internalEndBlock = dev->endBlock + 1;
6302 dev->blockOffset = 1;
6303 dev->chunkOffset = dev->nChunksPerBlock;
6306 /* Check geometry parameters. */
6308 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
6309 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
6310 dev->nChunksPerBlock < 2 ||
6311 dev->nReservedBlocks < 2 ||
6312 dev->internalStartBlock <= 0 ||
6313 dev->internalEndBlock <= 0 ||
6314 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6316 T(YAFFS_TRACE_ALWAYS,
6318 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6319 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6323 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6324 T(YAFFS_TRACE_ALWAYS,
6325 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6329 /* Got the right mix of functions? */
6330 if (!yaffs_CheckDevFunctions(dev)) {
6331 /* Function missing */
6332 T(YAFFS_TRACE_ALWAYS,
6334 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6339 /* This is really a compilation check. */
6340 if (!yaffs_CheckStructures()) {
6341 T(YAFFS_TRACE_ALWAYS,
6342 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6346 if (dev->isMounted) {
6347 T(YAFFS_TRACE_ALWAYS,
6348 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6352 /* Finished with most checks. One or two more checks happen later on too. */
6358 /* OK now calculate a few things for the device */
6361 * Calculate all the chunk size manipulation numbers:
6363 /* Start off assuming it is a power of 2 */
6364 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
6365 dev->chunkMask = (1<<dev->chunkShift) - 1;
6367 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
6368 /* Yes it is a power of 2, disable crumbs */
6370 dev->crumbShift = 0;
6371 dev->crumbsPerChunk = 0;
6373 /* Not a power of 2, use crumbs instead */
6374 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
6375 dev->crumbMask = (1<<dev->crumbShift)-1;
6376 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
6377 dev->chunkShift = 0;
6383 * Calculate chunkGroupBits.
6384 * We need to find the next power of 2 > than internalEndBlock
6387 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6391 /* Set up tnode width if wide tnodes are enabled. */
6392 if(!dev->wideTnodesDisabled){
6393 /* bits must be even so that we end up with 32-bit words */
6397 dev->tnodeWidth = 16;
6399 dev->tnodeWidth = bits;
6402 dev->tnodeWidth = 16;
6404 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6406 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6407 * so if the bitwidth of the
6408 * chunk range we're using is greater than 16 we need
6409 * to figure out chunk shift and chunkGroupSize
6412 if (bits <= dev->tnodeWidth)
6413 dev->chunkGroupBits = 0;
6415 dev->chunkGroupBits = bits - dev->tnodeWidth;
6418 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6420 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6421 /* We have a problem because the soft delete won't work if
6422 * the chunk group size > chunks per block.
6423 * This can be remedied by using larger "virtual blocks".
6425 T(YAFFS_TRACE_ALWAYS,
6426 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6431 /* OK, we've finished verifying the device, lets continue with initialisation */
6433 /* More device initialisation */
6434 dev->garbageCollections = 0;
6435 dev->passiveGarbageCollections = 0;
6436 dev->currentDirtyChecker = 0;
6437 dev->bufferedBlock = -1;
6438 dev->doingBufferedBlockRewrite = 0;
6439 dev->nDeletedFiles = 0;
6440 dev->nBackgroundDeletions = 0;
6441 dev->nUnlinkedFiles = 0;
6443 dev->eccUnfixed = 0;
6444 dev->tagsEccFixed = 0;
6445 dev->tagsEccUnfixed = 0;
6446 dev->nErasureFailures = 0;
6447 dev->nErasedBlocks = 0;
6449 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
6451 /* Initialise temporary buffers and caches. */
6454 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6455 dev->tempBuffer[i].line = 0; /* not in use */
6456 dev->tempBuffer[i].buffer =
6457 YMALLOC_DMA(dev->nDataBytesPerChunk);
6461 if (dev->nShortOpCaches > 0) {
6464 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6465 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6469 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6471 for (i = 0; i < dev->nShortOpCaches; i++) {
6472 dev->srCache[i].object = NULL;
6473 dev->srCache[i].lastUse = 0;
6474 dev->srCache[i].dirty = 0;
6475 dev->srCache[i].data = YMALLOC_DMA(dev->nDataBytesPerChunk);
6482 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6484 if (dev->isYaffs2) {
6485 dev->useHeaderFileSize = 1;
6488 yaffs_InitialiseBlocks(dev);
6489 yaffs_InitialiseTnodes(dev);
6490 yaffs_InitialiseObjects(dev);
6492 yaffs_CreateInitialDirectories(dev);
6495 /* Now scan the flash. */
6496 if (dev->isYaffs2) {
6497 if(yaffs_CheckpointRestore(dev)) {
6498 T(YAFFS_TRACE_ALWAYS,
6499 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6502 /* Clean up the mess caused by an aborted checkpoint load
6503 * and scan backwards.
6505 yaffs_DeinitialiseBlocks(dev);
6506 yaffs_DeinitialiseTnodes(dev);
6507 yaffs_DeinitialiseObjects(dev);
6508 yaffs_InitialiseBlocks(dev);
6509 yaffs_InitialiseTnodes(dev);
6510 yaffs_InitialiseObjects(dev);
6511 yaffs_CreateInitialDirectories(dev);
6513 yaffs_ScanBackwards(dev);
6518 /* Zero out stats */
6519 dev->nPageReads = 0;
6520 dev->nPageWrites = 0;
6521 dev->nBlockErasures = 0;
6523 dev->nRetriedWrites = 0;
6525 dev->nRetiredBlocks = 0;
6527 yaffs_VerifyFreeChunks(dev);
6529 T(YAFFS_TRACE_TRACING,
6530 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6535 void yaffs_Deinitialise(yaffs_Device * dev)
6537 if (dev->isMounted) {
6540 yaffs_DeinitialiseBlocks(dev);
6541 yaffs_DeinitialiseTnodes(dev);
6542 yaffs_DeinitialiseObjects(dev);
6543 if (dev->nShortOpCaches > 0) {
6545 for (i = 0; i < dev->nShortOpCaches; i++) {
6546 YFREE(dev->srCache[i].data);
6549 YFREE(dev->srCache);
6552 YFREE(dev->gcCleanupList);
6554 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6555 YFREE(dev->tempBuffer[i].buffer);
6563 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6568 yaffs_BlockInfo *blk;
6570 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6572 blk = yaffs_GetBlockInfo(dev, b);
6574 switch (blk->blockState) {
6575 case YAFFS_BLOCK_STATE_EMPTY:
6576 case YAFFS_BLOCK_STATE_ALLOCATING:
6577 case YAFFS_BLOCK_STATE_COLLECTING:
6578 case YAFFS_BLOCK_STATE_FULL:
6580 (dev->nChunksPerBlock - blk->pagesInUse +
6581 blk->softDeletions);
6592 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6594 /* This is what we report to the outside world */
6597 int nDirtyCacheChunks;
6598 int blocksForCheckpoint;
6601 nFree = dev->nFreeChunks;
6603 nFree = yaffs_CountFreeChunks(dev);
6606 nFree += dev->nDeletedFiles;
6608 /* Now count the number of dirty chunks in the cache and subtract those */
6612 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6613 if (dev->srCache[i].dirty)
6614 nDirtyCacheChunks++;
6618 nFree -= nDirtyCacheChunks;
6620 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6622 /* Now we figure out how much to reserve for the checkpoint and report that... */
6623 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6624 if(blocksForCheckpoint < 0)
6625 blocksForCheckpoint = 0;
6627 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6636 static int yaffs_freeVerificationFailures;
6638 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6640 int counted = yaffs_CountFreeChunks(dev);
6642 int difference = dev->nFreeChunks - counted;
6645 T(YAFFS_TRACE_ALWAYS,
6646 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6647 dev->nFreeChunks, counted, difference));
6648 yaffs_freeVerificationFailures++;
6652 /*---------------------------------------- YAFFS test code ----------------------*/
6654 #define yaffs_CheckStruct(structure,syze, name) \
6655 if(sizeof(structure) != syze) \
6657 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6658 name,syze,sizeof(structure))); \
6659 return YAFFS_FAIL; \
6662 static int yaffs_CheckStructures(void)
6664 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6665 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6666 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6667 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6668 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6670 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")