2 * YAFFS: Yet another FFS. A NAND-flash specific file system.
4 * Copyright (C) 2002 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
15 const char *yaffs_guts_c_version =
16 "$Id: yaffs_guts.c,v 1.44 2006-11-11 23:27:44 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #ifdef CONFIG_YAFFS_WINCE
37 void yfsd_LockYAFFS(BOOL fsLockOnly);
38 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
41 #define YAFFS_PASSIVE_GC_CHUNKS 2
43 #include "yaffs_ecc.h"
46 /* Robustification (if it ever comes about...) */
47 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
48 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
49 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
51 const yaffs_ExtendedTags * tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
53 const yaffs_ExtendedTags * tags);
55 /* Other local prototypes */
56 static int yaffs_UnlinkObject( yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
61 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
63 yaffs_ExtendedTags * tags,
65 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
66 int chunkInNAND, int inScan);
68 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
69 yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
72 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
73 int force, int isShrink, int shadows);
74 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
75 static int yaffs_CheckStructures(void);
76 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
77 int chunkOffset, int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
82 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
83 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
86 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
89 static int yaffs_UnlinkWorker(yaffs_Object * obj);
90 static void yaffs_DestroyObject(yaffs_Object * obj);
92 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
95 loff_t yaffs_GetFileSize(yaffs_Object * obj);
97 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
99 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
101 #ifdef YAFFS_PARANOID
102 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #define yaffs_CheckFileSanity(in)
107 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
108 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
114 /* Function to calculate chunk and offset */
116 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
119 /* Easy-peasy power of 2 case */
120 *chunk = (__u32)(addr >> dev->chunkShift);
121 *offset = (__u32)(addr & dev->chunkMask);
123 else if(dev->crumbsPerChunk)
125 /* Case where we're using "crumbs" */
126 *offset = (__u32)(addr & dev->crumbMask);
127 addr >>= dev->crumbShift;
128 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
129 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
135 /* Function to return the number of shifts for a power of 2 greater than or equal
136 * to the given number
137 * Note we don't try to cater for all possible numbers and this does not have to
138 * be hellishly efficient.
141 static __u32 ShiftsGE(__u32 x)
146 nShifts = extraBits = 0;
149 if(x & 1) extraBits++;
160 /* Function to return the number of shifts to get a 1 in bit 0
163 static __u32 ShiftDiv(__u32 x)
182 * Temporary buffer manipulations.
185 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
188 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
189 if (dev->tempBuffer[i].line == 0) {
190 dev->tempBuffer[i].line = lineNo;
191 if ((i + 1) > dev->maxTemp) {
192 dev->maxTemp = i + 1;
193 for (j = 0; j <= i; j++)
194 dev->tempBuffer[j].maxLine =
195 dev->tempBuffer[j].line;
198 return dev->tempBuffer[i].buffer;
202 T(YAFFS_TRACE_BUFFERS,
203 (TSTR("Out of temp buffers at line %d, other held by lines:"),
205 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
206 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
208 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
211 * If we got here then we have to allocate an unmanaged one
215 dev->unmanagedTempAllocations++;
216 return YMALLOC(dev->nDataBytesPerChunk);
220 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
224 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
225 if (dev->tempBuffer[i].buffer == buffer) {
226 dev->tempBuffer[i].line = 0;
232 /* assume it is an unmanaged one. */
233 T(YAFFS_TRACE_BUFFERS,
234 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
237 dev->unmanagedTempDeallocations++;
243 * Determine if we have a managed buffer.
245 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
248 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
249 if (dev->tempBuffer[i].buffer == buffer)
254 for (i = 0; i < dev->nShortOpCaches; i++) {
255 if( dev->srCache[i].data == buffer )
260 if (buffer == dev->checkpointBuffer)
263 T(YAFFS_TRACE_ALWAYS,
264 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
269 * Chunk bitmap manipulations
272 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
274 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
276 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
280 return dev->chunkBits +
281 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
284 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
286 __u8 *blkBits = yaffs_BlockBits(dev, blk);
288 memset(blkBits, 0, dev->chunkBitmapStride);
291 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
293 __u8 *blkBits = yaffs_BlockBits(dev, blk);
295 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
298 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
300 __u8 *blkBits = yaffs_BlockBits(dev, blk);
302 blkBits[chunk / 8] |= (1 << (chunk & 7));
305 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
307 __u8 *blkBits = yaffs_BlockBits(dev, blk);
308 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
311 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
313 __u8 *blkBits = yaffs_BlockBits(dev, blk);
315 for (i = 0; i < dev->chunkBitmapStride; i++) {
324 * Simple hash function. Needs to have a reasonable spread
327 static Y_INLINE int yaffs_HashFunction(int n)
330 return (n % YAFFS_NOBJECT_BUCKETS);
334 * Access functions to useful fake objects
337 yaffs_Object *yaffs_Root(yaffs_Device * dev)
342 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
344 return dev->lostNFoundDir;
349 * Erased NAND checking functions
352 int yaffs_CheckFF(__u8 * buffer, int nBytes)
354 /* Horrible, slow implementation */
363 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
367 int retval = YAFFS_OK;
368 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
369 yaffs_ExtendedTags tags;
372 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
374 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
378 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
379 T(YAFFS_TRACE_NANDACCESS,
380 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
384 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
390 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
392 yaffs_ExtendedTags * tags,
402 yaffs_InvalidateCheckpoint(dev);
405 chunk = yaffs_AllocateChunk(dev, useReserve,&bi);
408 /* First check this chunk is erased, if it needs checking.
409 * The checking policy (unless forced always on) is as follows:
410 * Check the first page we try to write in a block.
411 * - If the check passes then we don't need to check any more.
412 * - If the check fails, we check again...
413 * If the block has been erased, we don't need to check.
415 * However, if the block has been prioritised for gc, then
416 * we think there might be something odd about this block
420 * We should only ever see chunks that have not been erased
421 * if there was a partially written chunk due to power loss
422 * This checking policy should catch that case with very
423 * few checks and thus save a lot of checks that are most likely not
427 if(bi->gcPrioritise){
428 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
430 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
432 bi->skipErasedCheck = 0;
435 if(!bi->skipErasedCheck){
436 erasedOk = yaffs_CheckChunkErased(dev, chunk);
437 if(erasedOk && !bi->gcPrioritise)
438 bi->skipErasedCheck = 1;
444 ("**>> yaffs chunk %d was not erased"
448 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
456 * Copy the data into the robustification buffer.
457 * NB We do this at the end to prevent duplicates in the case of a write error.
460 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
463 /* The erased check or write failed */
464 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
469 } while (chunk >= 0 && !writeOk);
473 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
475 dev->nRetriedWrites += (attempts - 1);
482 * Block retiring for handling a broken block.
485 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
487 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
489 yaffs_InvalidateCheckpoint(dev);
491 yaffs_MarkBlockBad(dev, blockInNAND);
493 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
494 bi->gcPrioritise = 0;
495 bi->needsRetiring = 0;
497 dev->nRetiredBlocks++;
501 * Functions for robustisizing TODO
505 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
507 const yaffs_ExtendedTags * tags)
511 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
512 const yaffs_ExtendedTags * tags)
516 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
518 if(!bi->gcPrioritise){
519 bi->gcPrioritise = 1;
520 dev->hasPendingPrioritisedGCs = 1;
521 bi->chunkErrorStrikes ++;
523 if(bi->chunkErrorStrikes > 3){
524 bi->needsRetiring = 1; /* Too many stikes, so retire this */
525 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
532 static void yaffs_ReportOddballBlocks(yaffs_Device *dev)
536 for(i = dev->internalStartBlock; i <= dev->internalEndBlock && (yaffs_traceMask & YAFFS_TRACE_BAD_BLOCKS); i++){
537 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
538 if(bi->needsRetiring || bi->gcPrioritise)
539 T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("yaffs block %d%s%s" TENDSTR),
541 bi->needsRetiring ? " needs retiring" : "",
542 bi->gcPrioritise ? " gc prioritised" : ""));
547 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
550 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
551 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
553 yaffs_HandleChunkError(dev,bi);
557 /* Was an actual write failure, so mark the block for retirement */
558 bi->needsRetiring = 1;
559 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
560 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
565 /* Delete the chunk */
566 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
570 /*---------------- Name handling functions ------------*/
572 static __u16 yaffs_CalcNameSum(const YCHAR * name)
577 YUCHAR *bname = (YUCHAR *) name;
579 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
581 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
582 sum += yaffs_toupper(*bname) * i;
593 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
595 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
596 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
597 yaffs_strcpy(obj->shortName, name);
599 obj->shortName[0] = _Y('\0');
602 obj->sum = yaffs_CalcNameSum(name);
605 /*-------------------- TNODES -------------------
607 * List of spare tnodes
608 * The list is hooked together using the first pointer
612 /* yaffs_CreateTnodes creates a bunch more tnodes and
613 * adds them to the tnode free list.
614 * Don't use this function directly
617 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
621 yaffs_Tnode *newTnodes;
625 yaffs_TnodeList *tnl;
630 /* Calculate the tnode size in bytes for variable width tnode support.
631 * Must be a multiple of 32-bits */
632 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
634 /* make these things */
636 newTnodes = YMALLOC(nTnodes * tnodeSize);
637 mem = (__u8 *)newTnodes;
641 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
645 /* Hook them into the free list */
647 for (i = 0; i < nTnodes - 1; i++) {
648 newTnodes[i].internal[0] = &newTnodes[i + 1];
649 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
650 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
654 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
655 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
656 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
658 dev->freeTnodes = newTnodes;
660 /* New hookup for wide tnodes */
661 for(i = 0; i < nTnodes -1; i++) {
662 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
663 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
664 curr->internal[0] = next;
667 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
668 curr->internal[0] = dev->freeTnodes;
669 dev->freeTnodes = (yaffs_Tnode *)mem;
674 dev->nFreeTnodes += nTnodes;
675 dev->nTnodesCreated += nTnodes;
677 /* Now add this bunch of tnodes to a list for freeing up.
678 * NB If we can't add this to the management list it isn't fatal
679 * but it just means we can't free this bunch of tnodes later.
682 tnl = YMALLOC(sizeof(yaffs_TnodeList));
686 ("yaffs: Could not add tnodes to management list" TENDSTR)));
689 tnl->tnodes = newTnodes;
690 tnl->next = dev->allocatedTnodeList;
691 dev->allocatedTnodeList = tnl;
694 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
699 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
701 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
703 yaffs_Tnode *tn = NULL;
705 /* If there are none left make more */
706 if (!dev->freeTnodes) {
707 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
710 if (dev->freeTnodes) {
711 tn = dev->freeTnodes;
712 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
713 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
714 /* Hoosterman, this thing looks like it isn't in the list */
715 T(YAFFS_TRACE_ALWAYS,
716 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
719 dev->freeTnodes = dev->freeTnodes->internal[0];
726 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
728 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
731 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
736 /* FreeTnode frees up a tnode and puts it back on the free list */
737 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
740 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
741 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
742 /* Hoosterman, this thing looks like it is already in the list */
743 T(YAFFS_TRACE_ALWAYS,
744 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
746 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
748 tn->internal[0] = dev->freeTnodes;
749 dev->freeTnodes = tn;
754 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
756 /* Free the list of allocated tnodes */
757 yaffs_TnodeList *tmp;
759 while (dev->allocatedTnodeList) {
760 tmp = dev->allocatedTnodeList->next;
762 YFREE(dev->allocatedTnodeList->tnodes);
763 YFREE(dev->allocatedTnodeList);
764 dev->allocatedTnodeList = tmp;
768 dev->freeTnodes = NULL;
769 dev->nFreeTnodes = 0;
772 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
774 dev->allocatedTnodeList = NULL;
775 dev->freeTnodes = NULL;
776 dev->nFreeTnodes = 0;
777 dev->nTnodesCreated = 0;
782 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
784 __u32 *map = (__u32 *)tn;
790 pos &= YAFFS_TNODES_LEVEL0_MASK;
791 val >>= dev->chunkGroupBits;
793 bitInMap = pos * dev->tnodeWidth;
794 wordInMap = bitInMap /32;
795 bitInWord = bitInMap & (32 -1);
797 mask = dev->tnodeMask << bitInWord;
799 map[wordInMap] &= ~mask;
800 map[wordInMap] |= (mask & (val << bitInWord));
802 if(dev->tnodeWidth > (32-bitInWord)) {
803 bitInWord = (32 - bitInWord);
805 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
806 map[wordInMap] &= ~mask;
807 map[wordInMap] |= (mask & (val >> bitInWord));
811 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
813 __u32 *map = (__u32 *)tn;
819 pos &= YAFFS_TNODES_LEVEL0_MASK;
821 bitInMap = pos * dev->tnodeWidth;
822 wordInMap = bitInMap /32;
823 bitInWord = bitInMap & (32 -1);
825 val = map[wordInMap] >> bitInWord;
827 if(dev->tnodeWidth > (32-bitInWord)) {
828 bitInWord = (32 - bitInWord);
830 val |= (map[wordInMap] << bitInWord);
833 val &= dev->tnodeMask;
834 val <<= dev->chunkGroupBits;
839 /* ------------------- End of individual tnode manipulation -----------------*/
841 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
842 * The look up tree is represented by the top tnode and the number of topLevel
843 * in the tree. 0 means only the level 0 tnode is in the tree.
846 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
847 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
848 yaffs_FileStructure * fStruct,
852 yaffs_Tnode *tn = fStruct->top;
854 int requiredTallness;
855 int level = fStruct->topLevel;
857 /* Check sane level and chunk Id */
858 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
862 if (chunkId > YAFFS_MAX_CHUNK_ID) {
866 /* First check we're tall enough (ie enough topLevel) */
868 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
869 requiredTallness = 0;
871 i >>= YAFFS_TNODES_INTERNAL_BITS;
875 if (requiredTallness > fStruct->topLevel) {
876 /* Not tall enough, so we can't find it, return NULL. */
880 /* Traverse down to level 0 */
881 while (level > 0 && tn) {
884 ( YAFFS_TNODES_LEVEL0_BITS +
886 YAFFS_TNODES_INTERNAL_BITS)
888 YAFFS_TNODES_INTERNAL_MASK];
896 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
897 * This happens in two steps:
898 * 1. If the tree isn't tall enough, then make it taller.
899 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
901 * Used when modifying the tree.
903 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
904 * be plugged into the ttree.
907 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
908 yaffs_FileStructure * fStruct,
910 yaffs_Tnode *passedTn)
913 int requiredTallness;
921 /* Check sane level and page Id */
922 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
926 if (chunkId > YAFFS_MAX_CHUNK_ID) {
930 /* First check we're tall enough (ie enough topLevel) */
932 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
933 requiredTallness = 0;
935 x >>= YAFFS_TNODES_INTERNAL_BITS;
940 if (requiredTallness > fStruct->topLevel) {
941 /* Not tall enough,gotta make the tree taller */
942 for (i = fStruct->topLevel; i < requiredTallness; i++) {
944 tn = yaffs_GetTnode(dev);
947 tn->internal[0] = fStruct->top;
951 (TSTR("yaffs: no more tnodes" TENDSTR)));
955 fStruct->topLevel = requiredTallness;
958 /* Traverse down to level 0, adding anything we need */
960 l = fStruct->topLevel;
964 while (l > 0 && tn) {
966 ( YAFFS_TNODES_LEVEL0_BITS +
967 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
968 YAFFS_TNODES_INTERNAL_MASK;
971 if((l>1) && !tn->internal[x]){
972 /* Add missing non-level-zero tnode */
973 tn->internal[x] = yaffs_GetTnode(dev);
976 /* Looking from level 1 at level 0 */
978 /* If we already have one, then release it.*/
980 yaffs_FreeTnode(dev,tn->internal[x]);
981 tn->internal[x] = passedTn;
983 } else if(!tn->internal[x]) {
984 /* Don't have one, none passed in */
985 tn->internal[x] = yaffs_GetTnode(dev);
989 tn = tn->internal[x];
995 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
996 yaffs_FreeTnode(dev,passedTn);
1003 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1004 yaffs_ExtendedTags * tags, int objectId,
1009 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1010 if (yaffs_CheckChunkBit
1011 (dev, theChunk / dev->nChunksPerBlock,
1012 theChunk % dev->nChunksPerBlock)) {
1013 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1015 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1027 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1028 * chunks and tnodes in the file
1029 * Returns 1 if the tree was deleted.
1030 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1033 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1034 int chunkOffset, int *limit)
1039 yaffs_ExtendedTags tags;
1041 yaffs_Device *dev = in->myDev;
1048 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1050 if (tn->internal[i]) {
1051 if (limit && (*limit) < 0) {
1055 yaffs_DeleteWorker(in,
1063 YAFFS_TNODES_INTERNAL_BITS)
1068 yaffs_FreeTnode(dev,
1071 tn->internal[i] = NULL;
1076 return (allDone) ? 1 : 0;
1077 } else if (level == 0) {
1080 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1082 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1087 YAFFS_TNODES_LEVEL0_BITS) + i;
1090 yaffs_FindChunkInGroup(dev,
1096 if (foundChunk > 0) {
1097 yaffs_DeleteChunk(dev,
1102 *limit = *limit - 1;
1110 yaffs_PutLevel0Tnode(dev,tn,i,0);
1114 return (i < 0) ? 1 : 0;
1124 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1127 yaffs_BlockInfo *theBlock;
1129 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1131 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1133 theBlock->softDeletions++;
1138 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1139 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1141 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1144 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1145 __u32 level, int chunkOffset)
1150 yaffs_Device *dev = in->myDev;
1155 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1157 if (tn->internal[i]) {
1159 yaffs_SoftDeleteWorker(in,
1165 YAFFS_TNODES_INTERNAL_BITS)
1168 yaffs_FreeTnode(dev,
1171 tn->internal[i] = NULL;
1173 /* Hoosterman... how could this happen? */
1177 return (allDone) ? 1 : 0;
1178 } else if (level == 0) {
1180 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1181 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1183 /* Note this does not find the real chunk, only the chunk group.
1184 * We make an assumption that a chunk group is not larger than
1187 yaffs_SoftDeleteChunk(dev, theChunk);
1188 yaffs_PutLevel0Tnode(dev,tn,i,0);
1202 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1205 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1206 if (obj->nDataChunks <= 0) {
1207 /* Empty file with no duplicate object headers, just delete it immediately */
1208 yaffs_FreeTnode(obj->myDev,
1209 obj->variant.fileVariant.top);
1210 obj->variant.fileVariant.top = NULL;
1211 T(YAFFS_TRACE_TRACING,
1212 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1214 yaffs_DoGenericObjectDeletion(obj);
1216 yaffs_SoftDeleteWorker(obj,
1217 obj->variant.fileVariant.top,
1218 obj->variant.fileVariant.
1220 obj->softDeleted = 1;
1225 /* Pruning removes any part of the file structure tree that is beyond the
1226 * bounds of the file (ie that does not point to chunks).
1228 * A file should only get pruned when its size is reduced.
1230 * Before pruning, the chunks must be pulled from the tree and the
1231 * level 0 tnode entries must be zeroed out.
1232 * Could also use this for file deletion, but that's probably better handled
1233 * by a special case.
1236 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1237 __u32 level, int del0)
1245 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1246 if (tn->internal[i] && level > 0) {
1248 yaffs_PruneWorker(dev, tn->internal[i],
1250 (i == 0) ? del0 : 1);
1253 if (tn->internal[i]) {
1258 if (hasData == 0 && del0) {
1259 /* Free and return NULL */
1261 yaffs_FreeTnode(dev, tn);
1271 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1272 yaffs_FileStructure * fStruct)
1279 if (fStruct->topLevel > 0) {
1281 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1283 /* Now we have a tree with all the non-zero branches NULL but the height
1284 * is the same as it was.
1285 * Let's see if we can trim internal tnodes to shorten the tree.
1286 * We can do this if only the 0th element in the tnode is in use
1287 * (ie all the non-zero are NULL)
1290 while (fStruct->topLevel && !done) {
1294 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1295 if (tn->internal[i]) {
1301 fStruct->top = tn->internal[0];
1302 fStruct->topLevel--;
1303 yaffs_FreeTnode(dev, tn);
1313 /*-------------------- End of File Structure functions.-------------------*/
1315 /* yaffs_CreateFreeObjects creates a bunch more objects and
1316 * adds them to the object free list.
1318 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1321 yaffs_Object *newObjects;
1322 yaffs_ObjectList *list;
1327 /* make these things */
1328 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1331 T(YAFFS_TRACE_ALLOCATE,
1332 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1336 /* Hook them into the free list */
1337 for (i = 0; i < nObjects - 1; i++) {
1338 newObjects[i].siblings.next =
1339 (struct list_head *)(&newObjects[i + 1]);
1342 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1343 dev->freeObjects = newObjects;
1344 dev->nFreeObjects += nObjects;
1345 dev->nObjectsCreated += nObjects;
1347 /* Now add this bunch of Objects to a list for freeing up. */
1349 list = YMALLOC(sizeof(yaffs_ObjectList));
1351 T(YAFFS_TRACE_ALLOCATE,
1352 (TSTR("Could not add objects to management list" TENDSTR)));
1354 list->objects = newObjects;
1355 list->next = dev->allocatedObjectList;
1356 dev->allocatedObjectList = list;
1363 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1364 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1366 yaffs_Object *tn = NULL;
1368 /* If there are none left make more */
1369 if (!dev->freeObjects) {
1370 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1373 if (dev->freeObjects) {
1374 tn = dev->freeObjects;
1376 (yaffs_Object *) (dev->freeObjects->siblings.next);
1377 dev->nFreeObjects--;
1379 /* Now sweeten it up... */
1381 memset(tn, 0, sizeof(yaffs_Object));
1384 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1385 INIT_LIST_HEAD(&(tn->hardLinks));
1386 INIT_LIST_HEAD(&(tn->hashLink));
1387 INIT_LIST_HEAD(&tn->siblings);
1389 /* Add it to the lost and found directory.
1390 * NB Can't put root or lostNFound in lostNFound so
1391 * check if lostNFound exists first
1393 if (dev->lostNFoundDir) {
1394 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1401 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1406 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1408 obj->fake = 1; /* it is fake so it has no NAND presence... */
1409 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1410 obj->unlinkAllowed = 0; /* ... or unlink it */
1413 obj->yst_mode = mode;
1415 obj->chunkId = 0; /* Not a valid chunk. */
1422 static void yaffs_UnhashObject(yaffs_Object * tn)
1425 yaffs_Device *dev = tn->myDev;
1427 /* If it is still linked into the bucket list, free from the list */
1428 if (!list_empty(&tn->hashLink)) {
1429 list_del_init(&tn->hashLink);
1430 bucket = yaffs_HashFunction(tn->objectId);
1431 dev->objectBucket[bucket].count--;
1436 /* FreeObject frees up a Object and puts it back on the free list */
1437 static void yaffs_FreeObject(yaffs_Object * tn)
1440 yaffs_Device *dev = tn->myDev;
1444 /* We're still hooked up to a cached inode.
1445 * Don't delete now, but mark for later deletion
1447 tn->deferedFree = 1;
1452 yaffs_UnhashObject(tn);
1454 /* Link into the free list. */
1455 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1456 dev->freeObjects = tn;
1457 dev->nFreeObjects++;
1462 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1464 if (obj->deferedFree) {
1465 yaffs_FreeObject(obj);
1471 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1473 /* Free the list of allocated Objects */
1475 yaffs_ObjectList *tmp;
1477 while (dev->allocatedObjectList) {
1478 tmp = dev->allocatedObjectList->next;
1479 YFREE(dev->allocatedObjectList->objects);
1480 YFREE(dev->allocatedObjectList);
1482 dev->allocatedObjectList = tmp;
1485 dev->freeObjects = NULL;
1486 dev->nFreeObjects = 0;
1489 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1493 dev->allocatedObjectList = NULL;
1494 dev->freeObjects = NULL;
1495 dev->nFreeObjects = 0;
1497 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1498 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1499 dev->objectBucket[i].count = 0;
1504 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1509 int lowest = 999999;
1511 /* First let's see if we can find one that's empty. */
1513 for (i = 0; i < 10 && lowest > 0; i++) {
1515 x %= YAFFS_NOBJECT_BUCKETS;
1516 if (dev->objectBucket[x].count < lowest) {
1517 lowest = dev->objectBucket[x].count;
1523 /* If we didn't find an empty list, then try
1524 * looking a bit further for a short one
1527 for (i = 0; i < 10 && lowest > 3; i++) {
1529 x %= YAFFS_NOBJECT_BUCKETS;
1530 if (dev->objectBucket[x].count < lowest) {
1531 lowest = dev->objectBucket[x].count;
1540 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1542 int bucket = yaffs_FindNiceObjectBucket(dev);
1544 /* Now find an object value that has not already been taken
1545 * by scanning the list.
1549 struct list_head *i;
1551 __u32 n = (__u32) bucket;
1553 /* yaffs_CheckObjectHashSanity(); */
1557 n += YAFFS_NOBJECT_BUCKETS;
1558 if (1 || dev->objectBucket[bucket].count > 0) {
1559 list_for_each(i, &dev->objectBucket[bucket].list) {
1560 /* If there is already one in the list */
1562 && list_entry(i, yaffs_Object,
1563 hashLink)->objectId == n) {
1574 static void yaffs_HashObject(yaffs_Object * in)
1576 int bucket = yaffs_HashFunction(in->objectId);
1577 yaffs_Device *dev = in->myDev;
1579 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1580 dev->objectBucket[bucket].count++;
1584 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1586 int bucket = yaffs_HashFunction(number);
1587 struct list_head *i;
1590 list_for_each(i, &dev->objectBucket[bucket].list) {
1591 /* Look if it is in the list */
1593 in = list_entry(i, yaffs_Object, hashLink);
1594 if (in->objectId == number) {
1596 /* Don't tell the VFS about this one if it is defered free */
1597 if (in->deferedFree)
1609 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1610 yaffs_ObjectType type)
1613 yaffs_Object *theObject;
1616 number = yaffs_CreateNewObjectNumber(dev);
1619 theObject = yaffs_AllocateEmptyObject(dev);
1622 theObject->fake = 0;
1623 theObject->renameAllowed = 1;
1624 theObject->unlinkAllowed = 1;
1625 theObject->objectId = number;
1626 yaffs_HashObject(theObject);
1627 theObject->variantType = type;
1628 #ifdef CONFIG_YAFFS_WINCE
1629 yfsd_WinFileTimeNow(theObject->win_atime);
1630 theObject->win_ctime[0] = theObject->win_mtime[0] =
1631 theObject->win_atime[0];
1632 theObject->win_ctime[1] = theObject->win_mtime[1] =
1633 theObject->win_atime[1];
1637 theObject->yst_atime = theObject->yst_mtime =
1638 theObject->yst_ctime = Y_CURRENT_TIME;
1641 case YAFFS_OBJECT_TYPE_FILE:
1642 theObject->variant.fileVariant.fileSize = 0;
1643 theObject->variant.fileVariant.scannedFileSize = 0;
1644 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1645 theObject->variant.fileVariant.topLevel = 0;
1646 theObject->variant.fileVariant.top =
1647 yaffs_GetTnode(dev);
1649 case YAFFS_OBJECT_TYPE_DIRECTORY:
1650 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1653 case YAFFS_OBJECT_TYPE_SYMLINK:
1654 case YAFFS_OBJECT_TYPE_HARDLINK:
1655 case YAFFS_OBJECT_TYPE_SPECIAL:
1656 /* No action required */
1658 case YAFFS_OBJECT_TYPE_UNKNOWN:
1659 /* todo this should not happen */
1667 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1669 yaffs_ObjectType type)
1671 yaffs_Object *theObject = NULL;
1674 theObject = yaffs_FindObjectByNumber(dev, number);
1678 theObject = yaffs_CreateNewObject(dev, number, type);
1686 static YCHAR *yaffs_CloneString(const YCHAR * str)
1688 YCHAR *newStr = NULL;
1691 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1692 yaffs_strcpy(newStr, str);
1700 * Mknod (create) a new object.
1701 * equivalentObject only has meaning for a hard link;
1702 * aliasString only has meaning for a sumlink.
1703 * rdev only has meaning for devices (a subset of special objects)
1706 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1707 yaffs_Object * parent,
1712 yaffs_Object * equivalentObject,
1713 const YCHAR * aliasString, __u32 rdev)
1717 yaffs_Device *dev = parent->myDev;
1719 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1720 if (yaffs_FindObjectByName(parent, name)) {
1724 in = yaffs_CreateNewObject(dev, -1, type);
1729 in->variantType = type;
1731 in->yst_mode = mode;
1733 #ifdef CONFIG_YAFFS_WINCE
1734 yfsd_WinFileTimeNow(in->win_atime);
1735 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1736 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1739 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1741 in->yst_rdev = rdev;
1745 in->nDataChunks = 0;
1747 yaffs_SetObjectName(in, name);
1750 yaffs_AddObjectToDirectory(parent, in);
1752 in->myDev = parent->myDev;
1755 case YAFFS_OBJECT_TYPE_SYMLINK:
1756 in->variant.symLinkVariant.alias =
1757 yaffs_CloneString(aliasString);
1759 case YAFFS_OBJECT_TYPE_HARDLINK:
1760 in->variant.hardLinkVariant.equivalentObject =
1762 in->variant.hardLinkVariant.equivalentObjectId =
1763 equivalentObject->objectId;
1764 list_add(&in->hardLinks, &equivalentObject->hardLinks);
1766 case YAFFS_OBJECT_TYPE_FILE:
1767 case YAFFS_OBJECT_TYPE_DIRECTORY:
1768 case YAFFS_OBJECT_TYPE_SPECIAL:
1769 case YAFFS_OBJECT_TYPE_UNKNOWN:
1774 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1775 /* Could not create the object header, fail the creation */
1776 yaffs_DestroyObject(in);
1785 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1786 __u32 mode, __u32 uid, __u32 gid)
1788 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1789 uid, gid, NULL, NULL, 0);
1792 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1793 __u32 mode, __u32 uid, __u32 gid)
1795 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1796 mode, uid, gid, NULL, NULL, 0);
1799 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1800 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1802 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1803 uid, gid, NULL, NULL, rdev);
1806 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1807 __u32 mode, __u32 uid, __u32 gid,
1808 const YCHAR * alias)
1810 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1811 uid, gid, NULL, alias, 0);
1814 /* yaffs_Link returns the object id of the equivalent object.*/
1815 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1816 yaffs_Object * equivalentObject)
1818 /* Get the real object in case we were fed a hard link as an equivalent object */
1819 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1821 if (yaffs_MknodObject
1822 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1823 equivalentObject, NULL, 0)) {
1824 return equivalentObject;
1831 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1832 const YCHAR * newName, int force, int shadows)
1837 yaffs_Object *existingTarget;
1839 if (newDir == NULL) {
1840 newDir = obj->parent; /* use the old directory */
1843 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1844 T(YAFFS_TRACE_ALWAYS,
1846 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1851 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1852 if (obj->myDev->isYaffs2) {
1853 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1855 unlinkOp = (newDir == obj->myDev->unlinkedDir
1856 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1859 deleteOp = (newDir == obj->myDev->deletedDir);
1861 existingTarget = yaffs_FindObjectByName(newDir, newName);
1863 /* If the object is a file going into the unlinked directory,
1864 * then it is OK to just stuff it in since duplicate names are allowed.
1865 * else only proceed if the new name does not exist and if we're putting
1866 * it into a directory.
1873 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1874 yaffs_SetObjectName(obj, newName);
1877 yaffs_AddObjectToDirectory(newDir, obj);
1882 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1883 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1890 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1891 yaffs_Object * newDir, const YCHAR * newName)
1894 yaffs_Object *existingTarget;
1897 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1898 /* Special case for case insemsitive systems (eg. WinCE).
1899 * While look-up is case insensitive, the name isn't.
1900 * Therefore we might want to change x.txt to X.txt
1902 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1907 obj = yaffs_FindObjectByName(oldDir, oldName);
1908 /* Check new name to long. */
1909 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1910 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1913 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1914 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1918 if (obj && obj->renameAllowed) {
1920 /* Now do the handling for an existing target, if there is one */
1922 existingTarget = yaffs_FindObjectByName(newDir, newName);
1923 if (existingTarget &&
1924 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1925 !list_empty(&existingTarget->variant.directoryVariant.children)) {
1926 /* There is a target that is a non-empty directory, so we fail */
1927 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1928 } else if (existingTarget && existingTarget != obj) {
1929 /* Nuke the target first, using shadowing,
1930 * but only if it isn't the same object
1932 yaffs_ChangeObjectName(obj, newDir, newName, force,
1933 existingTarget->objectId);
1934 yaffs_UnlinkObject(existingTarget);
1937 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1942 /*------------------------- Block Management and Page Allocation ----------------*/
1944 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1946 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1948 dev->allocationBlock = -1; /* force it to get a new one */
1950 /* Todo we're assuming the malloc will pass. */
1951 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1952 if(!dev->blockInfo){
1953 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1954 dev->blockInfoAlt = 1;
1957 dev->blockInfoAlt = 0;
1959 /* Set up dynamic blockinfo stuff. */
1960 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
1961 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1962 if(!dev->chunkBits){
1963 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1964 dev->chunkBitsAlt = 1;
1967 dev->chunkBitsAlt = 0;
1969 if (dev->blockInfo && dev->chunkBits) {
1970 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1971 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1979 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1981 if(dev->blockInfoAlt)
1982 YFREE_ALT(dev->blockInfo);
1984 YFREE(dev->blockInfo);
1985 dev->blockInfoAlt = 0;
1987 dev->blockInfo = NULL;
1989 if(dev->chunkBitsAlt)
1990 YFREE_ALT(dev->chunkBits);
1992 YFREE(dev->chunkBits);
1993 dev->chunkBitsAlt = 0;
1994 dev->chunkBits = NULL;
1997 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1998 yaffs_BlockInfo * bi)
2005 return 1; /* disqualification only applies to yaffs2. */
2007 if (!bi->hasShrinkHeader)
2008 return 1; /* can gc */
2010 /* Find the oldest dirty sequence number if we don't know it and save it
2011 * so we don't have to keep recomputing it.
2013 if (!dev->oldestDirtySequence) {
2014 seq = dev->sequenceNumber;
2016 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2018 b = yaffs_GetBlockInfo(dev, i);
2019 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2020 (b->pagesInUse - b->softDeletions) <
2021 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2022 seq = b->sequenceNumber;
2025 dev->oldestDirtySequence = seq;
2028 /* Can't do gc of this block if there are any blocks older than this one that have
2031 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2035 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2036 * for garbage collection.
2039 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2043 int b = dev->currentDirtyChecker;
2050 yaffs_BlockInfo *bi;
2051 static int nonAggressiveSkip = 0;
2052 int pendingPrioritisedExist = 0;
2054 /* First let's see if we need to grab a prioritised block */
2055 if(dev->hasPendingPrioritisedGCs){
2056 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2058 bi = yaffs_GetBlockInfo(dev, i);
2059 if(bi->gcPrioritise) {
2060 pendingPrioritisedExist = 1;
2061 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2062 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2063 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2066 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2071 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2072 dev->hasPendingPrioritisedGCs = 0;
2075 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2077 * else (we're doing a leasurely gc), then we only bother to do this if the
2078 * block has only a few pages in use.
2081 nonAggressiveSkip--;
2083 if (!aggressive && (nonAggressiveSkip > 0)) {
2089 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2093 dev->internalEndBlock - dev->internalStartBlock + 1;
2096 dev->internalEndBlock - dev->internalStartBlock + 1;
2097 iterations = iterations / 16;
2098 if (iterations > 200) {
2103 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2105 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2106 b = dev->internalStartBlock;
2109 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2110 T(YAFFS_TRACE_ERROR,
2111 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2115 bi = yaffs_GetBlockInfo(dev, b);
2118 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2125 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2126 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2127 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2129 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2133 dev->currentDirtyChecker = b;
2137 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2138 dev->nChunksPerBlock - pagesInUse,prioritised));
2141 dev->oldestDirtySequence = 0;
2144 nonAggressiveSkip = 4;
2150 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2152 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2156 /* If the block is still healthy erase it and mark as clean.
2157 * If the block has had a data failure, then retire it.
2160 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2161 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2162 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2164 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2166 if (!bi->needsRetiring) {
2167 yaffs_InvalidateCheckpoint(dev);
2168 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2170 dev->nErasureFailures++;
2171 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2172 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2176 if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2178 for (i = 0; i < dev->nChunksPerBlock; i++) {
2179 if (!yaffs_CheckChunkErased
2180 (dev, blockNo * dev->nChunksPerBlock + i)) {
2181 T(YAFFS_TRACE_ERROR,
2183 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2184 TENDSTR), blockNo, i));
2190 /* Clean it up... */
2191 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2192 dev->nErasedBlocks++;
2194 bi->softDeletions = 0;
2195 bi->hasShrinkHeader = 0;
2196 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2197 bi->gcPrioritise = 0;
2198 yaffs_ClearChunkBits(dev, blockNo);
2200 T(YAFFS_TRACE_ERASE,
2201 (TSTR("Erased block %d" TENDSTR), blockNo));
2203 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2205 yaffs_RetireBlock(dev, blockNo);
2206 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2207 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2211 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2215 yaffs_BlockInfo *bi;
2217 if (dev->nErasedBlocks < 1) {
2218 /* Hoosterman we've got a problem.
2219 * Can't get space to gc
2221 T(YAFFS_TRACE_ERROR,
2222 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2227 /* Find an empty block. */
2229 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2230 dev->allocationBlockFinder++;
2231 if (dev->allocationBlockFinder < dev->internalStartBlock
2232 || dev->allocationBlockFinder > dev->internalEndBlock) {
2233 dev->allocationBlockFinder = dev->internalStartBlock;
2236 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2238 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2239 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2240 dev->sequenceNumber++;
2241 bi->sequenceNumber = dev->sequenceNumber;
2242 dev->nErasedBlocks--;
2243 T(YAFFS_TRACE_ALLOCATE,
2244 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2245 dev->allocationBlockFinder, dev->sequenceNumber,
2246 dev->nErasedBlocks));
2247 return dev->allocationBlockFinder;
2251 T(YAFFS_TRACE_ALWAYS,
2253 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2254 TENDSTR), dev->nErasedBlocks));
2260 // Check if there's space to allocate...
2261 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2262 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2265 int reservedBlocks = dev->nReservedBlocks;
2266 int checkpointBlocks;
2268 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2269 if(checkpointBlocks < 0)
2270 checkpointBlocks = 0;
2272 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2274 return (dev->nFreeChunks > reservedChunks);
2277 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2280 yaffs_BlockInfo *bi;
2282 if (dev->allocationBlock < 0) {
2283 /* Get next block to allocate off */
2284 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2285 dev->allocationPage = 0;
2288 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2289 /* Not enough space to allocate unless we're allowed to use the reserve. */
2293 if (dev->nErasedBlocks < dev->nReservedBlocks
2294 && dev->allocationPage == 0) {
2295 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2298 /* Next page please.... */
2299 if (dev->allocationBlock >= 0) {
2300 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2302 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2303 dev->allocationPage;
2305 yaffs_SetChunkBit(dev, dev->allocationBlock,
2306 dev->allocationPage);
2308 dev->allocationPage++;
2312 /* If the block is full set the state to full */
2313 if (dev->allocationPage >= dev->nChunksPerBlock) {
2314 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2315 dev->allocationBlock = -1;
2324 T(YAFFS_TRACE_ERROR,
2325 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2330 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2334 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2336 if (dev->allocationBlock > 0) {
2337 n += (dev->nChunksPerBlock - dev->allocationPage);
2344 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2350 int retVal = YAFFS_OK;
2353 int isCheckpointBlock;
2355 int chunksBefore = yaffs_GetErasedChunks(dev);
2358 yaffs_ExtendedTags tags;
2360 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2362 yaffs_Object *object;
2364 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2366 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2368 T(YAFFS_TRACE_TRACING,
2369 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2370 bi->pagesInUse, bi->hasShrinkHeader));
2372 /*yaffs_VerifyFreeChunks(dev); */
2374 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2376 /* Take off the number of soft deleted entries because
2377 * they're going to get really deleted during GC.
2379 dev->nFreeChunks -= bi->softDeletions;
2383 if (isCheckpointBlock ||
2384 !yaffs_StillSomeChunkBits(dev, block)) {
2385 T(YAFFS_TRACE_TRACING,
2387 ("Collecting block %d that has no chunks in use" TENDSTR),
2389 yaffs_BlockBecameDirty(dev, block);
2392 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2394 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2395 chunkInBlock < dev->nChunksPerBlock
2396 && yaffs_StillSomeChunkBits(dev, block);
2397 chunkInBlock++, oldChunk++) {
2398 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2400 /* This page is in use and might need to be copied off */
2404 yaffs_InitialiseTags(&tags);
2406 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2410 yaffs_FindObjectByNumber(dev,
2413 T(YAFFS_TRACE_GC_DETAIL,
2415 ("Collecting page %d, %d %d %d " TENDSTR),
2416 chunkInBlock, tags.objectId, tags.chunkId,
2420 T(YAFFS_TRACE_ERROR,
2422 ("page %d in gc has no object "
2423 TENDSTR), oldChunk));
2426 if (object && object->deleted
2427 && tags.chunkId != 0) {
2428 /* Data chunk in a deleted file, throw it away
2429 * It's a soft deleted data chunk,
2430 * No need to copy this, just forget about it and
2431 * fix up the object.
2434 object->nDataChunks--;
2436 if (object->nDataChunks <= 0) {
2437 /* remeber to clean up the object */
2438 dev->gcCleanupList[cleanups] =
2444 /* Todo object && object->deleted && object->nDataChunks == 0 */
2446 /* Deleted object header with no data chunks.
2447 * Can be discarded and the file deleted.
2449 object->chunkId = 0;
2450 yaffs_FreeTnode(object->myDev,
2453 object->variant.fileVariant.top = NULL;
2454 yaffs_DoGenericObjectDeletion(object);
2456 } else if (object) {
2457 /* It's either a data chunk in a live file or
2458 * an ObjectHeader, so we're interested in it.
2459 * NB Need to keep the ObjectHeaders of deleted files
2460 * until the whole file has been deleted off
2462 tags.serialNumber++;
2466 if (tags.chunkId == 0) {
2467 /* It is an object Id,
2468 * We need to nuke the shrinkheader flags first
2469 * We no longer want the shrinkHeader flag since its work is done
2470 * and if it is left in place it will mess up scanning.
2471 * Also, clear out any shadowing stuff
2474 yaffs_ObjectHeader *oh;
2475 oh = (yaffs_ObjectHeader *)buffer;
2477 oh->shadowsObject = -1;
2478 tags.extraShadows = 0;
2479 tags.extraIsShrinkHeader = 0;
2483 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2486 retVal = YAFFS_FAIL;
2489 /* Ok, now fix up the Tnodes etc. */
2491 if (tags.chunkId == 0) {
2493 object->chunkId = newChunk;
2494 object->serial = tags.serialNumber;
2496 /* It's a data chunk */
2497 yaffs_PutChunkIntoFile
2505 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2510 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2513 /* Do any required cleanups */
2514 for (i = 0; i < cleanups; i++) {
2515 /* Time to delete the file too */
2517 yaffs_FindObjectByNumber(dev,
2518 dev->gcCleanupList[i]);
2520 yaffs_FreeTnode(dev,
2521 object->variant.fileVariant.
2523 object->variant.fileVariant.top = NULL;
2526 ("yaffs: About to finally delete object %d"
2527 TENDSTR), object->objectId));
2528 yaffs_DoGenericObjectDeletion(object);
2529 object->myDev->nDeletedFiles--;
2536 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2539 ("gc did not increase free chunks before %d after %d"
2540 TENDSTR), chunksBefore, chunksAfter));
2548 /* New garbage collector
2549 * If we're very low on erased blocks then we do aggressive garbage collection
2550 * otherwise we do "leasurely" garbage collection.
2551 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2552 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2554 * The idea is to help clear out space in a more spread-out manner.
2555 * Dunno if it really does anything useful.
2557 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2561 int gcOk = YAFFS_OK;
2564 int checkpointBlockAdjust;
2566 if (dev->isDoingGC) {
2567 /* Bail out so we don't get recursive gc */
2571 /* This loop should pass the first time.
2572 * We'll only see looping here if the erase of the collected block fails.
2578 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2579 if(checkpointBlockAdjust < 0)
2580 checkpointBlockAdjust = 0;
2582 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2583 /* We need a block soon...*/
2586 /* We're in no hurry */
2590 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2593 dev->garbageCollections++;
2595 dev->passiveGarbageCollections++;
2600 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2601 dev->nErasedBlocks, aggressive));
2603 gcOk = yaffs_GarbageCollectBlock(dev, block);
2606 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2609 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2610 TENDSTR), dev->nErasedBlocks, maxTries, block));
2612 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2615 return aggressive ? gcOk : YAFFS_OK;
2618 /*------------------------- TAGS --------------------------------*/
2620 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2623 return (tags->chunkId == chunkInObject &&
2624 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2629 /*-------------------- Data file manipulation -----------------*/
2631 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2632 yaffs_ExtendedTags * tags)
2634 /*Get the Tnode, then get the level 0 offset chunk offset */
2637 yaffs_ExtendedTags localTags;
2640 yaffs_Device *dev = in->myDev;
2643 /* Passed a NULL, so use our own tags space */
2647 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2650 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2653 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2659 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2660 yaffs_ExtendedTags * tags)
2662 /* Get the Tnode, then get the level 0 offset chunk offset */
2665 yaffs_ExtendedTags localTags;
2667 yaffs_Device *dev = in->myDev;
2671 /* Passed a NULL, so use our own tags space */
2675 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2679 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2682 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2685 /* Delete the entry in the filestructure (if found) */
2687 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2690 /*T(("No level 0 found for %d\n", chunkInInode)); */
2694 /* T(("Could not find %d to delete\n",chunkInInode)); */
2699 #ifdef YAFFS_PARANOID
2701 static int yaffs_CheckFileSanity(yaffs_Object * in)
2709 yaffs_Tags localTags;
2710 yaffs_Tags *tags = &localTags;
2714 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2715 /* T(("Object not a file\n")); */
2719 objId = in->objectId;
2720 fSize = in->variant.fileVariant.fileSize;
2722 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
2724 for (chunk = 1; chunk <= nChunks; chunk++) {
2725 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2730 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2732 if (yaffs_CheckChunkBits
2733 (dev, theChunk / dev->nChunksPerBlock,
2734 theChunk % dev->nChunksPerBlock)) {
2736 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2740 (tags, in->objectId, chunk, chunkDeleted)) {
2750 /* T(("No level 0 found for %d\n", chunk)); */
2754 return failed ? YAFFS_FAIL : YAFFS_OK;
2759 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2760 int chunkInNAND, int inScan)
2762 /* NB inScan is zero unless scanning.
2763 * For forward scanning, inScan is > 0;
2764 * for backward scanning inScan is < 0
2768 yaffs_Device *dev = in->myDev;
2770 yaffs_ExtendedTags existingTags;
2771 yaffs_ExtendedTags newTags;
2772 unsigned existingSerial, newSerial;
2774 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2775 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2776 * If it is not during Scanning then something went wrong!
2779 T(YAFFS_TRACE_ERROR,
2781 ("yaffs tragedy:attempt to put data chunk into a non-file"
2786 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2790 tn = yaffs_AddOrFindLevel0Tnode(dev,
2791 &in->variant.fileVariant,
2798 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2801 /* If we're scanning then we need to test for duplicates
2802 * NB This does not need to be efficient since it should only ever
2803 * happen when the power fails during a write, then only one
2804 * chunk should ever be affected.
2806 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2807 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2810 if (existingChunk != 0) {
2811 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2812 * thus we have to do a FindChunkInFile to get the real chunk id.
2814 * We have a duplicate now we need to decide which one to use:
2816 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2817 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2818 * YAFFS1: Get both sets of tags and compare serial numbers.
2822 /* Only do this for forward scanning */
2823 yaffs_ReadChunkWithTagsFromNAND(dev,
2827 /* Do a proper find */
2829 yaffs_FindChunkInFile(in, chunkInInode,
2833 if (existingChunk <= 0) {
2834 /*Hoosterman - how did this happen? */
2836 T(YAFFS_TRACE_ERROR,
2838 ("yaffs tragedy: existing chunk < 0 in scan"
2843 /* NB The deleted flags should be false, otherwise the chunks will
2844 * not be loaded during a scan
2847 newSerial = newTags.serialNumber;
2848 existingSerial = existingTags.serialNumber;
2851 (in->myDev->isYaffs2 ||
2852 existingChunk <= 0 ||
2853 ((existingSerial + 1) & 3) == newSerial)) {
2854 /* Forward scanning.
2856 * Delete the old one and drop through to update the tnode
2858 yaffs_DeleteChunk(dev, existingChunk, 1,
2861 /* Backward scanning or we want to use the existing one
2863 * Delete the new one and return early so that the tnode isn't changed
2865 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2873 if (existingChunk == 0) {
2877 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2882 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2885 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2887 if (chunkInNAND >= 0) {
2888 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2891 T(YAFFS_TRACE_NANDACCESS,
2892 (TSTR("Chunk %d not found zero instead" TENDSTR),
2894 /* get sane (zero) data if you read a hole */
2895 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2901 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2905 yaffs_ExtendedTags tags;
2906 yaffs_BlockInfo *bi;
2912 block = chunkId / dev->nChunksPerBlock;
2913 page = chunkId % dev->nChunksPerBlock;
2915 bi = yaffs_GetBlockInfo(dev, block);
2917 T(YAFFS_TRACE_DELETION,
2918 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2921 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2923 yaffs_InitialiseTags(&tags);
2925 tags.chunkDeleted = 1;
2927 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2928 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2930 dev->nUnmarkedDeletions++;
2933 /* Pull out of the management area.
2934 * If the whole block became dirty, this will kick off an erasure.
2936 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2937 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2938 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2939 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2942 yaffs_ClearChunkBit(dev, block, page);
2946 if (bi->pagesInUse == 0 &&
2947 !bi->hasShrinkHeader &&
2948 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2949 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2950 yaffs_BlockBecameDirty(dev, block);
2954 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2959 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2960 const __u8 * buffer, int nBytes,
2963 /* Find old chunk Need to do this to get serial number
2964 * Write new one and patch into tree.
2965 * Invalidate old tags.
2969 yaffs_ExtendedTags prevTags;
2972 yaffs_ExtendedTags newTags;
2974 yaffs_Device *dev = in->myDev;
2976 yaffs_CheckGarbageCollection(dev);
2978 /* Get the previous chunk at this location in the file if it exists */
2979 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2981 /* Set up new tags */
2982 yaffs_InitialiseTags(&newTags);
2984 newTags.chunkId = chunkInInode;
2985 newTags.objectId = in->objectId;
2986 newTags.serialNumber =
2987 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2988 newTags.byteCount = nBytes;
2991 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2994 if (newChunkId >= 0) {
2995 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2997 if (prevChunkId >= 0) {
2998 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3002 yaffs_CheckFileSanity(in);
3008 /* UpdateObjectHeader updates the header on NAND for an object.
3009 * If name is not NULL, then that new name is used.
3011 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3012 int isShrink, int shadows)
3015 yaffs_BlockInfo *bi;
3017 yaffs_Device *dev = in->myDev;
3024 yaffs_ExtendedTags newTags;
3026 __u8 *buffer = NULL;
3027 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3029 yaffs_ObjectHeader *oh = NULL;
3031 if (!in->fake || force) {
3033 yaffs_CheckGarbageCollection(dev);
3035 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3036 oh = (yaffs_ObjectHeader *) buffer;
3038 prevChunkId = in->chunkId;
3040 if (prevChunkId >= 0) {
3041 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3043 memcpy(oldName, oh->name, sizeof(oh->name));
3046 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3048 oh->type = in->variantType;
3049 oh->yst_mode = in->yst_mode;
3050 oh->shadowsObject = shadows;
3052 #ifdef CONFIG_YAFFS_WINCE
3053 oh->win_atime[0] = in->win_atime[0];
3054 oh->win_ctime[0] = in->win_ctime[0];
3055 oh->win_mtime[0] = in->win_mtime[0];
3056 oh->win_atime[1] = in->win_atime[1];
3057 oh->win_ctime[1] = in->win_ctime[1];
3058 oh->win_mtime[1] = in->win_mtime[1];
3060 oh->yst_uid = in->yst_uid;
3061 oh->yst_gid = in->yst_gid;
3062 oh->yst_atime = in->yst_atime;
3063 oh->yst_mtime = in->yst_mtime;
3064 oh->yst_ctime = in->yst_ctime;
3065 oh->yst_rdev = in->yst_rdev;
3068 oh->parentObjectId = in->parent->objectId;
3070 oh->parentObjectId = 0;
3073 if (name && *name) {
3074 memset(oh->name, 0, sizeof(oh->name));
3075 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3076 } else if (prevChunkId) {
3077 memcpy(oh->name, oldName, sizeof(oh->name));
3079 memset(oh->name, 0, sizeof(oh->name));
3082 oh->isShrink = isShrink;
3084 switch (in->variantType) {
3085 case YAFFS_OBJECT_TYPE_UNKNOWN:
3086 /* Should not happen */
3088 case YAFFS_OBJECT_TYPE_FILE:
3090 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3091 || oh->parentObjectId ==
3092 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3093 fileVariant.fileSize;
3095 case YAFFS_OBJECT_TYPE_HARDLINK:
3096 oh->equivalentObjectId =
3097 in->variant.hardLinkVariant.equivalentObjectId;
3099 case YAFFS_OBJECT_TYPE_SPECIAL:
3102 case YAFFS_OBJECT_TYPE_DIRECTORY:
3105 case YAFFS_OBJECT_TYPE_SYMLINK:
3106 yaffs_strncpy(oh->alias,
3107 in->variant.symLinkVariant.alias,
3108 YAFFS_MAX_ALIAS_LENGTH);
3109 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3114 yaffs_InitialiseTags(&newTags);
3116 newTags.chunkId = 0;
3117 newTags.objectId = in->objectId;
3118 newTags.serialNumber = in->serial;
3120 /* Add extra info for file header */
3122 newTags.extraHeaderInfoAvailable = 1;
3123 newTags.extraParentObjectId = oh->parentObjectId;
3124 newTags.extraFileLength = oh->fileSize;
3125 newTags.extraIsShrinkHeader = oh->isShrink;
3126 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3127 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3128 newTags.extraObjectType = in->variantType;
3130 /* Create new chunk in NAND */
3132 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3133 (prevChunkId >= 0) ? 1 : 0);
3135 if (newChunkId >= 0) {
3137 in->chunkId = newChunkId;
3139 if (prevChunkId >= 0) {
3140 yaffs_DeleteChunk(dev, prevChunkId, 1,
3144 if(!yaffs_ObjectHasCachedWriteData(in))
3147 /* If this was a shrink, then mark the block that the chunk lives on */
3149 bi = yaffs_GetBlockInfo(in->myDev,
3150 newChunkId /in->myDev-> nChunksPerBlock);
3151 bi->hasShrinkHeader = 1;
3156 retVal = newChunkId;
3161 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3166 /*------------------------ Short Operations Cache ----------------------------------------
3167 * In many situations where there is no high level buffering (eg WinCE) a lot of
3168 * reads might be short sequential reads, and a lot of writes may be short
3169 * sequential writes. eg. scanning/writing a jpeg file.
3170 * In these cases, a short read/write cache can provide a huge perfomance benefit
3171 * with dumb-as-a-rock code.
3172 * In Linux, the page cache provides read buffering aand the short op cache provides write
3175 * There are a limited number (~10) of cache chunks per device so that we don't
3176 * need a very intelligent search.
3179 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3181 yaffs_Device *dev = obj->myDev;
3183 yaffs_ChunkCache *cache;
3184 int nCaches = obj->myDev->nShortOpCaches;
3186 for(i = 0; i < nCaches; i++){
3187 cache = &dev->srCache[i];
3188 if (cache->object == obj &&
3197 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3199 yaffs_Device *dev = obj->myDev;
3200 int lowest = -99; /* Stop compiler whining. */
3202 yaffs_ChunkCache *cache;
3203 int chunkWritten = 0;
3204 int nCaches = obj->myDev->nShortOpCaches;
3210 /* Find the dirty cache for this object with the lowest chunk id. */
3211 for (i = 0; i < nCaches; i++) {
3212 if (dev->srCache[i].object == obj &&
3213 dev->srCache[i].dirty) {
3215 || dev->srCache[i].chunkId <
3217 cache = &dev->srCache[i];
3218 lowest = cache->chunkId;
3223 if (cache && !cache->locked) {
3224 /* Write it out and free it up */
3227 yaffs_WriteChunkDataToObject(cache->object,
3233 cache->object = NULL;
3236 } while (cache && chunkWritten > 0);
3239 /* Hoosterman, disk full while writing cache out. */
3240 T(YAFFS_TRACE_ERROR,
3241 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3248 /*yaffs_FlushEntireDeviceCache(dev)
3253 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3256 int nCaches = dev->nShortOpCaches;
3259 /* Find a dirty object in the cache and flush it...
3260 * until there are no further dirty objects.
3264 for( i = 0; i < nCaches && !obj; i++) {
3265 if (dev->srCache[i].object &&
3266 dev->srCache[i].dirty)
3267 obj = dev->srCache[i].object;
3271 yaffs_FlushFilesChunkCache(obj);
3278 /* Grab us a cache chunk for use.
3279 * First look for an empty one.
3280 * Then look for the least recently used non-dirty one.
3281 * Then look for the least recently used dirty one...., flush and look again.
3283 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3289 if (dev->nShortOpCaches > 0) {
3290 for (i = 0; i < dev->nShortOpCaches; i++) {
3291 if (!dev->srCache[i].object)
3292 return &dev->srCache[i];
3298 usage = 0; /* just to stop the compiler grizzling */
3300 for (i = 0; i < dev->nShortOpCaches; i++) {
3301 if (!dev->srCache[i].dirty &&
3302 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3304 usage = dev->srCache[i].lastUse;
3310 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3317 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3319 yaffs_ChunkCache *cache;
3320 yaffs_Object *theObj;