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.43 2006-11-08 09:52:12 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.
2159 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2161 if (!bi->needsRetiring) {
2162 yaffs_InvalidateCheckpoint(dev);
2163 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2165 dev->nErasureFailures++;
2166 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2167 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2171 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2173 for (i = 0; i < dev->nChunksPerBlock; i++) {
2174 if (!yaffs_CheckChunkErased
2175 (dev, blockNo * dev->nChunksPerBlock + i)) {
2176 T(YAFFS_TRACE_ERROR,
2178 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2179 TENDSTR), blockNo, i));
2185 /* Clean it up... */
2186 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2187 dev->nErasedBlocks++;
2189 bi->softDeletions = 0;
2190 bi->hasShrinkHeader = 0;
2191 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2192 bi->gcPrioritise = 0;
2193 yaffs_ClearChunkBits(dev, blockNo);
2195 T(YAFFS_TRACE_ERASE,
2196 (TSTR("Erased block %d" TENDSTR), blockNo));
2198 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2200 yaffs_RetireBlock(dev, blockNo);
2201 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2202 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2206 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2210 yaffs_BlockInfo *bi;
2212 if (dev->nErasedBlocks < 1) {
2213 /* Hoosterman we've got a problem.
2214 * Can't get space to gc
2216 T(YAFFS_TRACE_ERROR,
2217 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2222 /* Find an empty block. */
2224 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2225 dev->allocationBlockFinder++;
2226 if (dev->allocationBlockFinder < dev->internalStartBlock
2227 || dev->allocationBlockFinder > dev->internalEndBlock) {
2228 dev->allocationBlockFinder = dev->internalStartBlock;
2231 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2233 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2234 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2235 dev->sequenceNumber++;
2236 bi->sequenceNumber = dev->sequenceNumber;
2237 dev->nErasedBlocks--;
2238 T(YAFFS_TRACE_ALLOCATE,
2239 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2240 dev->allocationBlockFinder, dev->sequenceNumber,
2241 dev->nErasedBlocks));
2242 return dev->allocationBlockFinder;
2246 T(YAFFS_TRACE_ALWAYS,
2248 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2249 TENDSTR), dev->nErasedBlocks));
2255 // Check if there's space to allocate...
2256 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2257 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2260 int reservedBlocks = dev->nReservedBlocks;
2261 int checkpointBlocks;
2263 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2264 if(checkpointBlocks < 0)
2265 checkpointBlocks = 0;
2267 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2269 return (dev->nFreeChunks > reservedChunks);
2272 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2275 yaffs_BlockInfo *bi;
2277 if (dev->allocationBlock < 0) {
2278 /* Get next block to allocate off */
2279 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2280 dev->allocationPage = 0;
2283 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2284 /* Not enough space to allocate unless we're allowed to use the reserve. */
2288 if (dev->nErasedBlocks < dev->nReservedBlocks
2289 && dev->allocationPage == 0) {
2290 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2293 /* Next page please.... */
2294 if (dev->allocationBlock >= 0) {
2295 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2297 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2298 dev->allocationPage;
2300 yaffs_SetChunkBit(dev, dev->allocationBlock,
2301 dev->allocationPage);
2303 dev->allocationPage++;
2307 /* If the block is full set the state to full */
2308 if (dev->allocationPage >= dev->nChunksPerBlock) {
2309 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2310 dev->allocationBlock = -1;
2319 T(YAFFS_TRACE_ERROR,
2320 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2325 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2329 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2331 if (dev->allocationBlock > 0) {
2332 n += (dev->nChunksPerBlock - dev->allocationPage);
2339 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2345 int retVal = YAFFS_OK;
2348 int isCheckpointBlock;
2350 int chunksBefore = yaffs_GetErasedChunks(dev);
2353 yaffs_ExtendedTags tags;
2355 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2357 yaffs_Object *object;
2359 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2361 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2363 T(YAFFS_TRACE_TRACING,
2364 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2365 bi->pagesInUse, bi->hasShrinkHeader));
2367 /*yaffs_VerifyFreeChunks(dev); */
2369 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2371 /* Take off the number of soft deleted entries because
2372 * they're going to get really deleted during GC.
2374 dev->nFreeChunks -= bi->softDeletions;
2378 if (isCheckpointBlock ||
2379 !yaffs_StillSomeChunkBits(dev, block)) {
2380 T(YAFFS_TRACE_TRACING,
2382 ("Collecting block %d that has no chunks in use" TENDSTR),
2384 yaffs_BlockBecameDirty(dev, block);
2387 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2389 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2390 chunkInBlock < dev->nChunksPerBlock
2391 && yaffs_StillSomeChunkBits(dev, block);
2392 chunkInBlock++, oldChunk++) {
2393 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2395 /* This page is in use and might need to be copied off */
2399 yaffs_InitialiseTags(&tags);
2401 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2405 yaffs_FindObjectByNumber(dev,
2408 T(YAFFS_TRACE_GC_DETAIL,
2410 ("Collecting page %d, %d %d %d " TENDSTR),
2411 chunkInBlock, tags.objectId, tags.chunkId,
2415 T(YAFFS_TRACE_ERROR,
2417 ("page %d in gc has no object "
2418 TENDSTR), oldChunk));
2421 if (object && object->deleted
2422 && tags.chunkId != 0) {
2423 /* Data chunk in a deleted file, throw it away
2424 * It's a soft deleted data chunk,
2425 * No need to copy this, just forget about it and
2426 * fix up the object.
2429 object->nDataChunks--;
2431 if (object->nDataChunks <= 0) {
2432 /* remeber to clean up the object */
2433 dev->gcCleanupList[cleanups] =
2439 /* Todo object && object->deleted && object->nDataChunks == 0 */
2441 /* Deleted object header with no data chunks.
2442 * Can be discarded and the file deleted.
2444 object->chunkId = 0;
2445 yaffs_FreeTnode(object->myDev,
2448 object->variant.fileVariant.top = NULL;
2449 yaffs_DoGenericObjectDeletion(object);
2451 } else if (object) {
2452 /* It's either a data chunk in a live file or
2453 * an ObjectHeader, so we're interested in it.
2454 * NB Need to keep the ObjectHeaders of deleted files
2455 * until the whole file has been deleted off
2457 tags.serialNumber++;
2461 if (tags.chunkId == 0) {
2462 /* It is an object Id,
2463 * We need to nuke the shrinkheader flags first
2464 * We no longer want the shrinkHeader flag since its work is done
2465 * and if it is left in place it will mess up scanning.
2466 * Also, clear out any shadowing stuff
2469 yaffs_ObjectHeader *oh;
2470 oh = (yaffs_ObjectHeader *)buffer;
2472 oh->shadowsObject = -1;
2473 tags.extraShadows = 0;
2474 tags.extraIsShrinkHeader = 0;
2478 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2481 retVal = YAFFS_FAIL;
2484 /* Ok, now fix up the Tnodes etc. */
2486 if (tags.chunkId == 0) {
2488 object->chunkId = newChunk;
2489 object->serial = tags.serialNumber;
2491 /* It's a data chunk */
2492 yaffs_PutChunkIntoFile
2500 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2505 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2508 /* Do any required cleanups */
2509 for (i = 0; i < cleanups; i++) {
2510 /* Time to delete the file too */
2512 yaffs_FindObjectByNumber(dev,
2513 dev->gcCleanupList[i]);
2515 yaffs_FreeTnode(dev,
2516 object->variant.fileVariant.
2518 object->variant.fileVariant.top = NULL;
2521 ("yaffs: About to finally delete object %d"
2522 TENDSTR), object->objectId));
2523 yaffs_DoGenericObjectDeletion(object);
2524 object->myDev->nDeletedFiles--;
2531 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2534 ("gc did not increase free chunks before %d after %d"
2535 TENDSTR), chunksBefore, chunksAfter));
2543 /* New garbage collector
2544 * If we're very low on erased blocks then we do aggressive garbage collection
2545 * otherwise we do "leasurely" garbage collection.
2546 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2547 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2549 * The idea is to help clear out space in a more spread-out manner.
2550 * Dunno if it really does anything useful.
2552 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2556 int gcOk = YAFFS_OK;
2559 int checkpointBlockAdjust;
2561 if (dev->isDoingGC) {
2562 /* Bail out so we don't get recursive gc */
2566 /* This loop should pass the first time.
2567 * We'll only see looping here if the erase of the collected block fails.
2573 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2574 if(checkpointBlockAdjust < 0)
2575 checkpointBlockAdjust = 0;
2577 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2578 /* We need a block soon...*/
2581 /* We're in no hurry */
2585 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2588 dev->garbageCollections++;
2590 dev->passiveGarbageCollections++;
2595 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2596 dev->nErasedBlocks, aggressive));
2598 gcOk = yaffs_GarbageCollectBlock(dev, block);
2601 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2604 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2605 TENDSTR), dev->nErasedBlocks, maxTries, block));
2607 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2610 return aggressive ? gcOk : YAFFS_OK;
2613 /*------------------------- TAGS --------------------------------*/
2615 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2618 return (tags->chunkId == chunkInObject &&
2619 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2624 /*-------------------- Data file manipulation -----------------*/
2626 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2627 yaffs_ExtendedTags * tags)
2629 /*Get the Tnode, then get the level 0 offset chunk offset */
2632 yaffs_ExtendedTags localTags;
2635 yaffs_Device *dev = in->myDev;
2638 /* Passed a NULL, so use our own tags space */
2642 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2645 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2648 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2654 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2655 yaffs_ExtendedTags * tags)
2657 /* Get the Tnode, then get the level 0 offset chunk offset */
2660 yaffs_ExtendedTags localTags;
2662 yaffs_Device *dev = in->myDev;
2666 /* Passed a NULL, so use our own tags space */
2670 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2674 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2677 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2680 /* Delete the entry in the filestructure (if found) */
2682 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2685 /*T(("No level 0 found for %d\n", chunkInInode)); */
2689 /* T(("Could not find %d to delete\n",chunkInInode)); */
2694 #ifdef YAFFS_PARANOID
2696 static int yaffs_CheckFileSanity(yaffs_Object * in)
2704 yaffs_Tags localTags;
2705 yaffs_Tags *tags = &localTags;
2709 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2710 /* T(("Object not a file\n")); */
2714 objId = in->objectId;
2715 fSize = in->variant.fileVariant.fileSize;
2717 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
2719 for (chunk = 1; chunk <= nChunks; chunk++) {
2720 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2725 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2727 if (yaffs_CheckChunkBits
2728 (dev, theChunk / dev->nChunksPerBlock,
2729 theChunk % dev->nChunksPerBlock)) {
2731 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2735 (tags, in->objectId, chunk, chunkDeleted)) {
2745 /* T(("No level 0 found for %d\n", chunk)); */
2749 return failed ? YAFFS_FAIL : YAFFS_OK;
2754 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2755 int chunkInNAND, int inScan)
2757 /* NB inScan is zero unless scanning.
2758 * For forward scanning, inScan is > 0;
2759 * for backward scanning inScan is < 0
2763 yaffs_Device *dev = in->myDev;
2765 yaffs_ExtendedTags existingTags;
2766 yaffs_ExtendedTags newTags;
2767 unsigned existingSerial, newSerial;
2769 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2770 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2771 * If it is not during Scanning then something went wrong!
2774 T(YAFFS_TRACE_ERROR,
2776 ("yaffs tragedy:attempt to put data chunk into a non-file"
2781 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2785 tn = yaffs_AddOrFindLevel0Tnode(dev,
2786 &in->variant.fileVariant,
2793 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2796 /* If we're scanning then we need to test for duplicates
2797 * NB This does not need to be efficient since it should only ever
2798 * happen when the power fails during a write, then only one
2799 * chunk should ever be affected.
2801 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2802 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2805 if (existingChunk != 0) {
2806 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2807 * thus we have to do a FindChunkInFile to get the real chunk id.
2809 * We have a duplicate now we need to decide which one to use:
2811 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2812 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2813 * YAFFS1: Get both sets of tags and compare serial numbers.
2817 /* Only do this for forward scanning */
2818 yaffs_ReadChunkWithTagsFromNAND(dev,
2822 /* Do a proper find */
2824 yaffs_FindChunkInFile(in, chunkInInode,
2828 if (existingChunk <= 0) {
2829 /*Hoosterman - how did this happen? */
2831 T(YAFFS_TRACE_ERROR,
2833 ("yaffs tragedy: existing chunk < 0 in scan"
2838 /* NB The deleted flags should be false, otherwise the chunks will
2839 * not be loaded during a scan
2842 newSerial = newTags.serialNumber;
2843 existingSerial = existingTags.serialNumber;
2846 (in->myDev->isYaffs2 ||
2847 existingChunk <= 0 ||
2848 ((existingSerial + 1) & 3) == newSerial)) {
2849 /* Forward scanning.
2851 * Delete the old one and drop through to update the tnode
2853 yaffs_DeleteChunk(dev, existingChunk, 1,
2856 /* Backward scanning or we want to use the existing one
2858 * Delete the new one and return early so that the tnode isn't changed
2860 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2868 if (existingChunk == 0) {
2872 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2877 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2880 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2882 if (chunkInNAND >= 0) {
2883 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2886 T(YAFFS_TRACE_NANDACCESS,
2887 (TSTR("Chunk %d not found zero instead" TENDSTR),
2889 /* get sane (zero) data if you read a hole */
2890 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2896 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2900 yaffs_ExtendedTags tags;
2901 yaffs_BlockInfo *bi;
2907 block = chunkId / dev->nChunksPerBlock;
2908 page = chunkId % dev->nChunksPerBlock;
2910 bi = yaffs_GetBlockInfo(dev, block);
2912 T(YAFFS_TRACE_DELETION,
2913 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2916 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2918 yaffs_InitialiseTags(&tags);
2920 tags.chunkDeleted = 1;
2922 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2923 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2925 dev->nUnmarkedDeletions++;
2928 /* Pull out of the management area.
2929 * If the whole block became dirty, this will kick off an erasure.
2931 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2932 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2933 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2934 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2937 yaffs_ClearChunkBit(dev, block, page);
2941 if (bi->pagesInUse == 0 &&
2942 !bi->hasShrinkHeader &&
2943 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2944 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2945 yaffs_BlockBecameDirty(dev, block);
2949 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2954 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2955 const __u8 * buffer, int nBytes,
2958 /* Find old chunk Need to do this to get serial number
2959 * Write new one and patch into tree.
2960 * Invalidate old tags.
2964 yaffs_ExtendedTags prevTags;
2967 yaffs_ExtendedTags newTags;
2969 yaffs_Device *dev = in->myDev;
2971 yaffs_CheckGarbageCollection(dev);
2973 /* Get the previous chunk at this location in the file if it exists */
2974 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2976 /* Set up new tags */
2977 yaffs_InitialiseTags(&newTags);
2979 newTags.chunkId = chunkInInode;
2980 newTags.objectId = in->objectId;
2981 newTags.serialNumber =
2982 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2983 newTags.byteCount = nBytes;
2986 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2989 if (newChunkId >= 0) {
2990 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2992 if (prevChunkId >= 0) {
2993 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2997 yaffs_CheckFileSanity(in);
3003 /* UpdateObjectHeader updates the header on NAND for an object.
3004 * If name is not NULL, then that new name is used.
3006 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3007 int isShrink, int shadows)
3010 yaffs_BlockInfo *bi;
3012 yaffs_Device *dev = in->myDev;
3019 yaffs_ExtendedTags newTags;
3021 __u8 *buffer = NULL;
3022 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3024 yaffs_ObjectHeader *oh = NULL;
3026 if (!in->fake || force) {
3028 yaffs_CheckGarbageCollection(dev);
3030 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3031 oh = (yaffs_ObjectHeader *) buffer;
3033 prevChunkId = in->chunkId;
3035 if (prevChunkId >= 0) {
3036 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3038 memcpy(oldName, oh->name, sizeof(oh->name));
3041 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3043 oh->type = in->variantType;
3044 oh->yst_mode = in->yst_mode;
3045 oh->shadowsObject = shadows;
3047 #ifdef CONFIG_YAFFS_WINCE
3048 oh->win_atime[0] = in->win_atime[0];
3049 oh->win_ctime[0] = in->win_ctime[0];
3050 oh->win_mtime[0] = in->win_mtime[0];
3051 oh->win_atime[1] = in->win_atime[1];
3052 oh->win_ctime[1] = in->win_ctime[1];
3053 oh->win_mtime[1] = in->win_mtime[1];
3055 oh->yst_uid = in->yst_uid;
3056 oh->yst_gid = in->yst_gid;
3057 oh->yst_atime = in->yst_atime;
3058 oh->yst_mtime = in->yst_mtime;
3059 oh->yst_ctime = in->yst_ctime;
3060 oh->yst_rdev = in->yst_rdev;
3063 oh->parentObjectId = in->parent->objectId;
3065 oh->parentObjectId = 0;
3068 if (name && *name) {
3069 memset(oh->name, 0, sizeof(oh->name));
3070 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3071 } else if (prevChunkId) {
3072 memcpy(oh->name, oldName, sizeof(oh->name));
3074 memset(oh->name, 0, sizeof(oh->name));
3077 oh->isShrink = isShrink;
3079 switch (in->variantType) {
3080 case YAFFS_OBJECT_TYPE_UNKNOWN:
3081 /* Should not happen */
3083 case YAFFS_OBJECT_TYPE_FILE:
3085 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3086 || oh->parentObjectId ==
3087 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3088 fileVariant.fileSize;
3090 case YAFFS_OBJECT_TYPE_HARDLINK:
3091 oh->equivalentObjectId =
3092 in->variant.hardLinkVariant.equivalentObjectId;
3094 case YAFFS_OBJECT_TYPE_SPECIAL:
3097 case YAFFS_OBJECT_TYPE_DIRECTORY:
3100 case YAFFS_OBJECT_TYPE_SYMLINK:
3101 yaffs_strncpy(oh->alias,
3102 in->variant.symLinkVariant.alias,
3103 YAFFS_MAX_ALIAS_LENGTH);
3104 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3109 yaffs_InitialiseTags(&newTags);
3111 newTags.chunkId = 0;
3112 newTags.objectId = in->objectId;
3113 newTags.serialNumber = in->serial;
3115 /* Add extra info for file header */
3117 newTags.extraHeaderInfoAvailable = 1;
3118 newTags.extraParentObjectId = oh->parentObjectId;
3119 newTags.extraFileLength = oh->fileSize;
3120 newTags.extraIsShrinkHeader = oh->isShrink;
3121 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3122 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3123 newTags.extraObjectType = in->variantType;
3125 /* Create new chunk in NAND */
3127 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3128 (prevChunkId >= 0) ? 1 : 0);
3130 if (newChunkId >= 0) {
3132 in->chunkId = newChunkId;
3134 if (prevChunkId >= 0) {
3135 yaffs_DeleteChunk(dev, prevChunkId, 1,
3139 if(!yaffs_ObjectHasCachedWriteData(in))
3142 /* If this was a shrink, then mark the block that the chunk lives on */
3144 bi = yaffs_GetBlockInfo(in->myDev,
3145 newChunkId /in->myDev-> nChunksPerBlock);
3146 bi->hasShrinkHeader = 1;
3151 retVal = newChunkId;
3156 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3161 /*------------------------ Short Operations Cache ----------------------------------------
3162 * In many situations where there is no high level buffering (eg WinCE) a lot of
3163 * reads might be short sequential reads, and a lot of writes may be short
3164 * sequential writes. eg. scanning/writing a jpeg file.
3165 * In these cases, a short read/write cache can provide a huge perfomance benefit
3166 * with dumb-as-a-rock code.
3167 * In Linux, the page cache provides read buffering aand the short op cache provides write
3170 * There are a limited number (~10) of cache chunks per device so that we don't
3171 * need a very intelligent search.
3174 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3176 yaffs_Device *dev = obj->myDev;
3178 yaffs_ChunkCache *cache;
3179 int nCaches = obj->myDev->nShortOpCaches;
3181 for(i = 0; i < nCaches; i++){
3182 cache = &dev->srCache[i];
3183 if (cache->object == obj &&
3192 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3194 yaffs_Device *dev = obj->myDev;
3195 int lowest = -99; /* Stop compiler whining. */
3197 yaffs_ChunkCache *cache;
3198 int chunkWritten = 0;
3199 int nCaches = obj->myDev->nShortOpCaches;
3205 /* Find the dirty cache for this object with the lowest chunk id. */
3206 for (i = 0; i < nCaches; i++) {
3207 if (dev->srCache[i].object == obj &&
3208 dev->srCache[i].dirty) {
3210 || dev->srCache[i].chunkId <
3212 cache = &dev->srCache[i];
3213 lowest = cache->chunkId;
3218 if (cache && !cache->locked) {
3219 /* Write it out and free it up */
3222 yaffs_WriteChunkDataToObject(cache->object,
3228 cache->object = NULL;
3231 } while (cache && chunkWritten > 0);
3234 /* Hoosterman, disk full while writing cache out. */
3235 T(YAFFS_TRACE_ERROR,
3236 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3243 /*yaffs_FlushEntireDeviceCache(dev)
3248 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3251 int nCaches = dev->nShortOpCaches;
3254 /* Find a dirty object in the cache and flush it...
3255 * until there are no further dirty objects.
3259 for( i = 0; i < nCaches && !obj; i++) {
3260 if (dev->srCache[i].object &&
3261 dev->srCache[i].dirty)
3262 obj = dev->srCache[i].object;
3266 yaffs_FlushFilesChunkCache(obj);
3273 /* Grab us a cache chunk for use.
3274 * First look for an empty one.
3275 * Then look for the least recently used non-dirty one.
3276 * Then look for the least recently used dirty one...., flush and look again.
3278 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3284 if (dev->nShortOpCaches > 0) {
3285 for (i = 0; i < dev->nShortOpCaches; i++) {
3286 if (!dev->srCache[i].object)
3287 return &dev->srCache[i];
3293 usage = 0; /* just to stop the compiler grizzling */
3295 for (i = 0; i < dev->nShortOpCaches; i++) {
3296 if (!dev->srCache[i].dirty &&
3297 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3299 usage = dev->srCache[i].lastUse;
3305 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3312 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3314 yaffs_ChunkCache *cache;
3315 yaffs_Object *theObj;
3320 if (dev->nShortOpCaches > 0) {
3321 /* Try find a non-dirty one... */
3323 cache = yaffs_GrabChunkCacheWorker(dev);
3326 /* They were all dirty, find the last recently used object and flush
3327 * its cache, then find again.
3328 * NB what's here is not very accurate, we actually flush the object
3329 * the last recently used page.
3332 /* With locking we can't assume we can use entry zero */
3339 for (i = 0; i < dev->nShortOpCaches; i++) {
3340 if (dev->srCache[i].object &&
3341 !dev->srCache[i].locked &&
3342 (dev->srCache[i].lastUse < usage || !cache))
3344 usage = dev->srCache[i].lastUse;
3345 theObj = dev->srCache[i].object;
3346 cache = &dev->srCache[i];
3351 if (!cache || cache->dirty) {
3352 /* Flush and try again */
3353 yaffs_FlushFilesChunkCache(theObj);
3354 cache = yaffs_GrabChunkCacheWorker(dev);
3364 /* Find a cached chunk */
3365 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3368 yaffs_Device *dev = obj->myDev;
3370 if (dev->nShortOpCaches > 0) {
3371 for (i = 0; i < dev->nShortOpCaches; i++) {
3372 if (dev->srCache[i].object == obj &&
3373 dev->srCache[i].chunkId == chunkId) {
3376 return &dev->srCache[i];
3383 /* Mark the chunk for the least recently used algorithym */
3384 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3388 if (dev->nShortOpCaches > 0) {
3389 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3390 /* Reset the cache usages */
3392 for (i = 1; i < dev->nShortOpCaches; i++) {
3393 dev->srCache[i].lastUse = 0;
3400 cache->lastUse = dev->srLastUse;
3408 /* Invalidate a single cache page.
3409 * Do this when a whole page gets written,
3410 * ie the short cache for this page is no longer valid.
3412 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3414 if (object->myDev->nShortOpCaches > 0) {
3415 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3418 cache->object = NULL;
3423 /* Invalidate all the cache pages associated with this object
3424 * Do this whenever ther file is deleted or resized.
3426 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3429 yaffs_Device *dev = in->myDev;
3431 if (dev->nShortOpCaches > 0) {
3432 /* Invalidate it. */
3433 for (i = 0; i < dev->nShortOpCaches; i++) {
3434 if (dev->srCache[i].object == in) {
3435 dev->srCache[i].object = NULL;
3441 /*--------------------- Checkpointing --------------------*/
3444 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3446 yaffs_CheckpointValidity cp;
3447 cp.structType = sizeof(cp);
3448 cp.magic = YAFFS_MAGIC;
3449 cp.version = YAFFS_CHECKPOINT_VERSION;
3450 cp.head = (head) ? 1 : 0;
3452 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3456 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3458 yaffs_CheckpointValidity cp;
3461 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3464 ok = (cp.structType == sizeof(cp)) &&
3465 (cp.magic == YAFFS_MAGIC) &&
3466 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
3467 (cp.head == ((head) ? 1 : 0));
3471 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3474 cp->nErasedBlocks = dev->nErasedBlocks;
3475 cp->allocationBlock = dev->allocationBlock;
3476 cp->allocationPage = dev->allocationPage;
3477 cp->nFreeChunks = dev->nFreeChunks;
3479 cp->nDeletedFiles = dev->nDeletedFiles;
3480 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3481 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3482 cp->sequenceNumber = dev->sequenceNumber;
3483 cp->oldestDirtySequence = dev->oldestDirtySequence;
3487 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3488 yaffs_CheckpointDevice *cp)
3490 dev->nErasedBlocks = cp->nErasedBlocks;
3491 dev->allocationBlock = cp->allocationBlock;
3492 dev->allocationPage = cp->allocationPage;
3493 dev->nFreeChunks = cp->nFreeChunks;
3495 dev->nDeletedFiles = cp->nDeletedFiles;
3496 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3497 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3498 dev->sequenceNumber = cp->sequenceNumber;
3499 dev->oldestDirtySequence = cp->oldestDirtySequence;
3503 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3505 yaffs_CheckpointDevice cp;
3507 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3511 /* Write device runtime values*/
3512 yaffs_DeviceToCheckpointDevice(&cp,dev);
3513 cp.structType = sizeof(cp);
3515 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3517 /* Write block info */
3519 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3520 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3523 /* Write chunk bits */
3525 nBytes = nBlocks * dev->chunkBitmapStride;
3526 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3532 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3534 yaffs_CheckpointDevice cp;
3536 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3540 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3544 if(cp.structType != sizeof(cp))
3548 yaffs_CheckpointDeviceToDevice(dev,&cp);
3550 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3552 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3556 nBytes = nBlocks * dev->chunkBitmapStride;
3558 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3563 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3567 cp->objectId = obj->objectId;
3568 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3569 cp->chunkId = obj->chunkId;
3570 cp->variantType = obj->variantType;
3571 cp->deleted = obj->deleted;
3572 cp->softDeleted = obj->softDeleted;
3573 cp->unlinked = obj->unlinked;
3574 cp->fake = obj->fake;
3575 cp->renameAllowed = obj->renameAllowed;
3576 cp->unlinkAllowed = obj->unlinkAllowed;
3577 cp->serial = obj->serial;
3578 cp->nDataChunks = obj->nDataChunks;
3580 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3581 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3582 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3583 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3586 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3589 yaffs_Object *parent;
3591 obj->objectId = cp->objectId;
3594 parent = yaffs_FindOrCreateObjectByNumber(
3597 YAFFS_OBJECT_TYPE_DIRECTORY);
3602 yaffs_AddObjectToDirectory(parent, obj);
3604 obj->chunkId = cp->chunkId;
3605 obj->variantType = cp->variantType;
3606 obj->deleted = cp->deleted;
3607 obj->softDeleted = cp->softDeleted;
3608 obj->unlinked = cp->unlinked;
3609 obj->fake = cp->fake;
3610 obj->renameAllowed = cp->renameAllowed;
3611 obj->unlinkAllowed = cp->unlinkAllowed;
3612 obj->serial = cp->serial;
3613 obj->nDataChunks = cp->nDataChunks;
3615 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3616 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3617 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3618 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3620 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3621 obj->lazyLoaded = 1;
3626 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3627 __u32 level, int chunkOffset)
3630 yaffs_Device *dev = in->myDev;
3632 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3637 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3638 if (tn->internal[i]) {
3639 ok = yaffs_CheckpointTnodeWorker(in,
3642 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3645 } else if (level == 0) {
3646 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
3647 /* printf("write tnode at %d\n",baseOffset); */
3648 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3650 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3658 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3660 __u32 endMarker = ~0;
3663 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3664 ok = yaffs_CheckpointTnodeWorker(obj,
3665 obj->variant.fileVariant.top,
3666 obj->variant.fileVariant.topLevel,
3669 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
3676 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3680 yaffs_Device *dev = obj->myDev;
3681 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3684 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3686 while(ok && (~baseChunk)){
3687 /* Read level 0 tnode */
3689 /* printf("read tnode at %d\n",baseChunk); */
3690 tn = yaffs_GetTnodeRaw(dev);
3692 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3693 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3698 ok = yaffs_AddOrFindLevel0Tnode(dev,
3705 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3713 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3716 yaffs_CheckpointObject cp;
3719 struct list_head *lh;
3722 /* Iterate through the objects in each hash entry,
3723 * dumping them to the checkpointing stream.
3726 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
3727 list_for_each(lh, &dev->objectBucket[i].list) {
3729 obj = list_entry(lh, yaffs_Object, hashLink);
3730 if (!obj->deferedFree) {
3731 yaffs_ObjectToCheckpointObject(&cp,obj);
3732 cp.structType = sizeof(cp);
3734 T(YAFFS_TRACE_CHECKPOINT,(
3735 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3736 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3738 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3740 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3741 ok = yaffs_WriteCheckpointTnodes(obj);
3748 /* Dump end of list */
3749 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3750 cp.structType = sizeof(cp);
3753 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3758 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3761 yaffs_CheckpointObject cp;
3764 yaffs_Object *hardList = NULL;
3766 while(ok && !done) {
3767 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3768 if(cp.structType != sizeof(cp)) {
3769 /* printf("structure parsing failed\n"); */
3773 if(ok && cp.objectId == ~0)
3776 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3777 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3778 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3780 yaffs_CheckpointObjectToObject(obj,&cp);
3781 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3782 ok = yaffs_ReadCheckpointTnodes(obj);
3783 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3784 obj->hardLinks.next =
3785 (struct list_head *)
3795 yaffs_HardlinkFixup(dev,hardList);
3800 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3805 ok = yaffs_CheckpointOpen(dev,1);
3808 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3810 ok = yaffs_WriteCheckpointDevice(dev);
3812 ok = yaffs_WriteCheckpointObjects(dev);
3814 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3816 if(!yaffs_CheckpointClose(dev))
3820 dev->isCheckpointed = 1;
3822 dev->isCheckpointed = 0;
3824 return dev->isCheckpointed;
3827 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3831 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3834 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3836 ok = yaffs_ReadCheckpointDevice(dev);
3838 ok = yaffs_ReadCheckpointObjects(dev);
3840 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3844 if(!yaffs_CheckpointClose(dev))
3848 dev->isCheckpointed = 1;
3850 dev->isCheckpointed = 0;
3856 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3858 if(dev->isCheckpointed ||
3859 dev->blocksInCheckpoint > 0){
3860 dev->isCheckpointed = 0;
3861 yaffs_CheckpointInvalidateStream(dev);
3862 if(dev->superBlock && dev->markSuperBlockDirty)
3863 dev->markSuperBlockDirty(dev->superBlock);
3868 int yaffs_CheckpointSave(yaffs_Device *dev)
3870 yaffs_ReportOddballBlocks(dev);
3871 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3873 if(!dev->isCheckpointed)
3874 yaffs_WriteCheckpointData(dev);
3876 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3878 return dev->isCheckpointed;
3881 int yaffs_CheckpointRestore(yaffs_Device *dev)
3884 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3886 retval = yaffs_ReadCheckpointData(dev);
3888 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3890 yaffs_ReportOddballBlocks(dev);
3895 /*--------------------- File read/write ------------------------
3896 * Read and write have very similar structures.
3897 * In general the read/write has three parts to it
3898 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3899 * Some complete chunks
3900 * An incomplete chunk to end off with
3902 * Curve-balls: the first chunk might also be the last chunk.
3905 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
3914 yaffs_ChunkCache *cache;
3921 //chunk = offset / dev->nDataBytesPerChunk + 1;
3922 //start = offset % dev->nDataBytesPerChunk;
3923 yaffs_AddrToChunk(dev,offset,&chunk,&start);
3926 /* OK now check for the curveball where the start and end are in
3929 if ((start + n) < dev->nDataBytesPerChunk) {
3932 nToCopy = dev->nDataBytesPerChunk - start;
3935 cache = yaffs_FindChunkCache(in, chunk);
3937 /* If the chunk is already in the cache or it is less than a whole chunk
3938 * then use the cache (if there is caching)
3939 * else bypass the cache.
3941 if (cache || nToCopy != dev->nDataBytesPerChunk) {
3942 if (dev->nShortOpCaches > 0) {
3944 /* If we can't find the data in the cache, then load it up. */
3947 cache = yaffs_GrabChunkCache(in->myDev);
3949 cache->chunkId = chunk;
3952 yaffs_ReadChunkDataFromObject(in, chunk,
3958 yaffs_UseChunkCache(dev, cache, 0);
3962 #ifdef CONFIG_YAFFS_WINCE
3963 yfsd_UnlockYAFFS(TRUE);
3965 memcpy(buffer, &cache->data[start], nToCopy);
3967 #ifdef CONFIG_YAFFS_WINCE
3968 yfsd_LockYAFFS(TRUE);
3972 /* Read into the local buffer then copy..*/
3975 yaffs_GetTempBuffer(dev, __LINE__);
3976 yaffs_ReadChunkDataFromObject(in, chunk,
3978 #ifdef CONFIG_YAFFS_WINCE
3979 yfsd_UnlockYAFFS(TRUE);
3981 memcpy(buffer, &localBuffer[start], nToCopy);
3983 #ifdef CONFIG_YAFFS_WINCE
3984 yfsd_LockYAFFS(TRUE);
3986 yaffs_ReleaseTempBuffer(dev, localBuffer,
3991 #ifdef CONFIG_YAFFS_WINCE
3992 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3994 /* Under WinCE can't do direct transfer. Need to use a local buffer.
3995 * This is because we otherwise screw up WinCE's memory mapper
3997 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3999 #ifdef CONFIG_YAFFS_WINCE
4000 yfsd_UnlockYAFFS(TRUE);
4002 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4004 #ifdef CONFIG_YAFFS_WINCE
4005 yfsd_LockYAFFS(TRUE);
4006 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4010 /* A full chunk. Read directly into the supplied buffer. */
4011 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4025 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4026 int nBytes, int writeThrough)
4035 int startOfWrite = offset;
4036 int chunkWritten = 0;
4043 while (n > 0 && chunkWritten >= 0) {
4044 //chunk = offset / dev->nDataBytesPerChunk + 1;
4045 //start = offset % dev->nDataBytesPerChunk;
4046 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4049 /* OK now check for the curveball where the start and end are in
4053 if ((start + n) < dev->nDataBytesPerChunk) {
4056 /* Now folks, to calculate how many bytes to write back....
4057 * If we're overwriting and not writing to then end of file then
4058 * we need to write back as much as was there before.
4062 in->variant.fileVariant.fileSize -
4063 ((chunk - 1) * dev->nDataBytesPerChunk);
4065 if (nBytesRead > dev->nDataBytesPerChunk) {
4066 nBytesRead = dev->nDataBytesPerChunk;
4071 (start + n)) ? nBytesRead : (start + n);
4074 nToCopy = dev->nDataBytesPerChunk - start;
4075 nToWriteBack = dev->nDataBytesPerChunk;
4078 if (nToCopy != dev->nDataBytesPerChunk) {
4079 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4080 if (dev->nShortOpCaches > 0) {
4081 yaffs_ChunkCache *cache;
4082 /* If we can't find the data in the cache, then load the cache */
4083 cache = yaffs_FindChunkCache(in, chunk);
4086 && yaffs_CheckSpaceForAllocation(in->
4088 cache = yaffs_GrabChunkCache(in->myDev);
4090 cache->chunkId = chunk;
4093 yaffs_ReadChunkDataFromObject(in, chunk,
4099 !yaffs_CheckSpaceForAllocation(in->myDev)){
4100 /* Drop the cache if it was a read cache item and
4101 * no space check has been made for it.
4107 yaffs_UseChunkCache(dev, cache, 1);
4109 #ifdef CONFIG_YAFFS_WINCE
4110 yfsd_UnlockYAFFS(TRUE);
4113 memcpy(&cache->data[start], buffer,
4116 #ifdef CONFIG_YAFFS_WINCE
4117 yfsd_LockYAFFS(TRUE);
4120 cache->nBytes = nToWriteBack;
4124 yaffs_WriteChunkDataToObject
4127 cache->data, cache->nBytes,
4133 chunkWritten = -1; /* fail the write */
4136 /* An incomplete start or end chunk (or maybe both start and end chunk)
4137 * Read into the local buffer then copy, then copy over and write back.
4141 yaffs_GetTempBuffer(dev, __LINE__);
4143 yaffs_ReadChunkDataFromObject(in, chunk,
4146 #ifdef CONFIG_YAFFS_WINCE
4147 yfsd_UnlockYAFFS(TRUE);
4150 memcpy(&localBuffer[start], buffer, nToCopy);
4152 #ifdef CONFIG_YAFFS_WINCE
4153 yfsd_LockYAFFS(TRUE);
4156 yaffs_WriteChunkDataToObject(in, chunk,
4161 yaffs_ReleaseTempBuffer(dev, localBuffer,
4168 #ifdef CONFIG_YAFFS_WINCE
4169 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4170 * This is because we otherwise screw up WinCE's memory mapper
4172 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4173 #ifdef CONFIG_YAFFS_WINCE
4174 yfsd_UnlockYAFFS(TRUE);
4176 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4177 #ifdef CONFIG_YAFFS_WINCE
4178 yfsd_LockYAFFS(TRUE);
4181 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4182 dev->nDataBytesPerChunk,
4184 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4186 /* A full chunk. Write directly from the supplied buffer. */
4188 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4189 dev->nDataBytesPerChunk,
4192 /* Since we've overwritten the cached data, we better invalidate it. */
4193 yaffs_InvalidateChunkCache(in, chunk);
4196 if (chunkWritten >= 0) {
4205 /* Update file object */
4207 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4208 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4217 /* ---------------------- File resizing stuff ------------------ */
4219 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4222 yaffs_Device *dev = in->myDev;
4223 int oldFileSize = in->variant.fileVariant.fileSize;
4225 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4227 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4228 dev->nDataBytesPerChunk;
4232 /* Delete backwards so that we don't end up with holes if
4233 * power is lost part-way through the operation.
4235 for (i = lastDel; i >= startDel; i--) {
4236 /* NB this could be optimised somewhat,
4237 * eg. could retrieve the tags and write them without
4238 * using yaffs_DeleteChunk
4241 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4244 (dev->internalStartBlock * dev->nChunksPerBlock)
4246 ((dev->internalEndBlock +
4247 1) * dev->nChunksPerBlock)) {
4248 T(YAFFS_TRACE_ALWAYS,
4249 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4253 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4260 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4263 int oldFileSize = in->variant.fileVariant.fileSize;
4264 int newSizeOfPartialChunk;
4267 yaffs_Device *dev = in->myDev;
4269 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4271 yaffs_FlushFilesChunkCache(in);
4272 yaffs_InvalidateWholeChunkCache(in);
4274 yaffs_CheckGarbageCollection(dev);
4276 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4277 return yaffs_GetFileSize(in);
4280 if (newSize == oldFileSize) {
4284 if (newSize < oldFileSize) {
4286 yaffs_PruneResizedChunks(in, newSize);
4288 if (newSizeOfPartialChunk != 0) {
4289 int lastChunk = 1 + newFullChunks;
4291 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4293 /* Got to read and rewrite the last chunk with its new size and zero pad */
4294 yaffs_ReadChunkDataFromObject(in, lastChunk,
4297 memset(localBuffer + newSizeOfPartialChunk, 0,
4298 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4300 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4301 newSizeOfPartialChunk, 1);
4303 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4306 in->variant.fileVariant.fileSize = newSize;
4308 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4310 /* Write a new object header.
4311 * show we've shrunk the file, if need be
4312 * Do this only if the file is not in the deleted directories.
4314 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4315 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4316 yaffs_UpdateObjectHeader(in, NULL, 0,
4317 (newSize < oldFileSize) ? 1 : 0, 0);
4323 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4325 obj = yaffs_GetEquivalentObject(obj);
4327 switch (obj->variantType) {
4328 case YAFFS_OBJECT_TYPE_FILE:
4329 return obj->variant.fileVariant.fileSize;
4330 case YAFFS_OBJECT_TYPE_SYMLINK:
4331 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4339 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4343 yaffs_FlushFilesChunkCache(in);
4345 #ifdef CONFIG_YAFFS_WINCE
4346 yfsd_WinFileTimeNow(in->win_mtime);
4349 in->yst_mtime = Y_CURRENT_TIME;
4355 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4356 0) ? YAFFS_OK : YAFFS_FAIL;
4365 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4368 /* First off, invalidate the file's data in the cache, without flushing. */
4369 yaffs_InvalidateWholeChunkCache(in);
4371 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4372 /* Move to the unlinked directory so we have a record that it was deleted. */
4373 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4377 yaffs_RemoveObjectFromDirectory(in);
4378 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4381 yaffs_FreeObject(in);
4386 /* yaffs_DeleteFile deletes the whole file data
4387 * and the inode associated with the file.
4388 * It does not delete the links associated with the file.
4390 static int yaffs_UnlinkFile(yaffs_Object * in)
4394 int immediateDeletion = 0;
4399 immediateDeletion = 1;
4403 if (in->inUse <= 0) {
4404 immediateDeletion = 1;
4408 if (immediateDeletion) {
4410 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4412 T(YAFFS_TRACE_TRACING,
4413 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4416 in->myDev->nDeletedFiles++;
4417 if (0 && in->myDev->isYaffs2) {
4418 yaffs_ResizeFile(in, 0);
4420 yaffs_SoftDeleteFile(in);
4423 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4431 int yaffs_DeleteFile(yaffs_Object * in)
4433 int retVal = YAFFS_OK;
4435 if (in->nDataChunks > 0) {
4436 /* Use soft deletion if there is data in the file */
4437 if (!in->unlinked) {
4438 retVal = yaffs_UnlinkFile(in);
4440 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4442 in->myDev->nDeletedFiles++;
4443 yaffs_SoftDeleteFile(in);
4445 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4447 /* The file has no data chunks so we toss it immediately */
4448 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4449 in->variant.fileVariant.top = NULL;
4450 yaffs_DoGenericObjectDeletion(in);
4456 static int yaffs_DeleteDirectory(yaffs_Object * in)
4458 /* First check that the directory is empty. */
4459 if (list_empty(&in->variant.directoryVariant.children)) {
4460 return yaffs_DoGenericObjectDeletion(in);
4467 static int yaffs_DeleteSymLink(yaffs_Object * in)
4469 YFREE(in->variant.symLinkVariant.alias);
4471 return yaffs_DoGenericObjectDeletion(in);
4474 static int yaffs_DeleteHardLink(yaffs_Object * in)
4476 /* remove this hardlink from the list assocaited with the equivalent
4479 list_del(&in->hardLinks);
4480 return yaffs_DoGenericObjectDeletion(in);
4483 static void yaffs_DestroyObject(yaffs_Object * obj)
4485 switch (obj->variantType) {
4486 case YAFFS_OBJECT_TYPE_FILE:
4487 yaffs_DeleteFile(obj);
4489 case YAFFS_OBJECT_TYPE_DIRECTORY:
4490 yaffs_DeleteDirectory(obj);
4492 case YAFFS_OBJECT_TYPE_SYMLINK:
4493 yaffs_DeleteSymLink(obj);
4495 case YAFFS_OBJECT_TYPE_HARDLINK:
4496 yaffs_DeleteHardLink(obj);
4498 case YAFFS_OBJECT_TYPE_SPECIAL:
4499 yaffs_DoGenericObjectDeletion(obj);
4501 case YAFFS_OBJECT_TYPE_UNKNOWN:
4502 break; /* should not happen. */
4506 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4509 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4510 return yaffs_DeleteHardLink(obj);
4511 } else if (!list_empty(&obj->hardLinks)) {
4512 /* Curve ball: We're unlinking an object that has a hardlink.
4514 * This problem arises because we are not strictly following
4515 * The Linux link/inode model.
4517 * We can't really delete the object.
4518 * Instead, we do the following:
4519 * - Select a hardlink.
4520 * - Unhook it from the hard links
4521 * - Unhook it from its parent directory (so that the rename can work)
4522 * - Rename the object to the hardlink's name.
4523 * - Delete the hardlink
4528 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4530 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4532 list_del_init(&hl->hardLinks);
4533 list_del_init(&hl->siblings);
4535 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4537 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4539 if (retVal == YAFFS_OK) {
4540 retVal = yaffs_DoGenericObjectDeletion(hl);
4545 switch (obj->variantType) {
4546 case YAFFS_OBJECT_TYPE_FILE:
4547 return yaffs_UnlinkFile(obj);
4549 case YAFFS_OBJECT_TYPE_DIRECTORY:
4550 return yaffs_DeleteDirectory(obj);
4552 case YAFFS_OBJECT_TYPE_SYMLINK:
4553 return yaffs_DeleteSymLink(obj);
4555 case YAFFS_OBJECT_TYPE_SPECIAL:
4556 return yaffs_DoGenericObjectDeletion(obj);
4558 case YAFFS_OBJECT_TYPE_HARDLINK:
4559 case YAFFS_OBJECT_TYPE_UNKNOWN:
4567 static int yaffs_UnlinkObject( yaffs_Object *obj)
4570 if (obj && obj->unlinkAllowed) {
4571 return yaffs_UnlinkWorker(obj);
4577 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4581 obj = yaffs_FindObjectByName(dir, name);
4582 return yaffs_UnlinkObject(obj);
4585 /*----------------------- Initialisation Scanning ---------------------- */
4587 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4588 int backwardScanning)
4592 if (!backwardScanning) {
4593 /* Handle YAFFS1 forward scanning case
4594 * For YAFFS1 we always do the deletion
4598 /* Handle YAFFS2 case (backward scanning)
4599 * If the shadowed object exists then ignore.
4601 if (yaffs_FindObjectByNumber(dev, objId)) {
4606 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4607 * We put it in unlinked dir to be cleaned up after the scanning
4610 yaffs_FindOrCreateObjectByNumber(dev, objId,
4611 YAFFS_OBJECT_TYPE_FILE);
4612 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4613 obj->variant.fileVariant.shrinkSize = 0;
4614 obj->valid = 1; /* So that we don't read any other info for this file */
4624 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4631 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4633 in = yaffs_FindObjectByNumber(dev,
4634 hl->variant.hardLinkVariant.
4635 equivalentObjectId);
4638 /* Add the hardlink pointers */
4639 hl->variant.hardLinkVariant.equivalentObject = in;
4640 list_add(&hl->hardLinks, &in->hardLinks);
4642 /* Todo Need to report/handle this better.
4643 * Got a problem... hardlink to a non-existant object
4645 hl->variant.hardLinkVariant.equivalentObject = NULL;
4646 INIT_LIST_HEAD(&hl->hardLinks);
4658 static int ybicmp(const void *a, const void *b){
4659 register int aseq = ((yaffs_BlockIndex *)a)->seq;
4660 register int bseq = ((yaffs_BlockIndex *)b)->seq;
4661 register int ablock = ((yaffs_BlockIndex *)a)->block;
4662 register int bblock = ((yaffs_BlockIndex *)b)->block;
4664 return ablock - bblock;
4670 static int yaffs_Scan(yaffs_Device * dev)
4672 yaffs_ExtendedTags tags;
4677 int nBlocksToScan = 0;
4683 yaffs_BlockState state;
4684 yaffs_Object *hardList = NULL;
4686 yaffs_BlockInfo *bi;
4688 yaffs_ObjectHeader *oh;
4690 yaffs_Object *parent;
4691 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4695 yaffs_BlockIndex *blockIndex = NULL;
4697 if (dev->isYaffs2) {
4699 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4703 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4706 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
4707 dev->internalStartBlock, dev->internalEndBlock));
4709 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4711 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4713 if (dev->isYaffs2) {
4714 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4717 /* Scan all the blocks to determine their state */
4718 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4719 bi = yaffs_GetBlockInfo(dev, blk);
4720 yaffs_ClearChunkBits(dev, blk);
4722 bi->softDeletions = 0;
4724 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4726 bi->blockState = state;
4727 bi->sequenceNumber = sequenceNumber;
4729 T(YAFFS_TRACE_SCAN_DEBUG,
4730 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4731 state, sequenceNumber));
4733 if (state == YAFFS_BLOCK_STATE_DEAD) {
4734 T(YAFFS_TRACE_BAD_BLOCKS,
4735 (TSTR("block %d is bad" TENDSTR), blk));
4736 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4737 T(YAFFS_TRACE_SCAN_DEBUG,
4738 (TSTR("Block empty " TENDSTR)));
4739 dev->nErasedBlocks++;
4740 dev->nFreeChunks += dev->nChunksPerBlock;
4741 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4743 /* Determine the highest sequence number */
4744 if (dev->isYaffs2 &&
4745 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4746 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4748 blockIndex[nBlocksToScan].seq = sequenceNumber;
4749 blockIndex[nBlocksToScan].block = blk;
4753 if (sequenceNumber >= dev->sequenceNumber) {
4754 dev->sequenceNumber = sequenceNumber;
4756 } else if (dev->isYaffs2) {
4757 /* TODO: Nasty sequence number! */
4760 ("Block scanning block %d has bad sequence number %d"
4761 TENDSTR), blk, sequenceNumber));
4768 * Dungy old bubble sort for now...
4770 if (dev->isYaffs2) {
4771 yaffs_BlockIndex temp;
4775 for (i = 0; i < nBlocksToScan; i++)
4776 for (j = i + 1; j < nBlocksToScan; j++)
4777 if (blockIndex[i].seq > blockIndex[j].seq) {
4778 temp = blockIndex[j];
4779 blockIndex[j] = blockIndex[i];
4780 blockIndex[i] = temp;
4784 /* Now scan the blocks looking at the data. */
4785 if (dev->isYaffs2) {
4787 endIterator = nBlocksToScan - 1;
4788 T(YAFFS_TRACE_SCAN_DEBUG,
4789 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4791 startIterator = dev->internalStartBlock;
4792 endIterator = dev->internalEndBlock;
4795 /* For each block.... */
4796 for (blockIterator = startIterator; blockIterator <= endIterator;
4799 if (dev->isYaffs2) {
4800 /* get the block to scan in the correct order */
4801 blk = blockIndex[blockIterator].block;
4803 blk = blockIterator;
4806 bi = yaffs_GetBlockInfo(dev, blk);
4807 state = bi->blockState;
4811 /* For each chunk in each block that needs scanning....*/
4812 for (c = 0; c < dev->nChunksPerBlock &&
4813 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4814 /* Read the tags and decide what to do */
4815 chunk = blk * dev->nChunksPerBlock + c;
4817 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4820 /* Let's have a good look at this chunk... */
4822 if (!dev->isYaffs2 && tags.chunkDeleted) {
4828 /*T((" %d %d deleted\n",blk,c)); */
4829 } else if (!tags.chunkUsed) {
4830 /* An unassigned chunk in the block
4831 * This means that either the block is empty or
4832 * this is the one being allocated from
4836 /* We're looking at the first chunk in the block so the block is unused */
4837 state = YAFFS_BLOCK_STATE_EMPTY;
4838 dev->nErasedBlocks++;
4840 /* this is the block being allocated from */
4843 (" Allocating from %d %d" TENDSTR),
4845 state = YAFFS_BLOCK_STATE_ALLOCATING;
4846 dev->allocationBlock = blk;
4847 dev->allocationPage = c;
4848 dev->allocationBlockFinder = blk;
4849 /* Set it to here to encourage the allocator to go forth from here. */
4851 /* Yaffs2 sanity check:
4852 * This should be the one with the highest sequence number
4855 && (dev->sequenceNumber !=
4856 bi->sequenceNumber)) {
4857 T(YAFFS_TRACE_ALWAYS,
4859 ("yaffs: Allocation block %d was not highest sequence id:"
4860 " block seq = %d, dev seq = %d"
4861 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4865 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4866 } else if (tags.chunkId > 0) {
4867 /* chunkId > 0 so it is a data chunk... */
4868 unsigned int endpos;
4870 yaffs_SetChunkBit(dev, blk, c);
4873 in = yaffs_FindOrCreateObjectByNumber(dev,
4876 YAFFS_OBJECT_TYPE_FILE);
4877 /* PutChunkIntoFile checks for a clash (two data chunks with
4878 * the same chunkId).
4880 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4883 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
4885 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4886 && in->variant.fileVariant.scannedFileSize <
4888 in->variant.fileVariant.
4889 scannedFileSize = endpos;
4890 if (!dev->useHeaderFileSize) {
4891 in->variant.fileVariant.
4893 in->variant.fileVariant.
4898 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
4900 /* chunkId == 0, so it is an ObjectHeader.
4901 * Thus, we read in the object header and make the object
4903 yaffs_SetChunkBit(dev, blk, c);
4906 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4910 oh = (yaffs_ObjectHeader *) chunkData;
4912 in = yaffs_FindObjectByNumber(dev,
4914 if (in && in->variantType != oh->type) {
4915 /* This should not happen, but somehow
4916 * Wev'e ended up with an objectId that has been reused but not yet
4917 * deleted, and worse still it has changed type. Delete the old object.
4920 yaffs_DestroyObject(in);
4925 in = yaffs_FindOrCreateObjectByNumber(dev,
4930 if (oh->shadowsObject > 0) {
4931 yaffs_HandleShadowedObject(dev,
4938 /* We have already filled this one. We have a duplicate and need to resolve it. */
4940 unsigned existingSerial = in->serial;
4941 unsigned newSerial = tags.serialNumber;
4943 if (dev->isYaffs2 ||
4944 ((existingSerial + 1) & 3) ==
4946 /* Use new one - destroy the exisiting one */
4947 yaffs_DeleteChunk(dev,
4952 /* Use existing - destroy this one. */
4953 yaffs_DeleteChunk(dev, chunk, 1,
4959 (tags.objectId == YAFFS_OBJECTID_ROOT ||
4960 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4961 /* We only load some info, don't fiddle with directory structure */
4963 in->variantType = oh->type;
4965 in->yst_mode = oh->yst_mode;
4966 #ifdef CONFIG_YAFFS_WINCE
4967 in->win_atime[0] = oh->win_atime[0];
4968 in->win_ctime[0] = oh->win_ctime[0];
4969 in->win_mtime[0] = oh->win_mtime[0];
4970 in->win_atime[1] = oh->win_atime[1];
4971 in->win_ctime[1] = oh->win_ctime[1];
4972 in->win_mtime[1] = oh->win_mtime[1];
4974 in->yst_uid = oh->yst_uid;
4975 in->yst_gid = oh->yst_gid;
4976 in->yst_atime = oh->yst_atime;
4977 in->yst_mtime = oh->yst_mtime;
4978 in->yst_ctime = oh->yst_ctime;
4979 in->yst_rdev = oh->yst_rdev;
4981 in->chunkId = chunk;
4983 } else if (!in->valid) {
4984 /* we need to load this info */
4987 in->variantType = oh->type;
4989 in->yst_mode = oh->yst_mode;
4990 #ifdef CONFIG_YAFFS_WINCE
4991 in->win_atime[0] = oh->win_atime[0];
4992 in->win_ctime[0] = oh->win_ctime[0];
4993 in->win_mtime[0] = oh->win_mtime[0];
4994 in->win_atime[1] = oh->win_atime[1];
4995 in->win_ctime[1] = oh->win_ctime[1];
4996 in->win_mtime[1] = oh->win_mtime[1];
4998 in->yst_uid = oh->yst_uid;
4999 in->yst_gid = oh->yst_gid;
5000 in->yst_atime = oh->yst_atime;
5001 in->yst_mtime = oh->yst_mtime;
5002 in->yst_ctime = oh->yst_ctime;
5003 in->yst_rdev = oh->yst_rdev;
5005 in->chunkId = chunk;
5007 yaffs_SetObjectName(in, oh->name);
5010 /* directory stuff...
5015 yaffs_FindOrCreateObjectByNumber
5016 (dev, oh->parentObjectId,
5017 YAFFS_OBJECT_TYPE_DIRECTORY);
5018 if (parent->variantType ==
5019 YAFFS_OBJECT_TYPE_UNKNOWN) {
5020 /* Set up as a directory */
5021 parent->variantType =
5022 YAFFS_OBJECT_TYPE_DIRECTORY;
5023 INIT_LIST_HEAD(&parent->variant.
5026 } else if (parent->variantType !=
5027 YAFFS_OBJECT_TYPE_DIRECTORY)
5029 /* Hoosterman, another problem....
5030 * We're trying to use a non-directory as a directory
5033 T(YAFFS_TRACE_ERROR,
5035 ("yaffs tragedy: attempting to use non-directory as"
5036 " a directory in scan. Put in lost+found."
5038 parent = dev->lostNFoundDir;
5041 yaffs_AddObjectToDirectory(parent, in);
5043 if (0 && (parent == dev->deletedDir ||
5044 parent == dev->unlinkedDir)) {
5045 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5046 dev->nDeletedFiles++;
5048 /* Note re hardlinks.
5049 * Since we might scan a hardlink before its equivalent object is scanned
5050 * we put them all in a list.
5051 * After scanning is complete, we should have all the objects, so we run through this
5052 * list and fix up all the chains.
5055 switch (in->variantType) {
5056 case YAFFS_OBJECT_TYPE_UNKNOWN:
5057 /* Todo got a problem */
5059 case YAFFS_OBJECT_TYPE_FILE:
5062 /* Prune back the shrunken chunks */
5063 yaffs_PruneResizedChunks
5065 /* Mark the block as having a shrinkHeader */
5066 bi->hasShrinkHeader = 1;
5069 if (dev->useHeaderFileSize)
5071 in->variant.fileVariant.
5076 case YAFFS_OBJECT_TYPE_HARDLINK:
5077 in->variant.hardLinkVariant.
5078 equivalentObjectId =
5079 oh->equivalentObjectId;
5080 in->hardLinks.next =
5081 (struct list_head *)
5085 case YAFFS_OBJECT_TYPE_DIRECTORY:
5088 case YAFFS_OBJECT_TYPE_SPECIAL:
5091 case YAFFS_OBJECT_TYPE_SYMLINK:
5092 in->variant.symLinkVariant.
5094 yaffs_CloneString(oh->alias);
5098 if (parent == dev->deletedDir) {
5099 yaffs_DestroyObject(in);
5100 bi->hasShrinkHeader = 1;
5106 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5107 /* If we got this far while scanning, then the block is fully allocated.*/
5108 state = YAFFS_BLOCK_STATE_FULL;
5111 bi->blockState = state;
5113 /* Now let's see if it was dirty */
5114 if (bi->pagesInUse == 0 &&
5115 !bi->hasShrinkHeader &&
5116 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5117 yaffs_BlockBecameDirty(dev, blk);
5127 /* Ok, we've done all the scanning.
5128 * Fix up the hard link chains.
5129 * We should now have scanned all the objects, now it's time to add these
5133 yaffs_HardlinkFixup(dev,hardList);
5135 /* Handle the unlinked files. Since they were left in an unlinked state we should
5139 struct list_head *i;
5140 struct list_head *n;
5143 /* Soft delete all the unlinked files */
5144 list_for_each_safe(i, n,
5145 &dev->unlinkedDir->variant.directoryVariant.
5148 l = list_entry(i, yaffs_Object, siblings);
5149 yaffs_DestroyObject(l);
5154 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5156 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5161 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5164 yaffs_ObjectHeader *oh;
5165 yaffs_Device *dev = in->myDev;
5166 yaffs_ExtendedTags tags;
5170 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5172 in->lazyLoaded ? "not yet" : "already"));
5177 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5179 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5180 oh = (yaffs_ObjectHeader *) chunkData;
5182 in->yst_mode = oh->yst_mode;
5183 #ifdef CONFIG_YAFFS_WINCE
5184 in->win_atime[0] = oh->win_atime[0];
5185 in->win_ctime[0] = oh->win_ctime[0];
5186 in->win_mtime[0] = oh->win_mtime[0];
5187 in->win_atime[1] = oh->win_atime[1];
5188 in->win_ctime[1] = oh->win_ctime[1];
5189 in->win_mtime[1] = oh->win_mtime[1];
5191 in->yst_uid = oh->yst_uid;
5192 in->yst_gid = oh->yst_gid;
5193 in->yst_atime = oh->yst_atime;
5194 in->yst_mtime = oh->yst_mtime;
5195 in->yst_ctime = oh->yst_ctime;
5196 in->yst_rdev = oh->yst_rdev;
5199 yaffs_SetObjectName(in, oh->name);
5201 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
5202 in->variant.symLinkVariant.alias =
5203 yaffs_CloneString(oh->alias);
5205 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5209 static int yaffs_ScanBackwards(yaffs_Device * dev)
5211 yaffs_ExtendedTags tags;
5216 int nBlocksToScan = 0;
5222 yaffs_BlockState state;
5223 yaffs_Object *hardList = NULL;
5224 yaffs_BlockInfo *bi;
5226 yaffs_ObjectHeader *oh;
5228 yaffs_Object *parent;
5229 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5235 int foundChunksInBlock;
5236 int equivalentObjectId;
5239 yaffs_BlockIndex *blockIndex = NULL;
5240 int altBlockIndex = 0;
5242 if (!dev->isYaffs2) {
5244 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5250 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5251 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5254 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5256 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5259 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5265 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5269 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5271 /* Scan all the blocks to determine their state */
5272 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5273 bi = yaffs_GetBlockInfo(dev, blk);
5274 yaffs_ClearChunkBits(dev, blk);
5276 bi->softDeletions = 0;
5278 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5280 bi->blockState = state;
5281 bi->sequenceNumber = sequenceNumber;
5283 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5284 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5286 T(YAFFS_TRACE_SCAN_DEBUG,
5287 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5288 state, sequenceNumber));
5291 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5292 /* todo .. fix free space ? */
5294 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5295 T(YAFFS_TRACE_BAD_BLOCKS,
5296 (TSTR("block %d is bad" TENDSTR), blk));
5297 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5298 T(YAFFS_TRACE_SCAN_DEBUG,
5299 (TSTR("Block empty " TENDSTR)));
5300 dev->nErasedBlocks++;
5301 dev->nFreeChunks += dev->nChunksPerBlock;
5302 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5304 /* Determine the highest sequence number */
5305 if (dev->isYaffs2 &&
5306 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5307 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5309 blockIndex[nBlocksToScan].seq = sequenceNumber;
5310 blockIndex[nBlocksToScan].block = blk;
5314 if (sequenceNumber >= dev->sequenceNumber) {
5315 dev->sequenceNumber = sequenceNumber;
5317 } else if (dev->isYaffs2) {
5318 /* TODO: Nasty sequence number! */
5321 ("Block scanning block %d has bad sequence number %d"
5322 TENDSTR), blk, sequenceNumber));
5329 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5335 /* Sort the blocks */
5336 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5338 /* Use qsort now. */
5339 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5343 /* Dungy old bubble sort... */
5345 yaffs_BlockIndex temp;
5349 for (i = 0; i < nBlocksToScan; i++)
5350 for (j = i + 1; j < nBlocksToScan; j++)
5351 if (blockIndex[i].seq > blockIndex[j].seq) {
5352 temp = blockIndex[j];
5353 blockIndex[j] = blockIndex[i];
5354 blockIndex[i] = temp;
5361 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5363 /* Now scan the blocks looking at the data. */
5365 endIterator = nBlocksToScan - 1;
5366 T(YAFFS_TRACE_SCAN_DEBUG,
5367 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5369 /* For each block.... backwards */
5370 for (blockIterator = endIterator; blockIterator >= startIterator;
5372 /* Cooperative multitasking! This loop can run for so
5373 long that watchdog timers expire. */
5376 /* get the block to scan in the correct order */
5377 blk = blockIndex[blockIterator].block;
5379 bi = yaffs_GetBlockInfo(dev, blk);
5380 state = bi->blockState;
5384 /* For each chunk in each block that needs scanning.... */
5385 foundChunksInBlock = 0;
5386 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5387 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5388 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5389 /* Scan backwards...
5390 * Read the tags and decide what to do
5392 chunk = blk * dev->nChunksPerBlock + c;
5394 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5397 /* Let's have a good look at this chunk... */
5399 if (!tags.chunkUsed) {
5400 /* An unassigned chunk in the block.
5401 * If there are used chunks after this one, then
5402 * it is a chunk that was skipped due to failing the erased
5403 * check. Just skip it so that it can be deleted.
5404 * But, more typically, We get here when this is an unallocated
5405 * chunk and his means that either the block is empty or
5406 * this is the one being allocated from
5409 if(foundChunksInBlock)
5411 /* This is a chunk that was skipped due to failing the erased check */
5413 } else if (c == 0) {
5414 /* We're looking at the first chunk in the block so the block is unused */
5415 state = YAFFS_BLOCK_STATE_EMPTY;
5416 dev->nErasedBlocks++;
5418 /* this is the block being allocated from */
5420 YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5423 (" Allocating from %d %d"
5426 state = YAFFS_BLOCK_STATE_ALLOCATING;
5427 dev->allocationBlock = blk;
5428 dev->allocationPage = c;
5429 dev->allocationBlockFinder = blk;
5430 /* Set it to here to encourage the allocator to
5431 * go forth from here.
5434 /* Yaffs2 sanity check:
5435 * This should be the one with the highest sequence number
5438 && (dev->sequenceNumber !=
5439 bi->sequenceNumber)) {
5440 T(YAFFS_TRACE_ALWAYS,
5442 ("yaffs: Allocation block %d was not highest sequence "
5443 "id: block seq = %d, dev seq = %d"
5446 dev->sequenceNumber));
5451 } else if (tags.chunkId > 0) {
5452 /* chunkId > 0 so it is a data chunk... */
5453 unsigned int endpos;
5455 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
5457 foundChunksInBlock = 1;
5460 yaffs_SetChunkBit(dev, blk, c);
5463 in = yaffs_FindOrCreateObjectByNumber(dev,
5466 YAFFS_OBJECT_TYPE_FILE);
5467 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5469 in->variant.fileVariant.shrinkSize) {
5470 /* This has not been invalidated by a resize */
5471 yaffs_PutChunkIntoFile(in, tags.chunkId,
5474 /* File size is calculated by looking at the data chunks if we have not
5475 * seen an object header yet. Stop this practice once we find an object header.
5479 1) * dev->nDataBytesPerChunk +
5482 if (!in->valid && /* have not got an object header yet */
5483 in->variant.fileVariant.
5484 scannedFileSize < endpos) {
5485 in->variant.fileVariant.
5486 scannedFileSize = endpos;
5487 in->variant.fileVariant.
5489 in->variant.fileVariant.
5494 /* This chunk has been invalidated by a resize, so delete */
5495 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5499 /* chunkId == 0, so it is an ObjectHeader.
5500 * Thus, we read in the object header and make the object
5502 foundChunksInBlock = 1;
5504 yaffs_SetChunkBit(dev, blk, c);
5510 if (tags.extraHeaderInfoAvailable) {
5511 in = yaffs_FindOrCreateObjectByNumber
5512 (dev, tags.objectId,
5513 tags.extraObjectType);
5517 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5520 tags.extraShadows ||
5522 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5523 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5526 /* If we don't have valid info then we need to read the chunk
5527 * TODO In future we can probably defer reading the chunk and
5528 * living with invalid data until needed.
5531 result = yaffs_ReadChunkWithTagsFromNAND(dev,
5536 oh = (yaffs_ObjectHeader *) chunkData;
5539 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5544 /* TODO Hoosterman we have a problem! */
5545 T(YAFFS_TRACE_ERROR,
5547 ("yaffs tragedy: Could not make object for object %d "
5548 "at chunk %d during scan"
5549 TENDSTR), tags.objectId, chunk));
5554 /* We have already filled this one.
5555 * We have a duplicate that will be discarded, but
5556 * we first have to suck out resize info if it is a file.
5559 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
5561 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5562 (tags.extraHeaderInfoAvailable &&
5563 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5566 (oh) ? oh->fileSize : tags.
5568 __u32 parentObjectId =
5570 parentObjectId : tags.
5571 extraParentObjectId;
5573 (oh) ? oh->isShrink : tags.
5574 extraIsShrinkHeader;
5576 /* If it is deleted (unlinked at start also means deleted)
5577 * we treat the file size as being zeroed at this point.
5579 if (parentObjectId ==
5580 YAFFS_OBJECTID_DELETED
5581 || parentObjectId ==
5582 YAFFS_OBJECTID_UNLINKED) {
5588 in->variant.fileVariant.
5589 shrinkSize > thisSize) {
5590 in->variant.fileVariant.
5596 bi->hasShrinkHeader = 1;
5600 /* Use existing - destroy this one. */
5601 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5606 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5608 YAFFS_OBJECTID_LOSTNFOUND)) {
5609 /* We only load some info, don't fiddle with directory structure */
5613 in->variantType = oh->type;
5615 in->yst_mode = oh->yst_mode;
5616 #ifdef CONFIG_YAFFS_WINCE
5617 in->win_atime[0] = oh->win_atime[0];
5618 in->win_ctime[0] = oh->win_ctime[0];
5619 in->win_mtime[0] = oh->win_mtime[0];
5620 in->win_atime[1] = oh->win_atime[1];
5621 in->win_ctime[1] = oh->win_ctime[1];
5622 in->win_mtime[1] = oh->win_mtime[1];
5624 in->yst_uid = oh->yst_uid;
5625 in->yst_gid = oh->yst_gid;
5626 in->yst_atime = oh->yst_atime;
5627 in->yst_mtime = oh->yst_mtime;
5628 in->yst_ctime = oh->yst_ctime;
5629 in->yst_rdev = oh->yst_rdev;
5633 in->variantType = tags.extraObjectType;
5637 in->chunkId = chunk;
5639 } else if (!in->valid) {
5640 /* we need to load this info */
5643 in->chunkId = chunk;
5646 in->variantType = oh->type;
5648 in->yst_mode = oh->yst_mode;
5649 #ifdef CONFIG_YAFFS_WINCE
5650 in->win_atime[0] = oh->win_atime[0];
5651 in->win_ctime[0] = oh->win_ctime[0];
5652 in->win_mtime[0] = oh->win_mtime[0];
5653 in->win_atime[1] = oh->win_atime[1];
5654 in->win_ctime[1] = oh->win_ctime[1];
5655 in->win_mtime[1] = oh->win_mtime[1];
5657 in->yst_uid = oh->yst_uid;
5658 in->yst_gid = oh->yst_gid;
5659 in->yst_atime = oh->yst_atime;
5660 in->yst_mtime = oh->yst_mtime;
5661 in->yst_ctime = oh->yst_ctime;
5662 in->yst_rdev = oh->yst_rdev;
5665 if (oh->shadowsObject > 0)
5666 yaffs_HandleShadowedObject(dev,
5672 yaffs_SetObjectName(in, oh->name);
5674 yaffs_FindOrCreateObjectByNumber
5675 (dev, oh->parentObjectId,
5676 YAFFS_OBJECT_TYPE_DIRECTORY);
5678 fileSize = oh->fileSize;
5679 isShrink = oh->isShrink;
5680 equivalentObjectId = oh->equivalentObjectId;
5684 in->variantType = tags.extraObjectType;
5686 yaffs_FindOrCreateObjectByNumber
5687 (dev, tags.extraParentObjectId,
5688 YAFFS_OBJECT_TYPE_DIRECTORY);
5689 fileSize = tags.extraFileLength;
5690 isShrink = tags.extraIsShrinkHeader;
5691 equivalentObjectId = tags.extraEquivalentObjectId;
5697 /* directory stuff...
5701 if (parent->variantType ==
5702 YAFFS_OBJECT_TYPE_UNKNOWN) {
5703 /* Set up as a directory */
5704 parent->variantType =
5705 YAFFS_OBJECT_TYPE_DIRECTORY;
5706 INIT_LIST_HEAD(&parent->variant.
5709 } else if (parent->variantType !=
5710 YAFFS_OBJECT_TYPE_DIRECTORY)
5712 /* Hoosterman, another problem....
5713 * We're trying to use a non-directory as a directory
5716 T(YAFFS_TRACE_ERROR,
5718 ("yaffs tragedy: attempting to use non-directory as"
5719 " a directory in scan. Put in lost+found."
5721 parent = dev->lostNFoundDir;
5724 yaffs_AddObjectToDirectory(parent, in);
5726 itsUnlinked = (parent == dev->deletedDir) ||
5727 (parent == dev->unlinkedDir);
5730 /* Mark the block as having a shrinkHeader */
5731 bi->hasShrinkHeader = 1;
5734 /* Note re hardlinks.
5735 * Since we might scan a hardlink before its equivalent object is scanned
5736 * we put them all in a list.
5737 * After scanning is complete, we should have all the objects, so we run
5738 * through this list and fix up all the chains.
5741 switch (in->variantType) {
5742 case YAFFS_OBJECT_TYPE_UNKNOWN:
5743 /* Todo got a problem */
5745 case YAFFS_OBJECT_TYPE_FILE:
5747 if (in->variant.fileVariant.
5748 scannedFileSize < fileSize) {
5749 /* This covers the case where the file size is greater
5750 * than where the data is
5751 * This will happen if the file is resized to be larger
5752 * than its current data extents.
5754 in->variant.fileVariant.fileSize = fileSize;
5755 in->variant.fileVariant.scannedFileSize =
5756 in->variant.fileVariant.fileSize;
5760 in->variant.fileVariant.shrinkSize > fileSize) {
5761 in->variant.fileVariant.shrinkSize = fileSize;
5765 case YAFFS_OBJECT_TYPE_HARDLINK:
5767 in->variant.hardLinkVariant.equivalentObjectId =
5769 in->hardLinks.next =
5770 (struct list_head *) hardList;
5774 case YAFFS_OBJECT_TYPE_DIRECTORY:
5777 case YAFFS_OBJECT_TYPE_SPECIAL:
5780 case YAFFS_OBJECT_TYPE_SYMLINK:
5782 in->variant.symLinkVariant.alias =
5783 yaffs_CloneString(oh->
5792 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5793 /* If we got this far while scanning, then the block is fully allocated. */
5794 state = YAFFS_BLOCK_STATE_FULL;
5797 bi->blockState = state;
5799 /* Now let's see if it was dirty */
5800 if (bi->pagesInUse == 0 &&
5801 !bi->hasShrinkHeader &&
5802 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5803 yaffs_BlockBecameDirty(dev, blk);
5809 YFREE_ALT(blockIndex);
5813 /* Ok, we've done all the scanning.
5814 * Fix up the hard link chains.
5815 * We should now have scanned all the objects, now it's time to add these
5818 yaffs_HardlinkFixup(dev,hardList);
5822 * Sort out state of unlinked and deleted objects.
5825 struct list_head *i;
5826 struct list_head *n;
5830 /* Soft delete all the unlinked files */
5831 list_for_each_safe(i, n,
5832 &dev->unlinkedDir->variant.directoryVariant.
5835 l = list_entry(i, yaffs_Object, siblings);
5836 yaffs_DestroyObject(l);
5840 /* Soft delete all the deletedDir files */
5841 list_for_each_safe(i, n,
5842 &dev->deletedDir->variant.directoryVariant.
5845 l = list_entry(i, yaffs_Object, siblings);
5846 yaffs_DestroyObject(l);
5852 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5854 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5859 /*------------------------------ Directory Functions ----------------------------- */
5861 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5863 yaffs_Device *dev = obj->myDev;
5865 if(dev && dev->removeObjectCallback)
5866 dev->removeObjectCallback(obj);
5868 list_del_init(&obj->siblings);
5873 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5878 T(YAFFS_TRACE_ALWAYS,
5880 ("tragedy: Trying to add an object to a null pointer directory"
5884 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5885 T(YAFFS_TRACE_ALWAYS,
5887 ("tragedy: Trying to add an object to a non-directory"
5892 if (obj->siblings.prev == NULL) {
5893 /* Not initialised */
5894 INIT_LIST_HEAD(&obj->siblings);
5896 } else if (!list_empty(&obj->siblings)) {
5897 /* If it is holed up somewhere else, un hook it */
5898 yaffs_RemoveObjectFromDirectory(obj);
5901 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5902 obj->parent = directory;
5904 if (directory == obj->myDev->unlinkedDir
5905 || directory == obj->myDev->deletedDir) {
5907 obj->myDev->nUnlinkedFiles++;
5908 obj->renameAllowed = 0;
5912 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5917 struct list_head *i;
5918 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5927 T(YAFFS_TRACE_ALWAYS,
5929 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5933 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5934 T(YAFFS_TRACE_ALWAYS,
5936 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5940 sum = yaffs_CalcNameSum(name);
5942 list_for_each(i, &directory->variant.directoryVariant.children) {
5944 l = list_entry(i, yaffs_Object, siblings);
5946 yaffs_CheckObjectDetailsLoaded(l);
5948 /* Special case for lost-n-found */
5949 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5950 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5953 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
5955 /* LostnFound cunk called Objxxx
5958 yaffs_GetObjectName(l, buffer,
5959 YAFFS_MAX_NAME_LENGTH);
5960 if (yaffs_strcmp(name, buffer) == 0) {
5973 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5974 int (*fn) (yaffs_Object *))
5976 struct list_head *i;
5980 T(YAFFS_TRACE_ALWAYS,
5982 ("tragedy: yaffs_FindObjectByName: null pointer directory"
5986 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5987 T(YAFFS_TRACE_ALWAYS,
5989 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5993 list_for_each(i, &theDir->variant.directoryVariant.children) {
5995 l = list_entry(i, yaffs_Object, siblings);
6007 /* GetEquivalentObject dereferences any hard links to get to the
6011 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6013 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6014 /* We want the object id of the equivalent object, not this one */
6015 obj = obj->variant.hardLinkVariant.equivalentObject;
6021 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6023 memset(name, 0, buffSize * sizeof(YCHAR));
6025 yaffs_CheckObjectDetailsLoaded(obj);
6027 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6028 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6029 } else if (obj->chunkId <= 0) {
6031 /* make up a name */
6032 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6034 yaffs_strncpy(name, locName, buffSize - 1);
6037 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6038 else if (obj->shortName[0]) {
6039 yaffs_strcpy(name, obj->shortName);
6044 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6046 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6048 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6050 if (obj->chunkId >= 0) {
6051 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6052 obj->chunkId, buffer,
6055 yaffs_strncpy(name, oh->name, buffSize - 1);
6057 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6060 return yaffs_strlen(name);
6063 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6066 /* Dereference any hard linking */
6067 obj = yaffs_GetEquivalentObject(obj);
6069 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6070 return obj->variant.fileVariant.fileSize;
6072 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6073 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6075 /* Only a directory should drop through to here */
6076 return obj->myDev->nDataBytesPerChunk;
6080 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6083 struct list_head *i;
6085 if (!obj->unlinked) {
6086 count++; /* the object itself */
6088 list_for_each(i, &obj->hardLinks) {
6089 count++; /* add the hard links; */
6095 int yaffs_GetObjectInode(yaffs_Object * obj)
6097 obj = yaffs_GetEquivalentObject(obj);
6099 return obj->objectId;
6102 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6104 obj = yaffs_GetEquivalentObject(obj);
6106 switch (obj->variantType) {
6107 case YAFFS_OBJECT_TYPE_FILE:
6110 case YAFFS_OBJECT_TYPE_DIRECTORY:
6113 case YAFFS_OBJECT_TYPE_SYMLINK:
6116 case YAFFS_OBJECT_TYPE_HARDLINK:
6119 case YAFFS_OBJECT_TYPE_SPECIAL:
6120 if (S_ISFIFO(obj->yst_mode))
6122 if (S_ISCHR(obj->yst_mode))
6124 if (S_ISBLK(obj->yst_mode))
6126 if (S_ISSOCK(obj->yst_mode))
6134 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6136 obj = yaffs_GetEquivalentObject(obj);
6137 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6138 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6140 return yaffs_CloneString(_Y(""));
6144 #ifndef CONFIG_YAFFS_WINCE
6146 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6148 unsigned int valid = attr->ia_valid;
6150 if (valid & ATTR_MODE)
6151 obj->yst_mode = attr->ia_mode;
6152 if (valid & ATTR_UID)
6153 obj->yst_uid = attr->ia_uid;
6154 if (valid & ATTR_GID)
6155 obj->yst_gid = attr->ia_gid;
6157 if (valid & ATTR_ATIME)
6158 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6159 if (valid & ATTR_CTIME)
6160 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6161 if (valid & ATTR_MTIME)
6162 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6164 if (valid & ATTR_SIZE)
6165 yaffs_ResizeFile(obj, attr->ia_size);
6167 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6172 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6174 unsigned int valid = 0;
6176 attr->ia_mode = obj->yst_mode;
6178 attr->ia_uid = obj->yst_uid;
6180 attr->ia_gid = obj->yst_gid;
6183 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6184 valid |= ATTR_ATIME;
6185 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6186 valid |= ATTR_CTIME;
6187 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6188 valid |= ATTR_MTIME;
6190 attr->ia_size = yaffs_GetFileSize(obj);
6193 attr->ia_valid = valid;
6202 int yaffs_DumpObject(yaffs_Object * obj)
6206 yaffs_GetObjectName(obj, name, 256);
6208 T(YAFFS_TRACE_ALWAYS,
6210 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6211 " chunk %d type %d size %d\n"
6212 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6213 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6214 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6220 /*---------------------------- Initialisation code -------------------------------------- */
6222 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6225 /* Common functions, gotta have */
6226 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6229 #ifdef CONFIG_YAFFS_YAFFS2
6231 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6232 if (dev->writeChunkWithTagsToNAND &&
6233 dev->readChunkWithTagsFromNAND &&
6234 !dev->writeChunkToNAND &&
6235 !dev->readChunkFromNAND &&
6236 dev->markNANDBlockBad && dev->queryNANDBlock)
6240 /* Can use the "spare" style interface for yaffs1 */
6241 if (!dev->isYaffs2 &&
6242 !dev->writeChunkWithTagsToNAND &&
6243 !dev->readChunkWithTagsFromNAND &&
6244 dev->writeChunkToNAND &&
6245 dev->readChunkFromNAND &&
6246 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6253 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6255 /* Initialise the unlinked, deleted, root and lost and found directories */
6257 dev->lostNFoundDir = dev->rootDir = NULL;
6258 dev->unlinkedDir = dev->deletedDir = NULL;
6261 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6263 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6266 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6267 YAFFS_ROOT_MODE | S_IFDIR);
6268 dev->lostNFoundDir =
6269 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6270 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6271 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6274 int yaffs_GutsInitialise(yaffs_Device * dev)
6279 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6281 /* Check stuff that must be set */
6284 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6288 dev->internalStartBlock = dev->startBlock;
6289 dev->internalEndBlock = dev->endBlock;
6290 dev->blockOffset = 0;
6291 dev->chunkOffset = 0;
6292 dev->nFreeChunks = 0;
6294 if (dev->startBlock == 0) {
6295 dev->internalStartBlock = dev->startBlock + 1;
6296 dev->internalEndBlock = dev->endBlock + 1;
6297 dev->blockOffset = 1;
6298 dev->chunkOffset = dev->nChunksPerBlock;
6301 /* Check geometry parameters. */
6303 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
6304 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
6305 dev->nChunksPerBlock < 2 ||
6306 dev->nReservedBlocks < 2 ||
6307 dev->internalStartBlock <= 0 ||
6308 dev->internalEndBlock <= 0 ||
6309 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6311 T(YAFFS_TRACE_ALWAYS,
6313 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6314 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6318 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6319 T(YAFFS_TRACE_ALWAYS,
6320 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6324 /* Got the right mix of functions? */
6325 if (!yaffs_CheckDevFunctions(dev)) {
6326 /* Function missing */
6327 T(YAFFS_TRACE_ALWAYS,
6329 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6334 /* This is really a compilation check. */
6335 if (!yaffs_CheckStructures()) {
6336 T(YAFFS_TRACE_ALWAYS,
6337 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6341 if (dev->isMounted) {
6342 T(YAFFS_TRACE_ALWAYS,
6343 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6347 /* Finished with most checks. One or two more checks happen later on too. */
6353 /* OK now calculate a few things for the device */
6356 * Calculate all the chunk size manipulation numbers:
6358 /* Start off assuming it is a power of 2 */
6359 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
6360 dev->chunkMask = (1<<dev->chunkShift) - 1;
6362 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
6363 /* Yes it is a power of 2, disable crumbs */
6365 dev->crumbShift = 0;
6366 dev->crumbsPerChunk = 0;
6368 /* Not a power of 2, use crumbs instead */
6369 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
6370 dev->crumbMask = (1<<dev->crumbShift)-1;
6371 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
6372 dev->chunkShift = 0;
6378 * Calculate chunkGroupBits.
6379 * We need to find the next power of 2 > than internalEndBlock
6382 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6386 /* Set up tnode width if wide tnodes are enabled. */
6387 if(!dev->wideTnodesDisabled){
6388 /* bits must be even so that we end up with 32-bit words */
6392 dev->tnodeWidth = 16;
6394 dev->tnodeWidth = bits;
6397 dev->tnodeWidth = 16;
6399 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6401 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6402 * so if the bitwidth of the
6403 * chunk range we're using is greater than 16 we need
6404 * to figure out chunk shift and chunkGroupSize
6407 if (bits <= dev->tnodeWidth)
6408 dev->chunkGroupBits = 0;
6410 dev->chunkGroupBits = bits - dev->tnodeWidth;
6413 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6415 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6416 /* We have a problem because the soft delete won't work if
6417 * the chunk group size > chunks per block.
6418 * This can be remedied by using larger "virtual blocks".
6420 T(YAFFS_TRACE_ALWAYS,
6421 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6426 /* OK, we've finished verifying the device, lets continue with initialisation */
6428 /* More device initialisation */
6429 dev->garbageCollections = 0;
6430 dev->passiveGarbageCollections = 0;
6431 dev->currentDirtyChecker = 0;
6432 dev->bufferedBlock = -1;
6433 dev->doingBufferedBlockRewrite = 0;
6434 dev->nDeletedFiles = 0;
6435 dev->nBackgroundDeletions = 0;
6436 dev->nUnlinkedFiles = 0;
6438 dev->eccUnfixed = 0;
6439 dev->tagsEccFixed = 0;
6440 dev->tagsEccUnfixed = 0;
6441 dev->nErasureFailures = 0;
6442 dev->nErasedBlocks = 0;
6444 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
6446 /* Initialise temporary buffers and caches. */
6449 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6450 dev->tempBuffer[i].line = 0; /* not in use */
6451 dev->tempBuffer[i].buffer =
6452 YMALLOC_DMA(dev->nDataBytesPerChunk);
6456 if (dev->nShortOpCaches > 0) {
6459 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6460 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6464 YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6466 for (i = 0; i < dev->nShortOpCaches; i++) {
6467 dev->srCache[i].object = NULL;
6468 dev->srCache[i].lastUse = 0;
6469 dev->srCache[i].dirty = 0;
6470 dev->srCache[i].data = YMALLOC_DMA(dev->nDataBytesPerChunk);
6477 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6479 if (dev->isYaffs2) {
6480 dev->useHeaderFileSize = 1;
6483 yaffs_InitialiseBlocks(dev);
6484 yaffs_InitialiseTnodes(dev);
6485 yaffs_InitialiseObjects(dev);
6487 yaffs_CreateInitialDirectories(dev);
6490 /* Now scan the flash. */
6491 if (dev->isYaffs2) {
6492 if(yaffs_CheckpointRestore(dev)) {
6493 T(YAFFS_TRACE_ALWAYS,
6494 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6497 /* Clean up the mess caused by an aborted checkpoint load
6498 * and scan backwards.
6500 yaffs_DeinitialiseBlocks(dev);
6501 yaffs_DeinitialiseTnodes(dev);
6502 yaffs_DeinitialiseObjects(dev);
6503 yaffs_InitialiseBlocks(dev);
6504 yaffs_InitialiseTnodes(dev);
6505 yaffs_InitialiseObjects(dev);
6506 yaffs_CreateInitialDirectories(dev);
6508 yaffs_ScanBackwards(dev);
6513 /* Zero out stats */
6514 dev->nPageReads = 0;
6515 dev->nPageWrites = 0;
6516 dev->nBlockErasures = 0;
6518 dev->nRetriedWrites = 0;
6520 dev->nRetiredBlocks = 0;
6522 yaffs_VerifyFreeChunks(dev);
6524 T(YAFFS_TRACE_TRACING,
6525 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6530 void yaffs_Deinitialise(yaffs_Device * dev)
6532 if (dev->isMounted) {
6535 yaffs_DeinitialiseBlocks(dev);
6536 yaffs_DeinitialiseTnodes(dev);
6537 yaffs_DeinitialiseObjects(dev);
6538 if (dev->nShortOpCaches > 0) {
6540 for (i = 0; i < dev->nShortOpCaches; i++) {
6541 YFREE(dev->srCache[i].data);
6544 YFREE(dev->srCache);
6547 YFREE(dev->gcCleanupList);
6549 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6550 YFREE(dev->tempBuffer[i].buffer);
6558 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6563 yaffs_BlockInfo *blk;
6565 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6567 blk = yaffs_GetBlockInfo(dev, b);
6569 switch (blk->blockState) {
6570 case YAFFS_BLOCK_STATE_EMPTY:
6571 case YAFFS_BLOCK_STATE_ALLOCATING:
6572 case YAFFS_BLOCK_STATE_COLLECTING:
6573 case YAFFS_BLOCK_STATE_FULL:
6575 (dev->nChunksPerBlock - blk->pagesInUse +
6576 blk->softDeletions);
6587 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6589 /* This is what we report to the outside world */
6592 int nDirtyCacheChunks;
6593 int blocksForCheckpoint;
6596 nFree = dev->nFreeChunks;
6598 nFree = yaffs_CountFreeChunks(dev);
6601 nFree += dev->nDeletedFiles;
6603 /* Now count the number of dirty chunks in the cache and subtract those */
6607 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6608 if (dev->srCache[i].dirty)
6609 nDirtyCacheChunks++;
6613 nFree -= nDirtyCacheChunks;
6615 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6617 /* Now we figure out how much to reserve for the checkpoint and report that... */
6618 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6619 if(blocksForCheckpoint < 0)
6620 blocksForCheckpoint = 0;
6622 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6631 static int yaffs_freeVerificationFailures;
6633 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6635 int counted = yaffs_CountFreeChunks(dev);
6637 int difference = dev->nFreeChunks - counted;
6640 T(YAFFS_TRACE_ALWAYS,
6641 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6642 dev->nFreeChunks, counted, difference));
6643 yaffs_freeVerificationFailures++;
6647 /*---------------------------------------- YAFFS test code ----------------------*/
6649 #define yaffs_CheckStruct(structure,syze, name) \
6650 if(sizeof(structure) != syze) \
6652 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6653 name,syze,sizeof(structure))); \
6654 return YAFFS_FAIL; \
6657 static int yaffs_CheckStructures(void)
6659 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6660 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6661 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6662 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6663 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6665 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")