2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2010 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
14 #include "yaffs_trace.h"
16 #include "yaffsinterface.h"
17 #include "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
21 #include "yaffs_tagscompat.h"
23 #include "yaffs_nand.h"
25 #include "yaffs_yaffs1.h"
26 #include "yaffs_yaffs2.h"
27 #include "yaffs_bitmap.h"
28 #include "yaffs_verify.h"
30 #include "yaffs_nand.h"
31 #include "yaffs_packedtags2.h"
33 #include "yaffs_nameval.h"
34 #include "yaffs_allocator.h"
36 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
37 #define YAFFS_GC_GOOD_ENOUGH 2
38 #define YAFFS_GC_PASSIVE_THRESHOLD 4
40 #include "yaffs_ecc.h"
44 /* Robustification (if it ever comes about...) */
45 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
46 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
48 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
50 const yaffs_ExtendedTags *tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
52 const yaffs_ExtendedTags *tags);
54 /* Other local prototypes */
55 static void yaffs_UpdateParent(yaffs_Object *obj);
56 static int yaffs_UnlinkObject(yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
61 yaffs_ExtendedTags *tags,
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66 yaffs_ObjectType type);
69 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
75 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
78 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
81 static int yaffs_UnlinkWorker(yaffs_Object *obj);
83 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
86 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
87 yaffs_BlockInfo **blockUsedPtr);
89 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
91 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
92 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
94 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
95 yaffs_ExtendedTags *tags);
97 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
100 yaffs_ExtendedTags *tags);
103 static void yaffs_LoadNameFromObjectHeader(yaffs_Device *dev,YCHAR *name, const YCHAR *ohName, int bufferSize);
104 static void yaffs_LoadObjectHeaderFromName(yaffs_Device *dev,YCHAR *ohName, const YCHAR *name);
107 /* Function to calculate chunk and offset */
109 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
115 chunk = (__u32)(addr >> dev->chunkShift);
117 if (dev->chunkDiv == 1) {
118 /* easy power of 2 case */
119 offset = (__u32)(addr & dev->chunkMask);
121 /* Non power-of-2 case */
125 chunk /= dev->chunkDiv;
127 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
128 offset = (__u32)(addr - chunkBase);
135 /* Function to return the number of shifts for a power of 2 greater than or
136 * equal 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;
161 /* Function to return the number of shifts to get a 1 in bit 0
164 static __u32 Shifts(__u32 x)
184 * Temporary buffer manipulations.
187 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
190 __u8 *buf = (__u8 *)1;
192 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
194 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
195 dev->tempBuffer[i].line = 0; /* not in use */
196 dev->tempBuffer[i].buffer = buf =
197 YMALLOC_DMA(dev->param.totalBytesPerChunk);
200 return buf ? YAFFS_OK : YAFFS_FAIL;
203 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
208 if (dev->tempInUse > dev->maxTemp)
209 dev->maxTemp = dev->tempInUse;
211 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
212 if (dev->tempBuffer[i].line == 0) {
213 dev->tempBuffer[i].line = lineNo;
214 if ((i + 1) > dev->maxTemp) {
215 dev->maxTemp = i + 1;
216 for (j = 0; j <= i; j++)
217 dev->tempBuffer[j].maxLine =
218 dev->tempBuffer[j].line;
221 return dev->tempBuffer[i].buffer;
225 T(YAFFS_TRACE_BUFFERS,
226 (TSTR("Out of temp buffers at line %d, other held by lines:"),
228 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
229 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
231 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
234 * If we got here then we have to allocate an unmanaged one
238 dev->unmanagedTempAllocations++;
239 return YMALLOC(dev->nDataBytesPerChunk);
243 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
250 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
251 if (dev->tempBuffer[i].buffer == buffer) {
252 dev->tempBuffer[i].line = 0;
258 /* assume it is an unmanaged one. */
259 T(YAFFS_TRACE_BUFFERS,
260 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
263 dev->unmanagedTempDeallocations++;
269 * Determine if we have a managed buffer.
271 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
275 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
276 if (dev->tempBuffer[i].buffer == buffer)
280 for (i = 0; i < dev->param.nShortOpCaches; i++) {
281 if (dev->srCache[i].data == buffer)
285 if (buffer == dev->checkpointBuffer)
288 T(YAFFS_TRACE_ALWAYS,
289 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
301 * Simple hash function. Needs to have a reasonable spread
304 static Y_INLINE int yaffs_HashFunction(int n)
307 return n % YAFFS_NOBJECT_BUCKETS;
311 * Access functions to useful fake objects.
312 * Note that root might have a presence in NAND if permissions are set.
315 yaffs_Object *yaffs_Root(yaffs_Device *dev)
320 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
322 return dev->lostNFoundDir;
327 * Erased NAND checking functions
330 int yaffs_CheckFF(__u8 *buffer, int nBytes)
332 /* Horrible, slow implementation */
341 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
344 int retval = YAFFS_OK;
345 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
346 yaffs_ExtendedTags tags;
349 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
351 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
354 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
355 T(YAFFS_TRACE_NANDACCESS,
356 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
360 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
367 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
370 yaffs_ExtendedTags *tags)
372 int retval = YAFFS_OK;
373 yaffs_ExtendedTags tempTags;
374 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
377 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
378 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
379 tempTags.objectId != tags->objectId ||
380 tempTags.chunkId != tags->chunkId ||
381 tempTags.byteCount != tags->byteCount)
384 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
389 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
391 yaffs_ExtendedTags *tags,
398 yaffs2_InvalidateCheckpoint(dev);
401 yaffs_BlockInfo *bi = 0;
404 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
410 /* First check this chunk is erased, if it needs
411 * checking. The checking policy (unless forced
412 * always on) is as follows:
414 * Check the first page we try to write in a block.
415 * If the check passes then we don't need to check any
416 * more. If the check fails, we check again...
417 * If the block has been erased, we don't need to check.
419 * However, if the block has been prioritised for gc,
420 * then we think there might be something odd about
421 * this block and stop using it.
423 * Rationale: We should only ever see chunks that have
424 * not been erased if there was a partially written
425 * chunk due to power loss. This checking policy should
426 * catch that case with very few checks and thus save a
427 * lot of checks that are most likely not needed.
430 * If an erase check fails or the write fails we skip the
434 /* let's give it a try */
437 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
438 bi->skipErasedCheck = 0;
440 if (!bi->skipErasedCheck) {
441 erasedOk = yaffs_CheckChunkErased(dev, chunk);
442 if (erasedOk != YAFFS_OK) {
444 (TSTR("**>> yaffs chunk %d was not erased"
447 /* If not erased, delete this one,
448 * skip rest of block and
449 * try another chunk */
450 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
451 yaffs_SkipRestOfBlock(dev);
456 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
459 if(!bi->skipErasedCheck)
460 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
462 if (writeOk != YAFFS_OK) {
463 /* Clean up aborted write, skip to next block and
464 * try another chunk */
465 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
469 bi->skipErasedCheck = 1;
471 /* Copy the data into the robustification buffer */
472 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
474 } while (writeOk != YAFFS_OK &&
475 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
482 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
485 dev->nRetriedWrites += (attempts - 1);
494 * Block retiring for handling a broken block.
497 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
499 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
501 yaffs2_InvalidateCheckpoint(dev);
503 yaffs2_ClearOldestDirtySequence(dev,bi);
505 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
506 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
507 T(YAFFS_TRACE_ALWAYS, (TSTR(
508 "yaffs: Failed to mark bad and erase block %d"
509 TENDSTR), blockInNAND));
511 yaffs_ExtendedTags tags;
512 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
514 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
516 memset(buffer, 0xff, dev->nDataBytesPerChunk);
517 yaffs_InitialiseTags(&tags);
518 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
519 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
520 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
521 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
522 TCONT("write bad block marker to block %d")
523 TENDSTR), blockInNAND));
525 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
529 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
530 bi->gcPrioritise = 0;
531 bi->needsRetiring = 0;
533 dev->nRetiredBlocks++;
537 * Functions for robustisizing TODO
541 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
543 const yaffs_ExtendedTags *tags)
546 chunkInNAND=chunkInNAND;
551 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
552 const yaffs_ExtendedTags *tags)
555 chunkInNAND=chunkInNAND;
559 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
561 if (!bi->gcPrioritise) {
562 bi->gcPrioritise = 1;
563 dev->hasPendingPrioritisedGCs = 1;
564 bi->chunkErrorStrikes++;
566 if (bi->chunkErrorStrikes > 3) {
567 bi->needsRetiring = 1; /* Too many stikes, so retire this */
568 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
574 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
577 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
578 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
580 yaffs_HandleChunkError(dev, bi);
583 /* Was an actual write failure, so mark the block for retirement */
584 bi->needsRetiring = 1;
585 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
586 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
589 /* Delete the chunk */
590 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
591 yaffs_SkipRestOfBlock(dev);
595 /*---------------- Name handling functions ------------*/
597 static __u16 yaffs_CalcNameSum(const YCHAR *name)
602 const YUCHAR *bname = (const YUCHAR *) name;
604 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
606 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
607 sum += yaffs_toupper(*bname) * i;
618 void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
620 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
621 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
622 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
623 yaffs_strcpy(obj->shortName, name);
625 obj->shortName[0] = _Y('\0');
627 obj->sum = yaffs_CalcNameSum(name);
630 void yaffs_SetObjectNameFromOH(yaffs_Object *obj, const yaffs_ObjectHeader *oh)
632 #ifdef CONFIG_YAFFS_AUTO_UNICODE
633 YCHAR tmpName[YAFFS_MAX_NAME_LENGTH+1];
634 memset(tmpName,0,sizeof(tmpName));
635 yaffs_LoadNameFromObjectHeader(obj->myDev,tmpName,oh->name,YAFFS_MAX_NAME_LENGTH+1);
636 yaffs_SetObjectName(obj,tmpName);
638 yaffs_SetObjectName(obj,oh->name);
642 /*-------------------- TNODES -------------------
644 * List of spare tnodes
645 * The list is hooked together using the first pointer
650 yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
652 yaffs_Tnode *tn = yaffs_AllocateRawTnode(dev);
654 memset(tn, 0, dev->tnodeSize);
658 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
663 /* FreeTnode frees up a tnode and puts it back on the free list */
664 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
666 yaffs_FreeRawTnode(dev,tn);
668 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
671 static void yaffs_DeinitialiseTnodesAndObjects(yaffs_Device *dev)
673 yaffs_DeinitialiseRawTnodesAndObjects(dev);
679 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
682 __u32 *map = (__u32 *)tn;
688 pos &= YAFFS_TNODES_LEVEL0_MASK;
689 val >>= dev->chunkGroupBits;
691 bitInMap = pos * dev->tnodeWidth;
692 wordInMap = bitInMap / 32;
693 bitInWord = bitInMap & (32 - 1);
695 mask = dev->tnodeMask << bitInWord;
697 map[wordInMap] &= ~mask;
698 map[wordInMap] |= (mask & (val << bitInWord));
700 if (dev->tnodeWidth > (32 - bitInWord)) {
701 bitInWord = (32 - bitInWord);
703 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
704 map[wordInMap] &= ~mask;
705 map[wordInMap] |= (mask & (val >> bitInWord));
709 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
712 __u32 *map = (__u32 *)tn;
718 pos &= YAFFS_TNODES_LEVEL0_MASK;
720 bitInMap = pos * dev->tnodeWidth;
721 wordInMap = bitInMap / 32;
722 bitInWord = bitInMap & (32 - 1);
724 val = map[wordInMap] >> bitInWord;
726 if (dev->tnodeWidth > (32 - bitInWord)) {
727 bitInWord = (32 - bitInWord);
729 val |= (map[wordInMap] << bitInWord);
732 val &= dev->tnodeMask;
733 val <<= dev->chunkGroupBits;
738 /* ------------------- End of individual tnode manipulation -----------------*/
740 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
741 * The look up tree is represented by the top tnode and the number of topLevel
742 * in the tree. 0 means only the level 0 tnode is in the tree.
745 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
746 yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
747 yaffs_FileStructure *fStruct,
750 yaffs_Tnode *tn = fStruct->top;
752 int requiredTallness;
753 int level = fStruct->topLevel;
757 /* Check sane level and chunk Id */
758 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
761 if (chunkId > YAFFS_MAX_CHUNK_ID)
764 /* First check we're tall enough (ie enough topLevel) */
766 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
767 requiredTallness = 0;
769 i >>= YAFFS_TNODES_INTERNAL_BITS;
773 if (requiredTallness > fStruct->topLevel)
774 return NULL; /* Not tall enough, so we can't find it */
776 /* Traverse down to level 0 */
777 while (level > 0 && tn) {
778 tn = tn->internal[(chunkId >>
779 (YAFFS_TNODES_LEVEL0_BITS +
781 YAFFS_TNODES_INTERNAL_BITS)) &
782 YAFFS_TNODES_INTERNAL_MASK];
789 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
790 * This happens in two steps:
791 * 1. If the tree isn't tall enough, then make it taller.
792 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
794 * Used when modifying the tree.
796 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
797 * be plugged into the ttree.
800 yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
801 yaffs_FileStructure *fStruct,
803 yaffs_Tnode *passedTn)
805 int requiredTallness;
813 /* Check sane level and page Id */
814 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
817 if (chunkId > YAFFS_MAX_CHUNK_ID)
820 /* First check we're tall enough (ie enough topLevel) */
822 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
823 requiredTallness = 0;
825 x >>= YAFFS_TNODES_INTERNAL_BITS;
830 if (requiredTallness > fStruct->topLevel) {
831 /* Not tall enough, gotta make the tree taller */
832 for (i = fStruct->topLevel; i < requiredTallness; i++) {
834 tn = yaffs_GetTnode(dev);
837 tn->internal[0] = fStruct->top;
842 (TSTR("yaffs: no more tnodes" TENDSTR)));
848 /* Traverse down to level 0, adding anything we need */
850 l = fStruct->topLevel;
854 while (l > 0 && tn) {
856 (YAFFS_TNODES_LEVEL0_BITS +
857 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
858 YAFFS_TNODES_INTERNAL_MASK;
861 if ((l > 1) && !tn->internal[x]) {
862 /* Add missing non-level-zero tnode */
863 tn->internal[x] = yaffs_GetTnode(dev);
867 /* Looking from level 1 at level 0 */
869 /* If we already have one, then release it.*/
871 yaffs_FreeTnode(dev, tn->internal[x]);
872 tn->internal[x] = passedTn;
874 } else if (!tn->internal[x]) {
875 /* Don't have one, none passed in */
876 tn->internal[x] = yaffs_GetTnode(dev);
882 tn = tn->internal[x];
888 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
889 yaffs_FreeTnode(dev, passedTn);
896 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
897 yaffs_ExtendedTags *tags, int objectId,
902 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
903 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
904 theChunk % dev->param.nChunksPerBlock)) {
906 if(dev->chunkGroupSize == 1)
909 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
911 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
923 /* Experimental code not being used yet. Might speed up file deletion */
924 /* DeleteWorker scans backwards through the tnode tree and deletes all the
925 * chunks and tnodes in the file.
926 * Returns 1 if the tree was deleted.
927 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
930 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
931 int chunkOffset, int *limit)
936 yaffs_ExtendedTags tags;
938 yaffs_Device *dev = in->myDev;
944 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
946 if (tn->internal[i]) {
947 if (limit && (*limit) < 0) {
951 yaffs_DeleteWorker(in,
959 YAFFS_TNODES_INTERNAL_BITS)
967 tn->internal[i] = NULL;
971 return (allDone) ? 1 : 0;
972 } else if (level == 0) {
975 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
977 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
980 chunkInInode = (chunkOffset <<
981 YAFFS_TNODES_LEVEL0_BITS) + i;
984 yaffs_FindChunkInGroup(dev,
990 if (foundChunk > 0) {
991 yaffs_DeleteChunk(dev,
1003 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1007 return (i < 0) ? 1 : 0;
1019 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1021 yaffs_BlockInfo *theBlock;
1024 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1026 blockNo = chunk / dev->param.nChunksPerBlock;
1027 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1029 theBlock->softDeletions++;
1031 yaffs2_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1035 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1036 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1038 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1041 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1042 __u32 level, int chunkOffset)
1047 yaffs_Device *dev = in->myDev;
1052 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1054 if (tn->internal[i]) {
1056 yaffs_SoftDeleteWorker(in,
1062 YAFFS_TNODES_INTERNAL_BITS)
1065 yaffs_FreeTnode(dev,
1068 tn->internal[i] = NULL;
1070 /* Hoosterman... how could this happen? */
1074 return (allDone) ? 1 : 0;
1075 } else if (level == 0) {
1077 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1078 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1080 /* Note this does not find the real chunk, only the chunk group.
1081 * We make an assumption that a chunk group is not larger than
1084 yaffs_SoftDeleteChunk(dev, theChunk);
1085 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1099 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1102 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1103 if (obj->nDataChunks <= 0) {
1104 /* Empty file with no duplicate object headers, just delete it immediately */
1105 yaffs_FreeTnode(obj->myDev,
1106 obj->variant.fileVariant.top);
1107 obj->variant.fileVariant.top = NULL;
1108 T(YAFFS_TRACE_TRACING,
1109 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1111 yaffs_DoGenericObjectDeletion(obj);
1113 yaffs_SoftDeleteWorker(obj,
1114 obj->variant.fileVariant.top,
1115 obj->variant.fileVariant.
1117 obj->softDeleted = 1;
1122 /* Pruning removes any part of the file structure tree that is beyond the
1123 * bounds of the file (ie that does not point to chunks).
1125 * A file should only get pruned when its size is reduced.
1127 * Before pruning, the chunks must be pulled from the tree and the
1128 * level 0 tnode entries must be zeroed out.
1129 * Could also use this for file deletion, but that's probably better handled
1130 * by a special case.
1132 * This function is recursive. For levels > 0 the function is called again on
1133 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1134 * If there is no data in a subtree then it is pruned.
1137 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1138 __u32 level, int del0)
1147 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1148 if (tn->internal[i]) {
1150 yaffs_PruneWorker(dev, tn->internal[i],
1152 (i == 0) ? del0 : 1);
1155 if (tn->internal[i])
1159 int tnodeSize_u32 = dev->tnodeSize/sizeof(__u32);
1160 __u32 *map = (__u32 *)tn;
1162 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1168 if (hasData == 0 && del0) {
1169 /* Free and return NULL */
1171 yaffs_FreeTnode(dev, tn);
1181 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1182 yaffs_FileStructure *fStruct)
1189 if (fStruct->topLevel > 0) {
1191 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1193 /* Now we have a tree with all the non-zero branches NULL but the height
1194 * is the same as it was.
1195 * Let's see if we can trim internal tnodes to shorten the tree.
1196 * We can do this if only the 0th element in the tnode is in use
1197 * (ie all the non-zero are NULL)
1200 while (fStruct->topLevel && !done) {
1204 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1205 if (tn->internal[i])
1210 fStruct->top = tn->internal[0];
1211 fStruct->topLevel--;
1212 yaffs_FreeTnode(dev, tn);
1222 /*-------------------- End of File Structure functions.-------------------*/
1225 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1226 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1228 yaffs_Object *obj = yaffs_AllocateRawObject(dev);
1233 /* Now sweeten it up... */
1235 memset(obj, 0, sizeof(yaffs_Object));
1236 obj->beingCreated = 1;
1240 obj->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1241 YINIT_LIST_HEAD(&(obj->hardLinks));
1242 YINIT_LIST_HEAD(&(obj->hashLink));
1243 YINIT_LIST_HEAD(&obj->siblings);
1246 /* Now make the directory sane */
1248 obj->parent = dev->rootDir;
1249 ylist_add(&(obj->siblings), &dev->rootDir->variant.directoryVariant.children);
1252 /* Add it to the lost and found directory.
1253 * NB Can't put root or lostNFound in lostNFound so
1254 * check if lostNFound exists first
1256 if (dev->lostNFoundDir)
1257 yaffs_AddObjectToDirectory(dev->lostNFoundDir, obj);
1259 obj->beingCreated = 0;
1262 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1267 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1272 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1274 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1275 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1276 obj->unlinkAllowed = 0; /* ... or unlink it */
1279 obj->yst_mode = mode;
1281 obj->hdrChunk = 0; /* Not a valid chunk. */
1288 static void yaffs_UnhashObject(yaffs_Object *obj)
1291 yaffs_Device *dev = obj->myDev;
1293 /* If it is still linked into the bucket list, free from the list */
1294 if (!ylist_empty(&obj->hashLink)) {
1295 ylist_del_init(&obj->hashLink);
1296 bucket = yaffs_HashFunction(obj->objectId);
1297 dev->objectBucket[bucket].count--;
1301 /* FreeObject frees up a Object and puts it back on the free list */
1302 static void yaffs_FreeObject(yaffs_Object *obj)
1304 yaffs_Device *dev = obj->myDev;
1306 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), obj, obj->myInode));
1312 if (!ylist_empty(&obj->siblings))
1317 /* We're still hooked up to a cached inode.
1318 * Don't delete now, but mark for later deletion
1320 obj->deferedFree = 1;
1324 yaffs_UnhashObject(obj);
1326 yaffs_FreeRawObject(dev,obj);
1328 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1332 void yaffs_HandleDeferedFree(yaffs_Object *obj)
1334 if (obj->deferedFree)
1335 yaffs_FreeObject(obj);
1338 static void yaffs_InitialiseTnodesAndObjects(yaffs_Device *dev)
1345 yaffs_InitialiseRawTnodesAndObjects(dev);
1347 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1348 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
1349 dev->objectBucket[i].count = 0;
1353 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1357 int lowest = 999999;
1360 /* Search for the shortest list or one that
1364 for (i = 0; i < 10 && lowest > 4; i++) {
1365 dev->bucketFinder++;
1366 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
1367 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
1368 lowest = dev->objectBucket[dev->bucketFinder].count;
1369 l = dev->bucketFinder;
1377 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1379 int bucket = yaffs_FindNiceObjectBucket(dev);
1381 /* Now find an object value that has not already been taken
1382 * by scanning the list.
1386 struct ylist_head *i;
1388 __u32 n = (__u32) bucket;
1390 /* yaffs_CheckObjectHashSanity(); */
1394 n += YAFFS_NOBJECT_BUCKETS;
1395 if (1 || dev->objectBucket[bucket].count > 0) {
1396 ylist_for_each(i, &dev->objectBucket[bucket].list) {
1397 /* If there is already one in the list */
1398 if (i && ylist_entry(i, yaffs_Object,
1399 hashLink)->objectId == n) {
1409 static void yaffs_HashObject(yaffs_Object *in)
1411 int bucket = yaffs_HashFunction(in->objectId);
1412 yaffs_Device *dev = in->myDev;
1414 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
1415 dev->objectBucket[bucket].count++;
1418 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
1420 int bucket = yaffs_HashFunction(number);
1421 struct ylist_head *i;
1424 ylist_for_each(i, &dev->objectBucket[bucket].list) {
1425 /* Look if it is in the list */
1427 in = ylist_entry(i, yaffs_Object, hashLink);
1428 if (in->objectId == number) {
1430 /* Don't tell the VFS about this one if it is defered free */
1431 if (in->deferedFree)
1442 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
1443 yaffs_ObjectType type)
1445 yaffs_Object *theObject=NULL;
1446 yaffs_Tnode *tn = NULL;
1449 number = yaffs_CreateNewObjectNumber(dev);
1451 if (type == YAFFS_OBJECT_TYPE_FILE) {
1452 tn = yaffs_GetTnode(dev);
1457 theObject = yaffs_AllocateEmptyObject(dev);
1460 yaffs_FreeTnode(dev,tn);
1466 theObject->fake = 0;
1467 theObject->renameAllowed = 1;
1468 theObject->unlinkAllowed = 1;
1469 theObject->objectId = number;
1470 yaffs_HashObject(theObject);
1471 theObject->variantType = type;
1472 #ifdef CONFIG_YAFFS_WINCE
1473 yfsd_WinFileTimeNow(theObject->win_atime);
1474 theObject->win_ctime[0] = theObject->win_mtime[0] =
1475 theObject->win_atime[0];
1476 theObject->win_ctime[1] = theObject->win_mtime[1] =
1477 theObject->win_atime[1];
1481 theObject->yst_atime = theObject->yst_mtime =
1482 theObject->yst_ctime = Y_CURRENT_TIME;
1485 case YAFFS_OBJECT_TYPE_FILE:
1486 theObject->variant.fileVariant.fileSize = 0;
1487 theObject->variant.fileVariant.scannedFileSize = 0;
1488 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1489 theObject->variant.fileVariant.topLevel = 0;
1490 theObject->variant.fileVariant.top = tn;
1492 case YAFFS_OBJECT_TYPE_DIRECTORY:
1493 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
1495 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
1498 case YAFFS_OBJECT_TYPE_SYMLINK:
1499 case YAFFS_OBJECT_TYPE_HARDLINK:
1500 case YAFFS_OBJECT_TYPE_SPECIAL:
1501 /* No action required */
1503 case YAFFS_OBJECT_TYPE_UNKNOWN:
1504 /* todo this should not happen */
1512 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
1514 yaffs_ObjectType type)
1516 yaffs_Object *theObject = NULL;
1519 theObject = yaffs_FindObjectByNumber(dev, number);
1522 theObject = yaffs_CreateNewObject(dev, number, type);
1529 YCHAR *yaffs_CloneString(const YCHAR *str)
1531 YCHAR *newStr = NULL;
1537 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
1538 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
1540 yaffs_strncpy(newStr, str,len);
1548 * Mknod (create) a new object.
1549 * equivalentObject only has meaning for a hard link;
1550 * aliasString only has meaning for a symlink.
1551 * rdev only has meaning for devices (a subset of special objects)
1554 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1555 yaffs_Object *parent,
1560 yaffs_Object *equivalentObject,
1561 const YCHAR *aliasString, __u32 rdev)
1566 yaffs_Device *dev = parent->myDev;
1568 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1569 if (yaffs_FindObjectByName(parent, name))
1572 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
1573 str = yaffs_CloneString(aliasString);
1578 in = yaffs_CreateNewObject(dev, -1, type);
1593 in->variantType = type;
1595 in->yst_mode = mode;
1597 #ifdef CONFIG_YAFFS_WINCE
1598 yfsd_WinFileTimeNow(in->win_atime);
1599 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1600 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1603 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1605 in->yst_rdev = rdev;
1609 in->nDataChunks = 0;
1611 yaffs_SetObjectName(in, name);
1614 yaffs_AddObjectToDirectory(parent, in);
1616 in->myDev = parent->myDev;
1619 case YAFFS_OBJECT_TYPE_SYMLINK:
1620 in->variant.symLinkVariant.alias = str;
1622 case YAFFS_OBJECT_TYPE_HARDLINK:
1623 in->variant.hardLinkVariant.equivalentObject =
1625 in->variant.hardLinkVariant.equivalentObjectId =
1626 equivalentObject->objectId;
1627 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
1629 case YAFFS_OBJECT_TYPE_FILE:
1630 case YAFFS_OBJECT_TYPE_DIRECTORY:
1631 case YAFFS_OBJECT_TYPE_SPECIAL:
1632 case YAFFS_OBJECT_TYPE_UNKNOWN:
1637 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0, NULL) < 0) {
1638 /* Could not create the object header, fail the creation */
1639 yaffs_DeleteObject(in);
1643 yaffs_UpdateParent(parent);
1649 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
1650 __u32 mode, __u32 uid, __u32 gid)
1652 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1653 uid, gid, NULL, NULL, 0);
1656 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
1657 __u32 mode, __u32 uid, __u32 gid)
1659 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1660 mode, uid, gid, NULL, NULL, 0);
1663 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
1664 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1666 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1667 uid, gid, NULL, NULL, rdev);
1670 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
1671 __u32 mode, __u32 uid, __u32 gid,
1674 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1675 uid, gid, NULL, alias, 0);
1678 /* yaffs_Link returns the object id of the equivalent object.*/
1679 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
1680 yaffs_Object *equivalentObject)
1682 /* Get the real object in case we were fed a hard link as an equivalent object */
1683 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1685 if (yaffs_MknodObject
1686 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1687 equivalentObject, NULL, 0)) {
1688 return equivalentObject;
1695 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
1696 const YCHAR *newName, int force, int shadows)
1701 yaffs_Object *existingTarget;
1704 newDir = obj->parent; /* use the old directory */
1706 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1707 T(YAFFS_TRACE_ALWAYS,
1709 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
1714 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1715 if (obj->myDev->param.isYaffs2)
1716 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1718 unlinkOp = (newDir == obj->myDev->unlinkedDir
1719 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1721 deleteOp = (newDir == obj->myDev->deletedDir);
1723 existingTarget = yaffs_FindObjectByName(newDir, newName);
1725 /* If the object is a file going into the unlinked directory,
1726 * then it is OK to just stuff it in since duplicate names are allowed.
1727 * else only proceed if the new name does not exist and if we're putting
1728 * it into a directory.
1735 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1736 yaffs_SetObjectName(obj, newName);
1739 yaffs_AddObjectToDirectory(newDir, obj);
1744 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1745 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows, NULL) >= 0)
1752 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
1753 yaffs_Object *newDir, const YCHAR *newName)
1755 yaffs_Object *obj = NULL;
1756 yaffs_Object *existingTarget = NULL;
1762 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1764 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1767 dev = oldDir->myDev;
1769 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1770 /* Special case for case insemsitive systems (eg. WinCE).
1771 * While look-up is case insensitive, the name isn't.
1772 * Therefore we might want to change x.txt to X.txt
1774 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
1778 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
1782 obj = yaffs_FindObjectByName(oldDir, oldName);
1784 if (obj && obj->renameAllowed) {
1786 /* Now do the handling for an existing target, if there is one */
1788 existingTarget = yaffs_FindObjectByName(newDir, newName);
1789 if (existingTarget &&
1790 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1791 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
1792 /* There is a target that is a non-empty directory, so we fail */
1793 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1794 } else if (existingTarget && existingTarget != obj) {
1795 /* Nuke the target first, using shadowing,
1796 * but only if it isn't the same object.
1798 * Note we must disable gc otherwise it can mess up the shadowing.
1802 yaffs_ChangeObjectName(obj, newDir, newName, force,
1803 existingTarget->objectId);
1804 existingTarget->isShadowed = 1;
1805 yaffs_UnlinkObject(existingTarget);
1809 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1811 yaffs_UpdateParent(oldDir);
1812 if(newDir != oldDir)
1813 yaffs_UpdateParent(newDir);
1820 /*------------------------- Block Management and Page Allocation ----------------*/
1822 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
1824 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1826 dev->blockInfo = NULL;
1827 dev->chunkBits = NULL;
1829 dev->allocationBlock = -1; /* force it to get a new one */
1831 /* If the first allocation strategy fails, thry the alternate one */
1832 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1833 if (!dev->blockInfo) {
1834 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1835 dev->blockInfoAlt = 1;
1837 dev->blockInfoAlt = 0;
1839 if (dev->blockInfo) {
1840 /* Set up dynamic blockinfo stuff. */
1841 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
1842 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1843 if (!dev->chunkBits) {
1844 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1845 dev->chunkBitsAlt = 1;
1847 dev->chunkBitsAlt = 0;
1850 if (dev->blockInfo && dev->chunkBits) {
1851 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1852 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1859 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1861 if (dev->blockInfoAlt && dev->blockInfo)
1862 YFREE_ALT(dev->blockInfo);
1863 else if (dev->blockInfo)
1864 YFREE(dev->blockInfo);
1866 dev->blockInfoAlt = 0;
1868 dev->blockInfo = NULL;
1870 if (dev->chunkBitsAlt && dev->chunkBits)
1871 YFREE_ALT(dev->chunkBits);
1872 else if (dev->chunkBits)
1873 YFREE(dev->chunkBits);
1874 dev->chunkBitsAlt = 0;
1875 dev->chunkBits = NULL;
1878 void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
1880 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1884 /* If the block is still healthy erase it and mark as clean.
1885 * If the block has had a data failure, then retire it.
1888 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
1889 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
1890 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
1892 yaffs2_ClearOldestDirtySequence(dev,bi);
1894 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1896 /* If this is the block being garbage collected then stop gc'ing this block */
1897 if(blockNo == dev->gcBlock)
1900 /* If this block is currently the best candidate for gc then drop as a candidate */
1901 if(blockNo == dev->gcDirtiest){
1902 dev->gcDirtiest = 0;
1903 dev->gcPagesInUse = 0;
1906 if (!bi->needsRetiring) {
1907 yaffs2_InvalidateCheckpoint(dev);
1908 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1910 dev->nErasureFailures++;
1911 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1912 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1917 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
1919 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
1920 if (!yaffs_CheckChunkErased
1921 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
1922 T(YAFFS_TRACE_ERROR,
1924 (">>Block %d erasure supposedly OK, but chunk %d not erased"
1925 TENDSTR), blockNo, i));
1931 /* Clean it up... */
1932 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1933 bi->sequenceNumber = 0;
1934 dev->nErasedBlocks++;
1936 bi->softDeletions = 0;
1937 bi->hasShrinkHeader = 0;
1938 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
1939 bi->gcPrioritise = 0;
1940 yaffs_ClearChunkBits(dev, blockNo);
1942 T(YAFFS_TRACE_ERASE,
1943 (TSTR("Erased block %d" TENDSTR), blockNo));
1945 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
1947 yaffs_RetireBlock(dev, blockNo);
1948 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1949 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
1953 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
1957 yaffs_BlockInfo *bi;
1959 if (dev->nErasedBlocks < 1) {
1960 /* Hoosterman we've got a problem.
1961 * Can't get space to gc
1963 T(YAFFS_TRACE_ERROR,
1964 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
1969 /* Find an empty block. */
1971 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1972 dev->allocationBlockFinder++;
1973 if (dev->allocationBlockFinder < dev->internalStartBlock
1974 || dev->allocationBlockFinder > dev->internalEndBlock) {
1975 dev->allocationBlockFinder = dev->internalStartBlock;
1978 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
1980 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
1981 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1982 dev->sequenceNumber++;
1983 bi->sequenceNumber = dev->sequenceNumber;
1984 dev->nErasedBlocks--;
1985 T(YAFFS_TRACE_ALLOCATE,
1986 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
1987 dev->allocationBlockFinder, dev->sequenceNumber,
1988 dev->nErasedBlocks));
1989 return dev->allocationBlockFinder;
1993 T(YAFFS_TRACE_ALWAYS,
1995 ("yaffs tragedy: no more erased blocks, but there should have been %d"
1996 TENDSTR), dev->nErasedBlocks));
2003 * Check if there's space to allocate...
2004 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2006 int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
2009 int reservedBlocks = dev->param.nReservedBlocks;
2010 int checkpointBlocks;
2012 checkpointBlocks = yaffs2_CalcCheckpointBlocksRequired(dev);
2014 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
2016 return (dev->nFreeChunks > (reservedChunks + nChunks));
2019 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2020 yaffs_BlockInfo **blockUsedPtr)
2023 yaffs_BlockInfo *bi;
2025 if (dev->allocationBlock < 0) {
2026 /* Get next block to allocate off */
2027 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2028 dev->allocationPage = 0;
2031 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
2032 /* Not enough space to allocate unless we're allowed to use the reserve. */
2036 if (dev->nErasedBlocks < dev->param.nReservedBlocks
2037 && dev->allocationPage == 0) {
2038 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2041 /* Next page please.... */
2042 if (dev->allocationBlock >= 0) {
2043 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2045 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
2046 dev->allocationPage;
2048 yaffs_SetChunkBit(dev, dev->allocationBlock,
2049 dev->allocationPage);
2051 dev->allocationPage++;
2055 /* If the block is full set the state to full */
2056 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
2057 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2058 dev->allocationBlock = -1;
2067 T(YAFFS_TRACE_ERROR,
2068 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2073 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2077 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2079 if (dev->allocationBlock > 0)
2080 n += (dev->param.nChunksPerBlock - dev->allocationPage);
2087 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
2088 * if we don't want to write to it.
2090 void yaffs_SkipRestOfBlock(yaffs_Device *dev)
2092 if(dev->allocationBlock > 0){
2093 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2094 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
2095 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2096 dev->allocationBlock = -1;
2102 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2108 int retVal = YAFFS_OK;
2110 int isCheckpointBlock;
2114 int chunksBefore = yaffs_GetErasedChunks(dev);
2117 yaffs_ExtendedTags tags;
2119 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2121 yaffs_Object *object;
2123 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2126 T(YAFFS_TRACE_TRACING,
2127 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2130 bi->hasShrinkHeader,
2133 /*yaffs_VerifyFreeChunks(dev); */
2135 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
2136 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2138 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2142 if (isCheckpointBlock ||
2143 !yaffs_StillSomeChunkBits(dev, block)) {
2144 T(YAFFS_TRACE_TRACING,
2146 ("Collecting block %d that has no chunks in use" TENDSTR),
2148 yaffs_BlockBecameDirty(dev, block);
2151 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2153 yaffs_VerifyBlock(dev, bi, block);
2155 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
2156 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
2158 for (/* init already done */;
2159 retVal == YAFFS_OK &&
2160 dev->gcChunk < dev->param.nChunksPerBlock &&
2161 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
2163 dev->gcChunk++, oldChunk++) {
2164 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
2166 /* This page is in use and might need to be copied off */
2172 yaffs_InitialiseTags(&tags);
2174 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2178 yaffs_FindObjectByNumber(dev,
2181 T(YAFFS_TRACE_GC_DETAIL,
2183 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
2184 dev->gcChunk, tags.objectId, tags.chunkId,
2187 if (object && !yaffs_SkipVerification(dev)) {
2188 if (tags.chunkId == 0)
2189 matchingChunk = object->hdrChunk;
2190 else if (object->softDeleted)
2191 matchingChunk = oldChunk; /* Defeat the test */
2193 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
2195 if (oldChunk != matchingChunk)
2196 T(YAFFS_TRACE_ERROR,
2197 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2198 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
2203 T(YAFFS_TRACE_ERROR,
2205 ("page %d in gc has no object: %d %d %d "
2207 tags.objectId, tags.chunkId, tags.byteCount));
2212 object->softDeleted &&
2213 tags.chunkId != 0) {
2214 /* Data chunk in a soft deleted file, throw it away
2215 * It's a soft deleted data chunk,
2216 * No need to copy this, just forget about it and
2217 * fix up the object.
2220 /* Free chunks already includes softdeleted chunks.
2221 * How ever this chunk is going to soon be really deleted
2222 * which will increment free chunks.
2223 * We have to decrement free chunks so this works out properly.
2226 bi->softDeletions--;
2228 object->nDataChunks--;
2230 if (object->nDataChunks <= 0) {
2231 /* remeber to clean up the object */
2232 dev->gcCleanupList[dev->nCleanups] =
2238 /* Todo object && object->deleted && object->nDataChunks == 0 */
2239 /* Deleted object header with no data chunks.
2240 * Can be discarded and the file deleted.
2242 object->hdrChunk = 0;
2243 yaffs_FreeTnode(object->myDev,
2246 object->variant.fileVariant.top = NULL;
2247 yaffs_DoGenericObjectDeletion(object);
2249 } else if (object) {
2250 /* It's either a data chunk in a live file or
2251 * an ObjectHeader, so we're interested in it.
2252 * NB Need to keep the ObjectHeaders of deleted files
2253 * until the whole file has been deleted off
2255 tags.serialNumber++;
2259 if (tags.chunkId == 0) {
2260 /* It is an object Id,
2261 * We need to nuke the shrinkheader flags first
2262 * Also need to clean up shadowing.
2263 * We no longer want the shrinkHeader flag since its work is done
2264 * and if it is left in place it will mess up scanning.
2267 yaffs_ObjectHeader *oh;
2268 oh = (yaffs_ObjectHeader *)buffer;
2271 tags.extraIsShrinkHeader = 0;
2273 oh->shadowsObject = 0;
2274 oh->inbandShadowsObject = 0;
2275 tags.extraShadows = 0;
2277 /* Update file size */
2278 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
2279 oh->fileSize = object->variant.fileVariant.fileSize;
2280 tags.extraFileLength = oh->fileSize;
2283 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
2285 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
2288 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2291 retVal = YAFFS_FAIL;
2294 /* Ok, now fix up the Tnodes etc. */
2296 if (tags.chunkId == 0) {
2298 object->hdrChunk = newChunk;
2299 object->serial = tags.serialNumber;
2301 /* It's a data chunk */
2303 ok = yaffs_PutChunkIntoFile
2311 if (retVal == YAFFS_OK)
2312 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2317 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2323 yaffs_VerifyCollectedBlock(dev, bi, block);
2327 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2329 * The gc did not complete. Set block state back to FULL
2330 * because checkpointing does not restore gc.
2332 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2334 /* The gc completed. */
2335 /* Do any required cleanups */
2336 for (i = 0; i < dev->nCleanups; i++) {
2337 /* Time to delete the file too */
2339 yaffs_FindObjectByNumber(dev,
2340 dev->gcCleanupList[i]);
2342 yaffs_FreeTnode(dev,
2343 object->variant.fileVariant.
2345 object->variant.fileVariant.top = NULL;
2348 ("yaffs: About to finally delete object %d"
2349 TENDSTR), object->objectId));
2350 yaffs_DoGenericObjectDeletion(object);
2351 object->myDev->nDeletedFiles--;
2357 chunksAfter = yaffs_GetErasedChunks(dev);
2358 if (chunksBefore >= chunksAfter) {
2361 ("gc did not increase free chunks before %d after %d"
2362 TENDSTR), chunksBefore, chunksAfter));
2375 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2376 * for garbage collection.
2379 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2385 unsigned selected = 0;
2386 int prioritised = 0;
2387 int prioritisedExists = 0;
2388 yaffs_BlockInfo *bi;
2391 /* First let's see if we need to grab a prioritised block */
2392 if (dev->hasPendingPrioritisedGCs && !aggressive) {
2393 dev->gcDirtiest = 0;
2394 bi = dev->blockInfo;
2395 for (i = dev->internalStartBlock;
2396 i <= dev->internalEndBlock && !selected;
2399 if (bi->gcPrioritise) {
2400 prioritisedExists = 1;
2401 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2402 yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2411 * If there is a prioritised block and none was selected then
2412 * this happened because there is at least one old dirty block gumming
2413 * up the works. Let's gc the oldest dirty block.
2416 if(prioritisedExists &&
2418 dev->oldestDirtyBlock > 0)
2419 selected = dev->oldestDirtyBlock;
2421 if (!prioritisedExists) /* None found, so we can clear this */
2422 dev->hasPendingPrioritisedGCs = 0;
2425 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2427 * else (we're doing a leasurely gc), then we only bother to do this if the
2428 * block has only a few pages in use.
2433 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2435 threshold = dev->param.nChunksPerBlock;
2436 iterations = nBlocks;
2441 maxThreshold = dev->param.nChunksPerBlock/2;
2443 maxThreshold = dev->param.nChunksPerBlock/8;
2445 if(maxThreshold < YAFFS_GC_PASSIVE_THRESHOLD)
2446 maxThreshold = YAFFS_GC_PASSIVE_THRESHOLD;
2448 threshold = background ?
2449 (dev->gcNotDone + 2) * 2 : 0;
2450 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
2451 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2452 if(threshold > maxThreshold)
2453 threshold = maxThreshold;
2455 iterations = nBlocks / 16 + 1;
2456 if (iterations > 100)
2462 (dev->gcDirtiest < 1 ||
2463 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
2465 dev->gcBlockFinder++;
2466 if (dev->gcBlockFinder < dev->internalStartBlock ||
2467 dev->gcBlockFinder > dev->internalEndBlock)
2468 dev->gcBlockFinder = dev->internalStartBlock;
2470 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
2472 pagesUsed = bi->pagesInUse - bi->softDeletions;
2474 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2475 pagesUsed < dev->param.nChunksPerBlock &&
2476 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
2477 yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2478 dev->gcDirtiest = dev->gcBlockFinder;
2479 dev->gcPagesInUse = pagesUsed;
2483 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
2484 selected = dev->gcDirtiest;
2488 * If nothing has been selected for a while, try selecting the oldest dirty
2489 * because that's gumming up the works.
2492 if(!selected && dev->param.isYaffs2 &&
2493 dev->gcNotDone >= ( background ? 10 : 20)){
2494 yaffs2_FindOldestDirtySequence(dev);
2495 if(dev->oldestDirtyBlock > 0) {
2496 selected = dev->oldestDirtyBlock;
2497 dev->gcDirtiest = selected;
2498 dev->oldestDirtyGCs++;
2499 bi = yaffs_GetBlockInfo(dev, selected);
2500 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
2507 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
2509 dev->param.nChunksPerBlock - dev->gcPagesInUse,
2514 dev->backgroundGCs++;
2516 dev->gcDirtiest = 0;
2517 dev->gcPagesInUse = 0;
2519 if(dev->refreshSkip > 0)
2524 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
2525 dev->gcBlockFinder, dev->gcNotDone,
2527 dev->gcDirtiest, dev->gcPagesInUse,
2528 dev->oldestDirtyBlock,
2529 background ? " bg" : ""));
2535 /* New garbage collector
2536 * If we're very low on erased blocks then we do aggressive garbage collection
2537 * otherwise we do "leasurely" garbage collection.
2538 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2539 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2541 * The idea is to help clear out space in a more spread-out manner.
2542 * Dunno if it really does anything useful.
2544 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
2547 int gcOk = YAFFS_OK;
2551 int checkpointBlockAdjust;
2553 if(dev->param.gcControl &&
2554 (dev->param.gcControl(dev) & 1) == 0)
2557 if (dev->gcDisable) {
2558 /* Bail out so we don't get recursive gc */
2562 /* This loop should pass the first time.
2563 * We'll only see looping here if the collection does not increase space.
2569 checkpointBlockAdjust = yaffs2_CalcCheckpointBlocksRequired(dev);
2571 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
2572 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2574 /* If we need a block soon then do aggressive gc.*/
2575 if (dev->nErasedBlocks < minErased)
2578 if(!background && erasedChunks > (dev->nFreeChunks / 4))
2581 if(dev->gcSkip > 20)
2583 if(erasedChunks < dev->nFreeChunks/2 ||
2595 /* If we don't already have a block being gc'd then see if we should start another */
2597 if (dev->gcBlock < 1 && !aggressive) {
2598 dev->gcBlock = yaffs2_FindRefreshBlock(dev);
2602 if (dev->gcBlock < 1) {
2603 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
2608 if (dev->gcBlock > 0) {
2615 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2616 dev->nErasedBlocks, aggressive));
2618 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
2621 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
2624 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2625 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
2627 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
2628 (dev->gcBlock > 0) &&
2631 return aggressive ? gcOk : YAFFS_OK;
2635 * yaffs_BackgroundGarbageCollect()
2636 * Garbage collects. Intended to be called from a background thread.
2637 * Returns non-zero if at least half the free chunks are erased.
2639 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
2641 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2643 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
2645 yaffs_CheckGarbageCollection(dev, 1);
2646 return erasedChunks > dev->nFreeChunks/2;
2649 /*------------------------- TAGS --------------------------------*/
2651 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
2654 return (tags->chunkId == chunkInObject &&
2655 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2660 /*-------------------- Data file manipulation -----------------*/
2662 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
2663 yaffs_ExtendedTags *tags)
2665 /*Get the Tnode, then get the level 0 offset chunk offset */
2668 yaffs_ExtendedTags localTags;
2671 yaffs_Device *dev = in->myDev;
2674 /* Passed a NULL, so use our own tags space */
2678 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2681 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2684 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2690 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
2691 yaffs_ExtendedTags *tags)
2693 /* Get the Tnode, then get the level 0 offset chunk offset */
2696 yaffs_ExtendedTags localTags;
2698 yaffs_Device *dev = in->myDev;
2702 /* Passed a NULL, so use our own tags space */
2706 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2710 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2713 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2716 /* Delete the entry in the filestructure (if found) */
2718 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
2725 int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
2726 int chunkInNAND, int inScan)
2728 /* NB inScan is zero unless scanning.
2729 * For forward scanning, inScan is > 0;
2730 * for backward scanning inScan is < 0
2732 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
2736 yaffs_Device *dev = in->myDev;
2738 yaffs_ExtendedTags existingTags;
2739 yaffs_ExtendedTags newTags;
2740 unsigned existingSerial, newSerial;
2742 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2743 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2744 * If it is not during Scanning then something went wrong!
2747 T(YAFFS_TRACE_ERROR,
2749 ("yaffs tragedy:attempt to put data chunk into a non-file"
2754 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2758 tn = yaffs_AddOrFindLevel0Tnode(dev,
2759 &in->variant.fileVariant,
2766 /* Dummy insert, bail now */
2769 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2772 /* If we're scanning then we need to test for duplicates
2773 * NB This does not need to be efficient since it should only ever
2774 * happen when the power fails during a write, then only one
2775 * chunk should ever be affected.
2777 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2778 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2781 if (existingChunk > 0) {
2782 /* NB Right now existing chunk will not be real chunkId if the chunk group size > 1
2783 * thus we have to do a FindChunkInFile to get the real chunk id.
2785 * We have a duplicate now we need to decide which one to use:
2787 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2788 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2789 * YAFFS1: Get both sets of tags and compare serial numbers.
2793 /* Only do this for forward scanning */
2794 yaffs_ReadChunkWithTagsFromNAND(dev,
2798 /* Do a proper find */
2800 yaffs_FindChunkInFile(in, chunkInInode,
2804 if (existingChunk <= 0) {
2805 /*Hoosterman - how did this happen? */
2807 T(YAFFS_TRACE_ERROR,
2809 ("yaffs tragedy: existing chunk < 0 in scan"
2814 /* NB The deleted flags should be false, otherwise the chunks will
2815 * not be loaded during a scan
2819 newSerial = newTags.serialNumber;
2820 existingSerial = existingTags.serialNumber;
2824 (existingChunk <= 0 ||
2825 ((existingSerial + 1) & 3) == newSerial)) {
2826 /* Forward scanning.
2828 * Delete the old one and drop through to update the tnode
2830 yaffs_DeleteChunk(dev, existingChunk, 1,
2833 /* Backward scanning or we want to use the existing one
2835 * Delete the new one and return early so that the tnode isn't changed
2837 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2845 if (existingChunk == 0)
2848 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
2853 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
2856 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2858 if (chunkInNAND >= 0)
2859 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2862 T(YAFFS_TRACE_NANDACCESS,
2863 (TSTR("Chunk %d not found zero instead" TENDSTR),
2865 /* get sane (zero) data if you read a hole */
2866 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2872 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
2876 yaffs_ExtendedTags tags;
2877 yaffs_BlockInfo *bi;
2883 block = chunkId / dev->param.nChunksPerBlock;
2884 page = chunkId % dev->param.nChunksPerBlock;
2887 if (!yaffs_CheckChunkBit(dev, block, page))
2888 T(YAFFS_TRACE_VERIFY,
2889 (TSTR("Deleting invalid chunk %d"TENDSTR),
2892 bi = yaffs_GetBlockInfo(dev, block);
2894 yaffs2_UpdateOldestDirtySequence(dev, block, bi);
2896 T(YAFFS_TRACE_DELETION,
2897 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2899 if (!dev->param.isYaffs2 && markNAND &&
2900 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
2902 yaffs_InitialiseTags(&tags);
2904 tags.chunkDeleted = 1;
2906 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2907 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2909 dev->nUnmarkedDeletions++;
2912 /* Pull out of the management area.
2913 * If the whole block became dirty, this will kick off an erasure.
2915 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2916 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2917 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2918 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2921 yaffs_ClearChunkBit(dev, block, page);
2925 if (bi->pagesInUse == 0 &&
2926 !bi->hasShrinkHeader &&
2927 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2928 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2929 yaffs_BlockBecameDirty(dev, block);
2936 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
2937 const __u8 *buffer, int nBytes,
2940 /* Find old chunk Need to do this to get serial number
2941 * Write new one and patch into tree.
2942 * Invalidate old tags.
2946 yaffs_ExtendedTags prevTags;
2949 yaffs_ExtendedTags newTags;
2951 yaffs_Device *dev = in->myDev;
2953 yaffs_CheckGarbageCollection(dev,0);
2955 /* Get the previous chunk at this location in the file if it exists.
2956 * If it does not exist then put a zero into the tree. This creates
2957 * the tnode now, rather than later when it is harder to clean up.
2959 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2960 if(prevChunkId < 1 &&
2961 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
2964 /* Set up new tags */
2965 yaffs_InitialiseTags(&newTags);
2967 newTags.chunkId = chunkInInode;
2968 newTags.objectId = in->objectId;
2969 newTags.serialNumber =
2970 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
2971 newTags.byteCount = nBytes;
2973 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
2974 T(YAFFS_TRACE_ERROR,
2975 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
2981 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2984 if (newChunkId > 0) {
2985 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2987 if (prevChunkId > 0)
2988 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2990 yaffs_VerifyFileSanity(in);
2996 /* UpdateObjectHeader updates the header on NAND for an object.
2997 * If name is not NULL, then that new name is used.
2999 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3000 int isShrink, int shadows, yaffs_XAttrMod *xmod)
3003 yaffs_BlockInfo *bi;
3005 yaffs_Device *dev = in->myDev;
3012 yaffs_ExtendedTags newTags;
3013 yaffs_ExtendedTags oldTags;
3014 YCHAR *alias = NULL;
3016 __u8 *buffer = NULL;
3017 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3019 yaffs_ObjectHeader *oh = NULL;
3021 yaffs_strcpy(oldName, _Y("silly old name"));
3025 in == dev->rootDir || /* The rootDir should also be saved */
3028 yaffs_CheckGarbageCollection(dev,0);
3029 yaffs_CheckObjectDetailsLoaded(in);
3031 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3032 oh = (yaffs_ObjectHeader *) buffer;
3034 prevChunkId = in->hdrChunk;
3036 if (prevChunkId > 0) {
3037 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3040 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3042 memcpy(oldName, oh->name, sizeof(oh->name));
3043 memset(buffer, 0xFF, sizeof(yaffs_ObjectHeader));
3045 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3047 oh->type = in->variantType;
3048 oh->yst_mode = in->yst_mode;
3049 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3051 #ifdef CONFIG_YAFFS_WINCE
3052 oh->win_atime[0] = in->win_atime[0];
3053 oh->win_ctime[0] = in->win_ctime[0];
3054 oh->win_mtime[0] = in->win_mtime[0];
3055 oh->win_atime[1] = in->win_atime[1];
3056 oh->win_ctime[1] = in->win_ctime[1];
3057 oh->win_mtime[1] = in->win_mtime[1];
3059 oh->yst_uid = in->yst_uid;
3060 oh->yst_gid = in->yst_gid;
3061 oh->yst_atime = in->yst_atime;
3062 oh->yst_mtime = in->yst_mtime;
3063 oh->yst_ctime = in->yst_ctime;
3064 oh->yst_rdev = in->yst_rdev;
3067 oh->parentObjectId = in->parent->objectId;
3069 oh->parentObjectId = 0;
3071 if (name && *name) {
3072 memset(oh->name, 0, sizeof(oh->name));
3073 yaffs_LoadObjectHeaderFromName(dev,oh->name,name);
3074 } else if (prevChunkId > 0)
3075 memcpy(oh->name, oldName, sizeof(oh->name));
3077 memset(oh->name, 0, sizeof(oh->name));
3079 oh->isShrink = isShrink;
3081 switch (in->variantType) {
3082 case YAFFS_OBJECT_TYPE_UNKNOWN:
3083 /* Should not happen */
3085 case YAFFS_OBJECT_TYPE_FILE:
3087 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3088 || oh->parentObjectId ==
3089 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3090 fileVariant.fileSize;
3092 case YAFFS_OBJECT_TYPE_HARDLINK:
3093 oh->equivalentObjectId =
3094 in->variant.hardLinkVariant.equivalentObjectId;
3096 case YAFFS_OBJECT_TYPE_SPECIAL:
3099 case YAFFS_OBJECT_TYPE_DIRECTORY:
3102 case YAFFS_OBJECT_TYPE_SYMLINK:
3103 alias = in->variant.symLinkVariant.alias;
3105 alias = _Y("no alias");
3106 yaffs_strncpy(oh->alias,
3108 YAFFS_MAX_ALIAS_LENGTH);
3109 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3113 /* process any xattrib modifications */
3115 yaffs_ApplyXMod(dev, (char *)buffer, xmod);
3119 yaffs_InitialiseTags(&newTags);
3121 newTags.chunkId = 0;
3122 newTags.objectId = in->objectId;
3123 newTags.serialNumber = in->serial;
3125 /* Add extra info for file header */
3127 newTags.extraHeaderInfoAvailable = 1;
3128 newTags.extraParentObjectId = oh->parentObjectId;
3129 newTags.extraFileLength = oh->fileSize;
3130 newTags.extraIsShrinkHeader = oh->isShrink;
3131 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3132 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3133 newTags.extraObjectType = in->variantType;
3135 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3137 /* Create new chunk in NAND */
3139 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3140 (prevChunkId > 0) ? 1 : 0);
3142 if (newChunkId >= 0) {
3144 in->hdrChunk = newChunkId;
3146 if (prevChunkId > 0) {
3147 yaffs_DeleteChunk(dev, prevChunkId, 1,
3151 if (!yaffs_ObjectHasCachedWriteData(in))
3154 /* If this was a shrink, then mark the block that the chunk lives on */
3156 bi = yaffs_GetBlockInfo(in->myDev,
3157 newChunkId / in->myDev->param.nChunksPerBlock);
3158 bi->hasShrinkHeader = 1;
3163 retVal = newChunkId;
3168 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3173 /*------------------------ Short Operations Cache ----------------------------------------
3174 * In many situations where there is no high level buffering (eg WinCE) a lot of
3175 * reads might be short sequential reads, and a lot of writes may be short
3176 * sequential writes. eg. scanning/writing a jpeg file.
3177 * In these cases, a short read/write cache can provide a huge perfomance benefit
3178 * with dumb-as-a-rock code.
3179 * In Linux, the page cache provides read buffering aand the short op cache provides write
3182 * There are a limited number (~10) of cache chunks per device so that we don't
3183 * need a very intelligent search.
3186 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3188 yaffs_Device *dev = obj->myDev;
3190 yaffs_ChunkCache *cache;
3191 int nCaches = obj->myDev->param.nShortOpCaches;
3193 for (i = 0; i < nCaches; i++) {
3194 cache = &dev->srCache[i];
3195 if (cache->object == obj &&
3204 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3206 yaffs_Device *dev = obj->myDev;
3207 int lowest = -99; /* Stop compiler whining. */
3209 yaffs_ChunkCache *cache;
3210 int chunkWritten = 0;
3211 int nCaches = obj->myDev->param.nShortOpCaches;
3217 /* Find the dirty cache for this object with the lowest chunk id. */
3218 for (i = 0; i < nCaches; i++) {
3219 if (dev->srCache[i].object == obj &&
3220 dev->srCache[i].dirty) {
3222 || dev->srCache[i].chunkId <
3224 cache = &dev->srCache[i];
3225 lowest = cache->chunkId;
3230 if (cache && !cache->locked) {
3231 /* Write it out and free it up */
3234 yaffs_WriteChunkDataToObject(cache->object,
3240 cache->object = NULL;
3243 } while (cache && chunkWritten > 0);
3246 /* Hoosterman, disk full while writing cache out. */
3247 T(YAFFS_TRACE_ERROR,
3248 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3255 /*yaffs_FlushEntireDeviceCache(dev)
3260 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3263 int nCaches = dev->param.nShortOpCaches;
3266 /* Find a dirty object in the cache and flush it...
3267 * until there are no further dirty objects.
3271 for (i = 0; i < nCaches && !obj; i++) {
3272 if (dev->srCache[i].object &&
3273 dev->srCache[i].dirty)
3274 obj = dev->srCache[i].object;
3278 yaffs_FlushFilesChunkCache(obj);
3285 /* Grab us a cache chunk for use.
3286 * First look for an empty one.
3287 * Then look for the least recently used non-dirty one.
3288 * Then look for the least recently used dirty one...., flush and look again.
3290 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3294 if (dev->param.nShortOpCaches > 0) {
3295 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3296 if (!dev->srCache[i].object)
3297 return &dev->srCache[i];
3304 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3306 yaffs_ChunkCache *cache;
3307 yaffs_Object *theObj;
3312 if (dev->param.nShortOpCaches > 0) {
3313 /* Try find a non-dirty one... */
3315 cache = yaffs_GrabChunkCacheWorker(dev);
3318 /* They were all dirty, find the last recently used object and flush
3319 * its cache, then find again.
3320 * NB what's here is not very accurate, we actually flush the object
3321 * the last recently used page.
3324 /* With locking we can't assume we can use entry zero */
3331 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3332 if (dev->srCache[i].object &&
3333 !dev->srCache[i].locked &&
3334 (dev->srCache[i].lastUse < usage || !cache)) {
3335 usage = dev->srCache[i].lastUse;
3336 theObj = dev->srCache[i].object;
3337 cache = &dev->srCache[i];
3342 if (!cache || cache->dirty) {
3343 /* Flush and try again */
3344 yaffs_FlushFilesChunkCache(theObj);
3345 cache = yaffs_GrabChunkCacheWorker(dev);
3355 /* Find a cached chunk */
3356 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
3359 yaffs_Device *dev = obj->myDev;
3361 if (dev->param.nShortOpCaches > 0) {
3362 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3363 if (dev->srCache[i].object == obj &&
3364 dev->srCache[i].chunkId == chunkId) {
3367 return &dev->srCache[i];
3374 /* Mark the chunk for the least recently used algorithym */
3375 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
3379 if (dev->param.nShortOpCaches > 0) {
3380 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3381 /* Reset the cache usages */
3383 for (i = 1; i < dev->param.nShortOpCaches; i++)
3384 dev->srCache[i].lastUse = 0;
3391 cache->lastUse = dev->srLastUse;
3398 /* Invalidate a single cache page.
3399 * Do this when a whole page gets written,
3400 * ie the short cache for this page is no longer valid.
3402 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3404 if (object->myDev->param.nShortOpCaches > 0) {
3405 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3408 cache->object = NULL;
3412 /* Invalidate all the cache pages associated with this object
3413 * Do this whenever ther file is deleted or resized.
3415 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3418 yaffs_Device *dev = in->myDev;
3420 if (dev->param.nShortOpCaches > 0) {
3421 /* Invalidate it. */
3422 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3423 if (dev->srCache[i].object == in)
3424 dev->srCache[i].object = NULL;
3430 /*--------------------- File read/write ------------------------
3431 * Read and write have very similar structures.
3432 * In general the read/write has three parts to it
3433 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3434 * Some complete chunks
3435 * An incomplete chunk to end off with
3437 * Curve-balls: the first chunk might also be the last chunk.
3440 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
3449 yaffs_ChunkCache *cache;
3456 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
3457 /* start = offset % dev->nDataBytesPerChunk; */
3458 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3461 /* OK now check for the curveball where the start and end are in
3464 if ((start + n) < dev->nDataBytesPerChunk)
3467 nToCopy = dev->nDataBytesPerChunk - start;
3469 cache = yaffs_FindChunkCache(in, chunk);
3471 /* If the chunk is already in the cache or it is less than a whole chunk
3472 * or we're using inband tags then use the cache (if there is caching)
3473 * else bypass the cache.
3475 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3476 if (dev->param.nShortOpCaches > 0) {
3478 /* If we can't find the data in the cache, then load it up. */
3481 cache = yaffs_GrabChunkCache(in->myDev);
3483 cache->chunkId = chunk;
3486 yaffs_ReadChunkDataFromObject(in, chunk,
3492 yaffs_UseChunkCache(dev, cache, 0);
3497 memcpy(buffer, &cache->data[start], nToCopy);
3501 /* Read into the local buffer then copy..*/
3504 yaffs_GetTempBuffer(dev, __LINE__);
3505 yaffs_ReadChunkDataFromObject(in, chunk,
3508 memcpy(buffer, &localBuffer[start], nToCopy);
3511 yaffs_ReleaseTempBuffer(dev, localBuffer,
3517 /* A full chunk. Read directly into the supplied buffer. */
3518 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3532 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3533 int nBytes, int writeThrough)
3542 int startOfWrite = offset;
3543 int chunkWritten = 0;
3551 while (n > 0 && chunkWritten >= 0) {
3552 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3554 if (chunk * dev->nDataBytesPerChunk + start != offset ||
3555 start >= dev->nDataBytesPerChunk) {
3556 T(YAFFS_TRACE_ERROR, (
3557 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
3559 (int)offset, chunk, start));
3561 chunk++; /* File pos to chunk in file offset */
3563 /* OK now check for the curveball where the start and end are in
3567 if ((start + n) < dev->nDataBytesPerChunk) {
3570 /* Now folks, to calculate how many bytes to write back....
3571 * If we're overwriting and not writing to then end of file then
3572 * we need to write back as much as was there before.
3575 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
3577 if (chunkStart > in->variant.fileVariant.fileSize)
3578 nBytesRead = 0; /* Past end of file */
3580 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
3582 if (nBytesRead > dev->nDataBytesPerChunk)
3583 nBytesRead = dev->nDataBytesPerChunk;
3587 (start + n)) ? nBytesRead : (start + n);
3589 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
3593 nToCopy = dev->nDataBytesPerChunk - start;
3594 nToWriteBack = dev->nDataBytesPerChunk;
3597 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3598 /* An incomplete start or end chunk (or maybe both start and end chunk),
3599 * or we're using inband tags, so we want to use the cache buffers.
3601 if (dev->param.nShortOpCaches > 0) {
3602 yaffs_ChunkCache *cache;
3603 /* If we can't find the data in the cache, then load the cache */
3604 cache = yaffs_FindChunkCache(in, chunk);
3607 && yaffs_CheckSpaceForAllocation(dev, 1)) {
3608 cache = yaffs_GrabChunkCache(dev);
3610 cache->chunkId = chunk;
3613 yaffs_ReadChunkDataFromObject(in, chunk,
3617 !yaffs_CheckSpaceForAllocation(dev, 1)) {
3618 /* Drop the cache if it was a read cache item and
3619 * no space check has been made for it.
3625 yaffs_UseChunkCache(dev, cache, 1);
3629 memcpy(&cache->data[start], buffer,
3634 cache->nBytes = nToWriteBack;
3638 yaffs_WriteChunkDataToObject
3641 cache->data, cache->nBytes,
3647 chunkWritten = -1; /* fail the write */
3650 /* An incomplete start or end chunk (or maybe both start and end chunk)
3651 * Read into the local buffer then copy, then copy over and write back.
3655 yaffs_GetTempBuffer(dev, __LINE__);
3657 yaffs_ReadChunkDataFromObject(in, chunk,
3662 memcpy(&localBuffer[start], buffer, nToCopy);
3665 yaffs_WriteChunkDataToObject(in, chunk,
3670 yaffs_ReleaseTempBuffer(dev, localBuffer,
3676 /* A full chunk. Write directly from the supplied buffer. */
3681 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3682 dev->nDataBytesPerChunk,
3685 /* Since we've overwritten the cached data, we better invalidate it. */
3686 yaffs_InvalidateChunkCache(in, chunk);
3689 if (chunkWritten >= 0) {
3698 /* Update file object */
3700 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3701 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3708 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3709 int nBytes, int writeThrough)
3711 yaffs2_HandleHole(in,offset);
3712 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
3717 /* ---------------------- File resizing stuff ------------------ */
3719 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
3722 yaffs_Device *dev = in->myDev;
3723 int oldFileSize = in->variant.fileVariant.fileSize;
3725 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
3727 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
3728 dev->nDataBytesPerChunk;
3732 /* Delete backwards so that we don't end up with holes if
3733 * power is lost part-way through the operation.
3735 for (i = lastDel; i >= startDel; i--) {
3736 /* NB this could be optimised somewhat,
3737 * eg. could retrieve the tags and write them without
3738 * using yaffs_DeleteChunk
3741 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3744 (dev->internalStartBlock * dev->param.nChunksPerBlock)
3746 ((dev->internalEndBlock +
3747 1) * dev->param.nChunksPerBlock)) {
3748 T(YAFFS_TRACE_ALWAYS,
3749 (TSTR("Found daft chunkId %d for %d" TENDSTR),
3753 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3761 void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
3764 __u32 newSizeOfPartialChunk;
3765 yaffs_Device *dev = obj->myDev;
3767 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
3769 yaffs_PruneResizedChunks(obj, newSize);
3771 if (newSizeOfPartialChunk != 0) {
3772 int lastChunk = 1 + newFullChunks;
3773 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3775 /* Got to read and rewrite the last chunk with its new size and zero pad */
3776 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
3777 memset(localBuffer + newSizeOfPartialChunk, 0,
3778 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
3780 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
3781 newSizeOfPartialChunk, 1);
3783 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3786 obj->variant.fileVariant.fileSize = newSize;
3788 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
3792 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
3794 yaffs_Device *dev = in->myDev;
3795 int oldFileSize = in->variant.fileVariant.fileSize;
3797 yaffs_FlushFilesChunkCache(in);
3798 yaffs_InvalidateWholeChunkCache(in);
3800 yaffs_CheckGarbageCollection(dev,0);
3802 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3805 if (newSize == oldFileSize)
3808 if(newSize > oldFileSize){
3809 yaffs2_HandleHole(in,newSize);
3810 in->variant.fileVariant.fileSize = newSize;
3812 /* newSize < oldFileSize */
3813 yaffs_ResizeDown(in, newSize);
3816 /* Write a new object header to reflect the resize.
3817 * show we've shrunk the file, if need be
3818 * Do this only if the file is not in the deleted directories
3819 * and is not shadowed.
3823 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3824 in->parent->objectId != YAFFS_OBJECTID_DELETED)
3825 yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL);
3831 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3833 YCHAR *alias = NULL;
3834 obj = yaffs_GetEquivalentObject(obj);
3836 switch (obj->variantType) {
3837 case YAFFS_OBJECT_TYPE_FILE:
3838 return obj->variant.fileVariant.fileSize;
3839 case YAFFS_OBJECT_TYPE_SYMLINK:
3840 alias = obj->variant.symLinkVariant.alias;
3843 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
3851 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
3855 yaffs_FlushFilesChunkCache(in);
3856 if(dataSync) /* Only sync data */
3860 #ifdef CONFIG_YAFFS_WINCE
3861 yfsd_WinFileTimeNow(in->win_mtime);
3864 in->yst_mtime = Y_CURRENT_TIME;
3869 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL) >=
3870 0) ? YAFFS_OK : YAFFS_FAIL;
3880 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3883 /* First off, invalidate the file's data in the cache, without flushing. */
3884 yaffs_InvalidateWholeChunkCache(in);
3886 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3887 /* Move to the unlinked directory so we have a record that it was deleted. */
3888 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
3892 yaffs_RemoveObjectFromDirectory(in);
3893 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
3896 yaffs_FreeObject(in);
3901 /* yaffs_DeleteFile deletes the whole file data
3902 * and the inode associated with the file.
3903 * It does not delete the links associated with the file.
3905 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
3909 int immediateDeletion = 0;
3910 yaffs_Device *dev = in->myDev;
3913 immediateDeletion = 1;
3915 if (immediateDeletion) {
3917 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3918 _Y("deleted"), 0, 0);
3919 T(YAFFS_TRACE_TRACING,
3920 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3923 in->myDev->nDeletedFiles++;
3924 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3925 yaffs_ResizeFile(in, 0);
3926 yaffs_SoftDeleteFile(in);
3929 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3930 _Y("unlinked"), 0, 0);
3937 int yaffs_DeleteFile(yaffs_Object *in)
3939 int retVal = YAFFS_OK;
3940 int deleted; /* Need to cache value on stack if in is freed */
3941 yaffs_Device *dev = in->myDev;
3943 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3944 yaffs_ResizeFile(in, 0);
3946 if (in->nDataChunks > 0) {
3947 /* Use soft deletion if there is data in the file.
3948 * That won't be the case if it has been resized to zero.
3951 retVal = yaffs_UnlinkFileIfNeeded(in);
3953 deleted = in->deleted;
3955 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3958 in->myDev->nDeletedFiles++;
3959 yaffs_SoftDeleteFile(in);
3961 return deleted ? YAFFS_OK : YAFFS_FAIL;
3963 /* The file has no data chunks so we toss it immediately */
3964 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3965 in->variant.fileVariant.top = NULL;
3966 yaffs_DoGenericObjectDeletion(in);
3972 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
3974 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3975 !(ylist_empty(&obj->variant.directoryVariant.children));
3978 static int yaffs_DeleteDirectory(yaffs_Object *obj)
3980 /* First check that the directory is empty. */
3981 if (yaffs_IsNonEmptyDirectory(obj))
3984 return yaffs_DoGenericObjectDeletion(obj);
3987 static int yaffs_DeleteSymLink(yaffs_Object *in)
3989 if(in->variant.symLinkVariant.alias)
3990 YFREE(in->variant.symLinkVariant.alias);
3991 in->variant.symLinkVariant.alias=NULL;
3993 return yaffs_DoGenericObjectDeletion(in);
3996 static int yaffs_DeleteHardLink(yaffs_Object *in)
3998 /* remove this hardlink from the list assocaited with the equivalent
4001 ylist_del_init(&in->hardLinks);
4002 return yaffs_DoGenericObjectDeletion(in);
4005 int yaffs_DeleteObject(yaffs_Object *obj)
4008 switch (obj->variantType) {
4009 case YAFFS_OBJECT_TYPE_FILE:
4010 retVal = yaffs_DeleteFile(obj);
4012 case YAFFS_OBJECT_TYPE_DIRECTORY:
4013 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
4014 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
4015 ylist_del_init(&obj->variant.directoryVariant.dirty);
4017 return yaffs_DeleteDirectory(obj);
4019 case YAFFS_OBJECT_TYPE_SYMLINK:
4020 retVal = yaffs_DeleteSymLink(obj);
4022 case YAFFS_OBJECT_TYPE_HARDLINK:
4023 retVal = yaffs_DeleteHardLink(obj);
4025 case YAFFS_OBJECT_TYPE_SPECIAL:
4026 retVal = yaffs_DoGenericObjectDeletion(obj);
4028 case YAFFS_OBJECT_TYPE_UNKNOWN:
4030 break; /* should not happen. */
4036 static int yaffs_UnlinkWorker(yaffs_Object *obj)
4039 int immediateDeletion = 0;
4042 immediateDeletion = 1;
4045 yaffs_UpdateParent(obj->parent);
4047 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4048 return yaffs_DeleteHardLink(obj);
4049 } else if (!ylist_empty(&obj->hardLinks)) {
4050 /* Curve ball: We're unlinking an object that has a hardlink.
4052 * This problem arises because we are not strictly following
4053 * The Linux link/inode model.
4055 * We can't really delete the object.
4056 * Instead, we do the following:
4057 * - Select a hardlink.
4058 * - Unhook it from the hard links
4059 * - Move it from its parent directory (so that the rename can work)
4060 * - Rename the object to the hardlink's name.
4061 * - Delete the hardlink
4065 yaffs_Object *parent;
4067 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4069 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4071 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4072 parent = hl->parent;
4074 ylist_del_init(&hl->hardLinks);
4076 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
4078 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
4080 if (retVal == YAFFS_OK)
4081 retVal = yaffs_DoGenericObjectDeletion(hl);
4085 } else if (immediateDeletion) {
4086 switch (obj->variantType) {
4087 case YAFFS_OBJECT_TYPE_FILE:
4088 return yaffs_DeleteFile(obj);
4090 case YAFFS_OBJECT_TYPE_DIRECTORY:
4091 ylist_del_init(&obj->variant.directoryVariant.dirty);
4092 return yaffs_DeleteDirectory(obj);
4094 case YAFFS_OBJECT_TYPE_SYMLINK:
4095 return yaffs_DeleteSymLink(obj);
4097 case YAFFS_OBJECT_TYPE_SPECIAL:
4098 return yaffs_DoGenericObjectDeletion(obj);
4100 case YAFFS_OBJECT_TYPE_HARDLINK:
4101 case YAFFS_OBJECT_TYPE_UNKNOWN:
4105 } else if(yaffs_IsNonEmptyDirectory(obj))
4108 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
4109 _Y("unlinked"), 0, 0);
4113 static int yaffs_UnlinkObject(yaffs_Object *obj)
4116 if (obj && obj->unlinkAllowed)
4117 return yaffs_UnlinkWorker(obj);
4122 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
4126 obj = yaffs_FindObjectByName(dir, name);
4127 return yaffs_UnlinkObject(obj);
4130 /*----------------------- Initialisation Scanning ---------------------- */
4132 void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
4133 int backwardScanning)
4137 if (!backwardScanning) {
4138 /* Handle YAFFS1 forward scanning case
4139 * For YAFFS1 we always do the deletion
4143 /* Handle YAFFS2 case (backward scanning)
4144 * If the shadowed object exists then ignore.
4146 obj = yaffs_FindObjectByNumber(dev, objId);
4151 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4152 * We put it in unlinked dir to be cleaned up after the scanning
4155 yaffs_FindOrCreateObjectByNumber(dev, objId,
4156 YAFFS_OBJECT_TYPE_FILE);
4159 obj->isShadowed = 1;
4160 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4161 obj->variant.fileVariant.shrinkSize = 0;
4162 obj->valid = 1; /* So that we don't read any other info for this file */
4167 void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4174 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4176 in = yaffs_FindObjectByNumber(dev,
4177 hl->variant.hardLinkVariant.
4178 equivalentObjectId);
4181 /* Add the hardlink pointers */
4182 hl->variant.hardLinkVariant.equivalentObject = in;
4183 ylist_add(&hl->hardLinks, &in->hardLinks);
4185 /* Todo Need to report/handle this better.
4186 * Got a problem... hardlink to a non-existant object
4188 hl->variant.hardLinkVariant.equivalentObject = NULL;
4189 YINIT_LIST_HEAD(&hl->hardLinks);
4196 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
4199 * Sort out state of unlinked and deleted objects after scanning.
4201 struct ylist_head *i;
4202 struct ylist_head *n;
4208 /* Soft delete all the unlinked files */
4209 ylist_for_each_safe(i, n,
4210 &dev->unlinkedDir->variant.directoryVariant.children) {
4212 l = ylist_entry(i, yaffs_Object, siblings);
4213 yaffs_DeleteObject(l);
4217 ylist_for_each_safe(i, n,
4218 &dev->deletedDir->variant.directoryVariant.children) {
4220 l = ylist_entry(i, yaffs_Object, siblings);
4221 yaffs_DeleteObject(l);
4228 * This code iterates through all the objects making sure that they are rooted.
4229 * Any unrooted objects are re-rooted in lost+found.
4230 * An object needs to be in one of:
4231 * - Directly under deleted, unlinked
4232 * - Directly or indirectly under root.
4235 * This code assumes that we don't ever change the current relationships between
4237 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
4238 * lostNfound->parent == rootDir
4240 * This fixes the problem where directories might have inadvertently been deleted
4241 * leaving the object "hanging" without being rooted in the directory tree.
4244 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
4246 return (obj == dev->deletedDir ||
4247 obj == dev->unlinkedDir||
4248 obj == dev->rootDir);
4251 static void yaffs_FixHangingObjects(yaffs_Device *dev)
4254 yaffs_Object *parent;
4256 struct ylist_head *lh;
4257 struct ylist_head *n;
4264 /* Iterate through the objects in each hash entry,
4265 * looking at each object.
4266 * Make sure it is rooted.
4269 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
4270 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
4272 obj = ylist_entry(lh, yaffs_Object, hashLink);
4273 parent= obj->parent;
4275 if(yaffs_HasNULLParent(dev,obj)){
4276 /* These directories are not hanging */
4279 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4281 else if(yaffs_HasNULLParent(dev,parent))
4285 * Need to follow the parent chain to see if it is hanging.
4290 while(parent != dev->rootDir &&
4292 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
4294 parent = parent->parent;
4297 if(parent != dev->rootDir)
4302 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
4304 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
4313 * Delete directory contents for cleaning up lost and found.
4315 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
4318 struct ylist_head *lh;
4319 struct ylist_head *n;
4321 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4324 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
4326 obj = ylist_entry(lh, yaffs_Object, siblings);
4327 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
4328 yaffs_DeleteDirectoryContents(obj);
4331 (TSTR("Deleting lost_found object %d" TENDSTR),
4334 /* Need to use UnlinkObject since Delete would not handle
4335 * hardlinked objects correctly.
4337 yaffs_UnlinkObject(obj);
4343 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
4345 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
4348 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4351 yaffs_ObjectHeader *oh;
4353 yaffs_ExtendedTags tags;
4355 int alloc_failed = 0;
4363 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
4365 in->lazyLoaded ? "not yet" : "already"));
4368 if (in->lazyLoaded && in->hdrChunk > 0) {
4370 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4372 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
4373 oh = (yaffs_ObjectHeader *) chunkData;
4375 in->yst_mode = oh->yst_mode;
4376 #ifdef CONFIG_YAFFS_WINCE
4377 in->win_atime[0] = oh->win_atime[0];
4378 in->win_ctime[0] = oh->win_ctime[0];
4379 in->win_mtime[0] = oh->win_mtime[0];
4380 in->win_atime[1] = oh->win_atime[1];
4381 in->win_ctime[1] = oh->win_ctime[1];
4382 in->win_mtime[1] = oh->win_mtime[1];
4384 in->yst_uid = oh->yst_uid;
4385 in->yst_gid = oh->yst_gid;
4386 in->yst_atime = oh->yst_atime;
4387 in->yst_mtime = oh->yst_mtime;
4388 in->yst_ctime = oh->yst_ctime;
4389 in->yst_rdev = oh->yst_rdev;
4392 yaffs_SetObjectNameFromOH(in, oh);
4394 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
4395 in->variant.symLinkVariant.alias =
4396 yaffs_CloneString(oh->alias);
4397 if (!in->variant.symLinkVariant.alias)
4398 alloc_failed = 1; /* Not returned to caller */
4401 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4405 /*------------------------------ Directory Functions ----------------------------- */
4408 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
4409 * link (ie. name) is created or deleted in the directory.
4412 * create dir/a : update dir's mtime/ctime
4413 * rm dir/a: update dir's mtime/ctime
4414 * modify dir/a: don't update dir's mtimme/ctime
4416 * This can be handled immediately or defered. Defering helps reduce the number
4417 * of updates when many files in a directory are changed within a brief period.
4419 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
4420 * called periodically.
4423 static void yaffs_UpdateParent(yaffs_Object *obj)
4428 #ifndef CONFIG_YAFFS_WINCE
4432 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
4433 if(dev->param.deferDirectoryUpdate){
4434 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
4436 if(ylist_empty(link)){
4437 ylist_add(link,&dev->dirtyDirectories);
4438 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
4442 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4446 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
4448 struct ylist_head *link;
4450 yaffs_DirectoryStructure *dS;
4451 yaffs_ObjectVariant *oV;
4453 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
4455 while(!ylist_empty(&dev->dirtyDirectories)){
4456 link = dev->dirtyDirectories.next;
4457 ylist_del_init(link);
4459 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
4460 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
4461 obj = ylist_entry(oV,yaffs_Object,variant);
4463 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
4466 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4470 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4472 yaffs_Device *dev = obj->myDev;
4473 yaffs_Object *parent;
4475 yaffs_VerifyObjectInDirectory(obj);
4476 parent = obj->parent;
4478 yaffs_VerifyDirectory(parent);
4480 if (dev && dev->param.removeObjectCallback)
4481 dev->param.removeObjectCallback(obj);
4484 ylist_del_init(&obj->siblings);
4487 yaffs_VerifyDirectory(parent);
4490 void yaffs_AddObjectToDirectory(yaffs_Object *directory,
4494 T(YAFFS_TRACE_ALWAYS,
4496 ("tragedy: Trying to add an object to a null pointer directory"
4501 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4502 T(YAFFS_TRACE_ALWAYS,
4504 ("tragedy: Trying to add an object to a non-directory"
4509 if (obj->siblings.prev == NULL) {
4510 /* Not initialised */
4515 yaffs_VerifyDirectory(directory);
4517 yaffs_RemoveObjectFromDirectory(obj);
4521 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
4522 obj->parent = directory;
4524 if (directory == obj->myDev->unlinkedDir
4525 || directory == obj->myDev->deletedDir) {
4527 obj->myDev->nUnlinkedFiles++;
4528 obj->renameAllowed = 0;
4531 yaffs_VerifyDirectory(directory);
4532 yaffs_VerifyObjectInDirectory(obj);
4535 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
4540 struct ylist_head *i;
4541 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4549 T(YAFFS_TRACE_ALWAYS,
4551 ("tragedy: yaffs_FindObjectByName: null pointer directory"
4556 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4557 T(YAFFS_TRACE_ALWAYS,
4559 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4563 sum = yaffs_CalcNameSum(name);
4565 ylist_for_each(i, &directory->variant.directoryVariant.children) {
4567 l = ylist_entry(i, yaffs_Object, siblings);
4569 if (l->parent != directory)
4572 yaffs_CheckObjectDetailsLoaded(l);
4574 /* Special case for lost-n-found */
4575 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4576 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
4578 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
4579 /* LostnFound chunk called Objxxx
4582 yaffs_GetObjectName(l, buffer,
4583 YAFFS_MAX_NAME_LENGTH + 1);
4584 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
4595 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
4596 int (*fn) (yaffs_Object *))
4598 struct ylist_head *i;
4602 T(YAFFS_TRACE_ALWAYS,
4604 ("tragedy: yaffs_FindObjectByName: null pointer directory"
4609 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4610 T(YAFFS_TRACE_ALWAYS,
4612 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4617 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
4619 l = ylist_entry(i, yaffs_Object, siblings);
4630 /* GetEquivalentObject dereferences any hard links to get to the
4634 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4636 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4637 /* We want the object id of the equivalent object, not this one */
4638 obj = obj->variant.hardLinkVariant.equivalentObject;
4639 yaffs_CheckObjectDetailsLoaded(obj);
4645 * A note or two on object names.
4646 * * If the object name is missing, we then make one up in the form objnnn
4648 * * ASCII names are stored in the object header's name field from byte zero
4649 * * Unicode names are historically stored starting from byte zero.
4651 * Then there are automatic Unicode names...
4652 * The purpose of these is to save names in a way that can be read as
4653 * ASCII or Unicode names as appropriate, thus allowing a Unicode and ASCII
4654 * system to share files.
4656 * These automatic unicode are stored slightly differently...
4657 * - If the name can fit in the ASCII character space then they are saved as
4658 * ascii names as per above.
4659 * - If the name needs Unicode then the name is saved in Unicode
4660 * starting at oh->name[1].
4663 static void yaffs_FixNullName(yaffs_Object * obj,YCHAR * name, int buffSize)
4665 /* Create an object name if we could not find one. */
4666 if(yaffs_strnlen(name,YAFFS_MAX_NAME_LENGTH) == 0){
4668 YCHAR numString[20];
4669 YCHAR *x = &numString[19];
4670 unsigned v = obj->objectId;
4674 *x = '0' + (v % 10);
4677 /* make up a name */
4678 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
4679 yaffs_strcat(locName,x);
4680 yaffs_strncpy(name, locName, buffSize - 1);
4684 static void yaffs_LoadNameFromObjectHeader(yaffs_Device *dev,YCHAR *name, const YCHAR *ohName, int bufferSize)
4686 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4687 if(dev->param.autoUnicode){
4689 /* It is an ASCII name, so do an ASCII to unicode conversion */
4690 const char *asciiOhName = (const char *)ohName;
4691 int n = bufferSize - 1;
4692 while(n > 0 && *asciiOhName){
4693 *name = *asciiOhName;
4699 yaffs_strncpy(name,ohName+1, bufferSize -1);
4702 yaffs_strncpy(name, ohName, bufferSize - 1);
4706 static void yaffs_LoadObjectHeaderFromName(yaffs_Device *dev, YCHAR *ohName, const YCHAR *name)
4708 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4713 if(dev->param.autoUnicode){
4718 /* Figure out if the name will fit in ascii character set */
4719 while(isAscii && *w){
4726 /* It is an ASCII name, so do a unicode to ascii conversion */
4727 char *asciiOhName = (char *)ohName;
4728 int n = YAFFS_MAX_NAME_LENGTH - 1;
4729 while(n > 0 && *name){
4730 *asciiOhName= *name;
4736 /* It is a unicode name, so save starting at the second YCHAR */
4738 yaffs_strncpy(ohName+1,name, YAFFS_MAX_NAME_LENGTH -2);
4743 yaffs_strncpy(ohName,name, YAFFS_MAX_NAME_LENGTH - 1);
4747 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
4749 memset(name, 0, buffSize * sizeof(YCHAR));
4751 yaffs_CheckObjectDetailsLoaded(obj);
4753 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4754 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
4756 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4757 else if (obj->shortName[0]) {
4758 yaffs_strcpy(name, obj->shortName);
4761 else if(obj->hdrChunk > 0) {
4763 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
4765 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
4767 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
4769 if (obj->hdrChunk > 0) {
4770 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
4771 obj->hdrChunk, buffer,
4774 yaffs_LoadNameFromObjectHeader(obj->myDev,name,oh->name,buffSize);
4776 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
4779 yaffs_FixNullName(obj,name,buffSize);
4781 return yaffs_strnlen(name,YAFFS_MAX_NAME_LENGTH);
4785 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4787 /* Dereference any hard linking */
4788 obj = yaffs_GetEquivalentObject(obj);
4790 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4791 return obj->variant.fileVariant.fileSize;
4792 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
4793 if(!obj->variant.symLinkVariant.alias)
4795 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
4797 /* Only a directory should drop through to here */
4798 return obj->myDev->nDataBytesPerChunk;
4802 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4805 struct ylist_head *i;
4808 count++; /* the object itself */
4810 ylist_for_each(i, &obj->hardLinks)
4811 count++; /* add the hard links; */
4816 int yaffs_GetObjectInode(yaffs_Object *obj)
4818 obj = yaffs_GetEquivalentObject(obj);
4820 return obj->objectId;
4823 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4825 obj = yaffs_GetEquivalentObject(obj);
4827 switch (obj->variantType) {
4828 case YAFFS_OBJECT_TYPE_FILE:
4831 case YAFFS_OBJECT_TYPE_DIRECTORY:
4834 case YAFFS_OBJECT_TYPE_SYMLINK:
4837 case YAFFS_OBJECT_TYPE_HARDLINK:
4840 case YAFFS_OBJECT_TYPE_SPECIAL:
4841 if (S_ISFIFO(obj->yst_mode))
4843 if (S_ISCHR(obj->yst_mode))
4845 if (S_ISBLK(obj->yst_mode))
4847 if (S_ISSOCK(obj->yst_mode))
4855 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4857 obj = yaffs_GetEquivalentObject(obj);
4858 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4859 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4861 return yaffs_CloneString(_Y(""));
4864 #ifndef CONFIG_YAFFS_WINCE
4866 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4868 unsigned int valid = attr->ia_valid;
4870 if (valid & ATTR_MODE)
4871 obj->yst_mode = attr->ia_mode;
4872 if (valid & ATTR_UID)
4873 obj->yst_uid = attr->ia_uid;
4874 if (valid & ATTR_GID)
4875 obj->yst_gid = attr->ia_gid;
4877 if (valid & ATTR_ATIME)
4878 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
4879 if (valid & ATTR_CTIME)
4880 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
4881 if (valid & ATTR_MTIME)
4882 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
4884 if (valid & ATTR_SIZE)
4885 yaffs_ResizeFile(obj, attr->ia_size);
4887 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0, NULL);
4892 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4894 unsigned int valid = 0;
4896 attr->ia_mode = obj->yst_mode;
4898 attr->ia_uid = obj->yst_uid;
4900 attr->ia_gid = obj->yst_gid;
4903 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
4904 valid |= ATTR_ATIME;
4905 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
4906 valid |= ATTR_CTIME;
4907 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
4908 valid |= ATTR_MTIME;
4910 attr->ia_size = yaffs_GetFileSize(obj);
4913 attr->ia_valid = valid;
4921 static int yaffs_DoXMod(yaffs_Object *obj, int set, const YCHAR *name, const void *value, int size, int flags)
4923 yaffs_XAttrMod xmod;
4932 xmod.result = -ENOSPC;
4934 result = yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, &xmod);
4942 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod)
4945 int x_offs = sizeof(yaffs_ObjectHeader);
4946 int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4948 char * x_buffer = buffer + x_offs;
4951 retval = nval_set(x_buffer, x_size, xmod->name, xmod->data, xmod->size, xmod->flags);
4953 retval = nval_del(x_buffer, x_size, xmod->name);
4955 xmod->result = retval;
4960 static int yaffs_DoXFetch(yaffs_Object *obj, const YCHAR *name, void *value, int size)
4962 char *buffer = NULL;
4964 yaffs_ExtendedTags tags;
4965 yaffs_Device *dev = obj->myDev;
4966 int x_offs = sizeof(yaffs_ObjectHeader);
4967 int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4973 if(obj->hdrChunk < 1)
4976 buffer = yaffs_GetTempBuffer(dev, __LINE__);
4980 result = yaffs_ReadChunkWithTagsFromNAND(dev,obj->hdrChunk, buffer, &tags);
4982 if(result != YAFFS_OK)
4985 x_buffer = buffer + x_offs;
4988 retval = nval_get(x_buffer, x_size, name, value, size);
4990 retval = nval_list(x_buffer, x_size, value,size);
4992 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
4996 int yaffs_SetXAttribute(yaffs_Object *obj, const YCHAR *name, const void * value, int size, int flags)
4998 return yaffs_DoXMod(obj, 1, name, value, size, flags);
5001 int yaffs_RemoveXAttribute(yaffs_Object *obj, const YCHAR *name)
5003 return yaffs_DoXMod(obj, 0, name, NULL, 0, 0);
5006 int yaffs_GetXAttribute(yaffs_Object *obj, const YCHAR *name, void *value, int size)
5008 return yaffs_DoXFetch(obj, name, value, size);
5011 int yaffs_ListXAttributes(yaffs_Object *obj, char *buffer, int size)
5013 return yaffs_DoXFetch(obj, NULL, buffer,size);
5019 int yaffs_DumpObject(yaffs_Object *obj)
5023 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
5025 T(YAFFS_TRACE_ALWAYS,
5027 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5028 " chunk %d type %d size %d\n"
5029 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5030 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
5031 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5037 /*---------------------------- Initialisation code -------------------------------------- */
5039 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
5042 /* Common functions, gotta have */
5043 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
5046 #ifdef CONFIG_YAFFS_YAFFS2
5048 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5049 if (dev->param.writeChunkWithTagsToNAND &&
5050 dev->param.readChunkWithTagsFromNAND &&
5051 !dev->param.writeChunkToNAND &&
5052 !dev->param.readChunkFromNAND &&
5053 dev->param.markNANDBlockBad &&
5054 dev->param.queryNANDBlock)
5058 /* Can use the "spare" style interface for yaffs1 */
5059 if (!dev->param.isYaffs2 &&
5060 !dev->param.writeChunkWithTagsToNAND &&
5061 !dev->param.readChunkWithTagsFromNAND &&
5062 dev->param.writeChunkToNAND &&
5063 dev->param.readChunkFromNAND &&
5064 !dev->param.markNANDBlockBad &&
5065 !dev->param.queryNANDBlock)
5072 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
5074 /* Initialise the unlinked, deleted, root and lost and found directories */
5076 dev->lostNFoundDir = dev->rootDir = NULL;
5077 dev->unlinkedDir = dev->deletedDir = NULL;
5080 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5083 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5086 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5087 YAFFS_ROOT_MODE | S_IFDIR);
5088 dev->lostNFoundDir =
5089 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5090 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5092 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
5093 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5100 int yaffs_GutsInitialise(yaffs_Device *dev)
5102 int init_failed = 0;
5106 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5108 /* Check stuff that must be set */
5111 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5115 dev->internalStartBlock = dev->param.startBlock;
5116 dev->internalEndBlock = dev->param.endBlock;
5117 dev->blockOffset = 0;
5118 dev->chunkOffset = 0;
5119 dev->nFreeChunks = 0;
5123 if (dev->param.startBlock == 0) {
5124 dev->internalStartBlock = dev->param.startBlock + 1;
5125 dev->internalEndBlock = dev->param.endBlock + 1;
5126 dev->blockOffset = 1;
5127 dev->chunkOffset = dev->param.nChunksPerBlock;
5130 /* Check geometry parameters. */
5132 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
5133 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
5134 (dev->param.inbandTags && !dev->param.isYaffs2) ||
5135 dev->param.nChunksPerBlock < 2 ||
5136 dev->param.nReservedBlocks < 2 ||
5137 dev->internalStartBlock <= 0 ||
5138 dev->internalEndBlock <= 0 ||
5139 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
5140 T(YAFFS_TRACE_ALWAYS,
5142 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
5143 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
5147 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5148 T(YAFFS_TRACE_ALWAYS,
5149 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5153 /* Sort out space for inband tags, if required */
5154 if (dev->param.inbandTags)
5155 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
5157 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
5159 /* Got the right mix of functions? */
5160 if (!yaffs_CheckDevFunctions(dev)) {
5161 /* Function missing */
5162 T(YAFFS_TRACE_ALWAYS,
5164 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5169 /* This is really a compilation check. */
5170 if (!yaffs_CheckStructures()) {
5171 T(YAFFS_TRACE_ALWAYS,
5172 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5176 if (dev->isMounted) {
5177 T(YAFFS_TRACE_ALWAYS,
5178 (TSTR("yaffs: device already mounted\n" TENDSTR)));
5182 /* Finished with most checks. One or two more checks happen later on too. */
5186 /* OK now calculate a few things for the device */
5189 * Calculate all the chunk size manipulation numbers:
5191 x = dev->nDataBytesPerChunk;
5192 /* We always use dev->chunkShift and dev->chunkDiv */
5193 dev->chunkShift = Shifts(x);
5194 x >>= dev->chunkShift;
5196 /* We only use chunk mask if chunkDiv is 1 */
5197 dev->chunkMask = (1<<dev->chunkShift) - 1;
5200 * Calculate chunkGroupBits.
5201 * We need to find the next power of 2 > than internalEndBlock
5204 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
5208 /* Set up tnode width if wide tnodes are enabled. */
5209 if (!dev->param.wideTnodesDisabled) {
5210 /* bits must be even so that we end up with 32-bit words */
5214 dev->tnodeWidth = 16;
5216 dev->tnodeWidth = bits;
5218 dev->tnodeWidth = 16;
5220 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5222 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5223 * so if the bitwidth of the
5224 * chunk range we're using is greater than 16 we need
5225 * to figure out chunk shift and chunkGroupSize
5228 if (bits <= dev->tnodeWidth)
5229 dev->chunkGroupBits = 0;
5231 dev->chunkGroupBits = bits - dev->tnodeWidth;
5233 dev->tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
5234 if(dev->tnodeSize < sizeof(yaffs_Tnode))
5235 dev->tnodeSize = sizeof(yaffs_Tnode);
5237 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5239 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
5240 /* We have a problem because the soft delete won't work if
5241 * the chunk group size > chunks per block.
5242 * This can be remedied by using larger "virtual blocks".
5244 T(YAFFS_TRACE_ALWAYS,
5245 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5250 /* OK, we've finished verifying the device, lets continue with initialisation */
5252 /* More device initialisation */
5254 dev->passiveGCs = 0;
5255 dev->oldestDirtyGCs = 0;
5256 dev->backgroundGCs = 0;
5257 dev->gcBlockFinder = 0;
5258 dev->bufferedBlock = -1;
5259 dev->doingBufferedBlockRewrite = 0;
5260 dev->nDeletedFiles = 0;
5261 dev->nBackgroundDeletions = 0;
5262 dev->nUnlinkedFiles = 0;
5264 dev->eccUnfixed = 0;
5265 dev->tagsEccFixed = 0;
5266 dev->tagsEccUnfixed = 0;
5267 dev->nErasureFailures = 0;
5268 dev->nErasedBlocks = 0;
5270 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
5271 YINIT_LIST_HEAD(&dev->dirtyDirectories);
5272 dev->oldestDirtySequence = 0;
5273 dev->oldestDirtyBlock = 0;
5275 /* Initialise temporary buffers and caches. */
5276 if (!yaffs_InitialiseTempBuffers(dev))
5279 dev->srCache = NULL;
5280 dev->gcCleanupList = NULL;
5284 dev->param.nShortOpCaches > 0) {
5287 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
5289 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
5290 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5292 dev->srCache = YMALLOC(srCacheBytes);
5294 buf = (__u8 *) dev->srCache;
5297 memset(dev->srCache, 0, srCacheBytes);
5299 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
5300 dev->srCache[i].object = NULL;
5301 dev->srCache[i].lastUse = 0;
5302 dev->srCache[i].dirty = 0;
5303 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
5314 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
5315 if (!dev->gcCleanupList)
5319 if (dev->param.isYaffs2)
5320 dev->param.useHeaderFileSize = 1;
5322 if (!init_failed && !yaffs_InitialiseBlocks(dev))
5325 yaffs_InitialiseTnodesAndObjects(dev);
5327 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5332 /* Now scan the flash. */
5333 if (dev->param.isYaffs2) {
5334 if (yaffs2_CheckpointRestore(dev)) {
5335 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
5336 T(YAFFS_TRACE_ALWAYS,
5337 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
5340 /* Clean up the mess caused by an aborted checkpoint load
5341 * and scan backwards.
5343 yaffs_DeinitialiseBlocks(dev);
5345 yaffs_DeinitialiseTnodesAndObjects(dev);
5347 dev->nErasedBlocks = 0;
5348 dev->nFreeChunks = 0;
5349 dev->allocationBlock = -1;
5350 dev->allocationPage = -1;
5351 dev->nDeletedFiles = 0;
5352 dev->nUnlinkedFiles = 0;
5353 dev->nBackgroundDeletions = 0;
5355 if (!init_failed && !yaffs_InitialiseBlocks(dev))
5358 yaffs_InitialiseTnodesAndObjects(dev);
5360 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5363 if (!init_failed && !yaffs2_ScanBackwards(dev))
5366 } else if (!yaffs1_Scan(dev))
5369 yaffs_StripDeletedObjects(dev);
5370 yaffs_FixHangingObjects(dev);
5371 if(dev->param.emptyLostAndFound)
5372 yaffs_EmptyLostAndFound(dev);
5376 /* Clean up the mess */
5377 T(YAFFS_TRACE_TRACING,
5378 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
5380 yaffs_Deinitialise(dev);
5384 /* Zero out stats */
5385 dev->nPageReads = 0;
5386 dev->nPageWrites = 0;
5387 dev->nBlockErasures = 0;
5389 dev->nRetriedWrites = 0;
5391 dev->nRetiredBlocks = 0;
5393 yaffs_VerifyFreeChunks(dev);
5394 yaffs_VerifyBlocks(dev);
5396 /* Clean up any aborted checkpoint data */
5397 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
5398 yaffs2_InvalidateCheckpoint(dev);
5400 T(YAFFS_TRACE_TRACING,
5401 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5406 void yaffs_Deinitialise(yaffs_Device *dev)
5408 if (dev->isMounted) {
5411 yaffs_DeinitialiseBlocks(dev);
5412 yaffs_DeinitialiseTnodesAndObjects(dev);
5413 if (dev->param.nShortOpCaches > 0 &&
5416 for (i = 0; i < dev->param.nShortOpCaches; i++) {
5417 if (dev->srCache[i].data)
5418 YFREE(dev->srCache[i].data);
5419 dev->srCache[i].data = NULL;
5422 YFREE(dev->srCache);
5423 dev->srCache = NULL;
5426 YFREE(dev->gcCleanupList);
5428 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5429 YFREE(dev->tempBuffer[i].buffer);
5433 if (dev->param.deinitialiseNAND)
5434 dev->param.deinitialiseNAND(dev);
5438 int yaffs_CountFreeChunks(yaffs_Device *dev)
5443 yaffs_BlockInfo *blk;
5445 blk = dev->blockInfo;
5446 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
5447 switch (blk->blockState) {
5448 case YAFFS_BLOCK_STATE_EMPTY:
5449 case YAFFS_BLOCK_STATE_ALLOCATING:
5450 case YAFFS_BLOCK_STATE_COLLECTING:
5451 case YAFFS_BLOCK_STATE_FULL:
5453 (dev->param.nChunksPerBlock - blk->pagesInUse +
5454 blk->softDeletions);
5465 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
5467 /* This is what we report to the outside world */
5470 int nDirtyCacheChunks;
5471 int blocksForCheckpoint;
5475 nFree = dev->nFreeChunks;
5477 nFree = yaffs_CountFreeChunks(dev);
5480 nFree += dev->nDeletedFiles;
5482 /* Now count the number of dirty chunks in the cache and subtract those */
5484 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
5485 if (dev->srCache[i].dirty)
5486 nDirtyCacheChunks++;
5489 nFree -= nDirtyCacheChunks;
5491 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
5493 /* Now we figure out how much to reserve for the checkpoint and report that... */
5494 blocksForCheckpoint = yaffs2_CalcCheckpointBlocksRequired(dev);
5496 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
5506 /*---------------------------------------- YAFFS test code ----------------------*/
5508 #define yaffs_CheckStruct(structure, syze, name) \
5510 if (sizeof(structure) != syze) { \
5511 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
5512 name, syze, (int) sizeof(structure))); \
5513 return YAFFS_FAIL; \
5517 static int yaffs_CheckStructures(void)
5519 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
5520 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
5521 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
5522 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5523 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
5525 #ifndef CONFIG_YAFFS_WINCE
5526 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");