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.
15 #include "yaffs_trace.h"
17 #include "yaffsinterface.h"
18 #include "yaffs_guts.h"
19 #include "yaffs_tagsvalidity.h"
20 #include "yaffs_getblockinfo.h"
22 #include "yaffs_tagscompat.h"
24 #include "yaffs_nand.h"
26 #include "yaffs_yaffs1.h"
27 #include "yaffs_yaffs2.h"
28 #include "yaffs_bitmap.h"
29 #include "yaffs_verify.h"
31 #include "yaffs_nand.h"
32 #include "yaffs_packedtags2.h"
34 #include "yaffs_nameval.h"
35 #include "yaffs_allocator.h"
37 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
38 #define YAFFS_GC_GOOD_ENOUGH 2
39 #define YAFFS_GC_PASSIVE_THRESHOLD 4
41 #include "yaffs_ecc.h"
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
49 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
51 const yaffs_ExtendedTags *tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
53 const yaffs_ExtendedTags *tags);
55 /* Other local prototypes */
56 static void yaffs_UpdateParent(yaffs_Object *obj);
57 static int yaffs_UnlinkObject(yaffs_Object *obj);
58 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
62 yaffs_ExtendedTags *tags,
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
67 yaffs_ObjectType type);
70 static int yaffs_ApplyXMod(yaffs_Object *obj, char *buffer, yaffs_XAttrMod *xmod);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
76 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
79 static int yaffs_UnlinkWorker(yaffs_Object *obj);
81 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
84 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
85 yaffs_BlockInfo **blockUsedPtr);
87 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
89 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
90 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
92 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
93 yaffs_ExtendedTags *tags);
95 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
98 yaffs_ExtendedTags *tags);
101 static void yaffs_LoadNameFromObjectHeader(yaffs_Device *dev,YCHAR *name, const YCHAR *ohName, int bufferSize);
102 static void yaffs_LoadObjectHeaderFromName(yaffs_Device *dev,YCHAR *ohName, const YCHAR *name);
105 /* Function to calculate chunk and offset */
107 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
113 chunk = (__u32)(addr >> dev->chunkShift);
115 if (dev->chunkDiv == 1) {
116 /* easy power of 2 case */
117 offset = (__u32)(addr & dev->chunkMask);
119 /* Non power-of-2 case */
123 chunk /= dev->chunkDiv;
125 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
126 offset = (__u32)(addr - chunkBase);
133 /* Function to return the number of shifts for a power of 2 greater than or
134 * equal to the given number
135 * Note we don't try to cater for all possible numbers and this does not have to
136 * be hellishly efficient.
139 static __u32 ShiftsGE(__u32 x)
144 nShifts = extraBits = 0;
159 /* Function to return the number of shifts to get a 1 in bit 0
162 static __u32 Shifts(__u32 x)
182 * Temporary buffer manipulations.
185 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
188 __u8 *buf = (__u8 *)1;
190 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
192 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
193 dev->tempBuffer[i].line = 0; /* not in use */
194 dev->tempBuffer[i].buffer = buf =
195 YMALLOC_DMA(dev->param.totalBytesPerChunk);
198 return buf ? YAFFS_OK : YAFFS_FAIL;
201 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
206 if (dev->tempInUse > dev->maxTemp)
207 dev->maxTemp = dev->tempInUse;
209 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
210 if (dev->tempBuffer[i].line == 0) {
211 dev->tempBuffer[i].line = lineNo;
212 if ((i + 1) > dev->maxTemp) {
213 dev->maxTemp = i + 1;
214 for (j = 0; j <= i; j++)
215 dev->tempBuffer[j].maxLine =
216 dev->tempBuffer[j].line;
219 return dev->tempBuffer[i].buffer;
223 T(YAFFS_TRACE_BUFFERS,
224 (TSTR("Out of temp buffers at line %d, other held by lines:"),
226 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
227 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
229 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
232 * If we got here then we have to allocate an unmanaged one
236 dev->unmanagedTempAllocations++;
237 return YMALLOC(dev->nDataBytesPerChunk);
241 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
248 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
249 if (dev->tempBuffer[i].buffer == buffer) {
250 dev->tempBuffer[i].line = 0;
256 /* assume it is an unmanaged one. */
257 T(YAFFS_TRACE_BUFFERS,
258 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
261 dev->unmanagedTempDeallocations++;
267 * Determine if we have a managed buffer.
269 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
273 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
274 if (dev->tempBuffer[i].buffer == buffer)
278 for (i = 0; i < dev->param.nShortOpCaches; i++) {
279 if (dev->srCache[i].data == buffer)
283 if (buffer == dev->checkpointBuffer)
286 T(YAFFS_TRACE_ALWAYS,
287 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
299 * Simple hash function. Needs to have a reasonable spread
302 static Y_INLINE int yaffs_HashFunction(int n)
305 return n % YAFFS_NOBJECT_BUCKETS;
309 * Access functions to useful fake objects.
310 * Note that root might have a presence in NAND if permissions are set.
313 yaffs_Object *yaffs_Root(yaffs_Device *dev)
318 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
320 return dev->lostNFoundDir;
325 * Erased NAND checking functions
328 int yaffs_CheckFF(__u8 *buffer, int nBytes)
330 /* Horrible, slow implementation */
339 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
342 int retval = YAFFS_OK;
343 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
344 yaffs_ExtendedTags tags;
347 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
349 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
352 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
353 T(YAFFS_TRACE_NANDACCESS,
354 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
358 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
365 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
368 yaffs_ExtendedTags *tags)
370 int retval = YAFFS_OK;
371 yaffs_ExtendedTags tempTags;
372 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
375 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
376 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
377 tempTags.objectId != tags->objectId ||
378 tempTags.chunkId != tags->chunkId ||
379 tempTags.byteCount != tags->byteCount)
382 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
387 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
389 yaffs_ExtendedTags *tags,
396 yaffs2_InvalidateCheckpoint(dev);
399 yaffs_BlockInfo *bi = 0;
402 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
408 /* First check this chunk is erased, if it needs
409 * checking. The checking policy (unless forced
410 * always on) is as follows:
412 * Check the first page we try to write in a block.
413 * If the check passes then we don't need to check any
414 * more. If the check fails, we check again...
415 * If the block has been erased, we don't need to check.
417 * However, if the block has been prioritised for gc,
418 * then we think there might be something odd about
419 * this block and stop using it.
421 * Rationale: We should only ever see chunks that have
422 * not been erased if there was a partially written
423 * chunk due to power loss. This checking policy should
424 * catch that case with very few checks and thus save a
425 * lot of checks that are most likely not needed.
428 * If an erase check fails or the write fails we skip the
432 /* let's give it a try */
435 if(dev->param.alwaysCheckErased)
436 bi->skipErasedCheck = 0;
438 if (!bi->skipErasedCheck) {
439 erasedOk = yaffs_CheckChunkErased(dev, chunk);
440 if (erasedOk != YAFFS_OK) {
442 (TSTR("**>> yaffs chunk %d was not erased"
445 /* If not erased, delete this one,
446 * skip rest of block and
447 * try another chunk */
448 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
449 yaffs_SkipRestOfBlock(dev);
454 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
457 if(!bi->skipErasedCheck)
458 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
460 if (writeOk != YAFFS_OK) {
461 /* Clean up aborted write, skip to next block and
462 * try another chunk */
463 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
467 bi->skipErasedCheck = 1;
469 /* Copy the data into the robustification buffer */
470 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
472 } while (writeOk != YAFFS_OK &&
473 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
480 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
483 dev->nRetriedWrites += (attempts - 1);
492 * Block retiring for handling a broken block.
495 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
497 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
499 yaffs2_InvalidateCheckpoint(dev);
501 yaffs2_ClearOldestDirtySequence(dev,bi);
503 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
504 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
505 T(YAFFS_TRACE_ALWAYS, (TSTR(
506 "yaffs: Failed to mark bad and erase block %d"
507 TENDSTR), blockInNAND));
509 yaffs_ExtendedTags tags;
510 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
512 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
514 memset(buffer, 0xff, dev->nDataBytesPerChunk);
515 yaffs_InitialiseTags(&tags);
516 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
517 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
518 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
519 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
520 TCONT("write bad block marker to block %d")
521 TENDSTR), blockInNAND));
523 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
527 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
528 bi->gcPrioritise = 0;
529 bi->needsRetiring = 0;
531 dev->nRetiredBlocks++;
535 * Functions for robustisizing TODO
539 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
541 const yaffs_ExtendedTags *tags)
544 chunkInNAND=chunkInNAND;
549 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
550 const yaffs_ExtendedTags *tags)
553 chunkInNAND=chunkInNAND;
557 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
559 if (!bi->gcPrioritise) {
560 bi->gcPrioritise = 1;
561 dev->hasPendingPrioritisedGCs = 1;
562 bi->chunkErrorStrikes++;
564 if (bi->chunkErrorStrikes > 3) {
565 bi->needsRetiring = 1; /* Too many stikes, so retire this */
566 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
572 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
575 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
576 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
578 yaffs_HandleChunkError(dev, bi);
581 /* Was an actual write failure, so mark the block for retirement */
582 bi->needsRetiring = 1;
583 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
584 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
587 /* Delete the chunk */
588 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
589 yaffs_SkipRestOfBlock(dev);
593 /*---------------- Name handling functions ------------*/
595 static __u16 yaffs_CalcNameSum(const YCHAR *name)
600 const YUCHAR *bname = (const YUCHAR *) name;
602 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
604 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
605 sum += yaffs_toupper(*bname) * i;
616 void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
618 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
619 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
620 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
621 yaffs_strcpy(obj->shortName, name);
623 obj->shortName[0] = _Y('\0');
625 obj->sum = yaffs_CalcNameSum(name);
628 void yaffs_SetObjectNameFromOH(yaffs_Object *obj, const yaffs_ObjectHeader *oh)
630 #ifdef CONFIG_YAFFS_AUTO_UNICODE
631 YCHAR tmpName[YAFFS_MAX_NAME_LENGTH+1];
632 memset(tmpName,0,sizeof(tmpName));
633 yaffs_LoadNameFromObjectHeader(obj->myDev,tmpName,oh->name,YAFFS_MAX_NAME_LENGTH+1);
634 yaffs_SetObjectName(obj,tmpName);
636 yaffs_SetObjectName(obj,oh->name);
640 /*-------------------- TNODES -------------------
642 * List of spare tnodes
643 * The list is hooked together using the first pointer
648 yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
650 yaffs_Tnode *tn = yaffs_AllocateRawTnode(dev);
652 memset(tn, 0, dev->tnodeSize);
656 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
661 /* FreeTnode frees up a tnode and puts it back on the free list */
662 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
664 yaffs_FreeRawTnode(dev,tn);
666 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
669 static void yaffs_DeinitialiseTnodesAndObjects(yaffs_Device *dev)
671 yaffs_DeinitialiseRawTnodesAndObjects(dev);
677 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
680 __u32 *map = (__u32 *)tn;
686 pos &= YAFFS_TNODES_LEVEL0_MASK;
687 val >>= dev->chunkGroupBits;
689 bitInMap = pos * dev->tnodeWidth;
690 wordInMap = bitInMap / 32;
691 bitInWord = bitInMap & (32 - 1);
693 mask = dev->tnodeMask << bitInWord;
695 map[wordInMap] &= ~mask;
696 map[wordInMap] |= (mask & (val << bitInWord));
698 if (dev->tnodeWidth > (32 - bitInWord)) {
699 bitInWord = (32 - bitInWord);
701 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
702 map[wordInMap] &= ~mask;
703 map[wordInMap] |= (mask & (val >> bitInWord));
707 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
710 __u32 *map = (__u32 *)tn;
716 pos &= YAFFS_TNODES_LEVEL0_MASK;
718 bitInMap = pos * dev->tnodeWidth;
719 wordInMap = bitInMap / 32;
720 bitInWord = bitInMap & (32 - 1);
722 val = map[wordInMap] >> bitInWord;
724 if (dev->tnodeWidth > (32 - bitInWord)) {
725 bitInWord = (32 - bitInWord);
727 val |= (map[wordInMap] << bitInWord);
730 val &= dev->tnodeMask;
731 val <<= dev->chunkGroupBits;
736 /* ------------------- End of individual tnode manipulation -----------------*/
738 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
739 * The look up tree is represented by the top tnode and the number of topLevel
740 * in the tree. 0 means only the level 0 tnode is in the tree.
743 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
744 yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
745 yaffs_FileStructure *fStruct,
748 yaffs_Tnode *tn = fStruct->top;
750 int requiredTallness;
751 int level = fStruct->topLevel;
755 /* Check sane level and chunk Id */
756 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
759 if (chunkId > YAFFS_MAX_CHUNK_ID)
762 /* First check we're tall enough (ie enough topLevel) */
764 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
765 requiredTallness = 0;
767 i >>= YAFFS_TNODES_INTERNAL_BITS;
771 if (requiredTallness > fStruct->topLevel)
772 return NULL; /* Not tall enough, so we can't find it */
774 /* Traverse down to level 0 */
775 while (level > 0 && tn) {
776 tn = tn->internal[(chunkId >>
777 (YAFFS_TNODES_LEVEL0_BITS +
779 YAFFS_TNODES_INTERNAL_BITS)) &
780 YAFFS_TNODES_INTERNAL_MASK];
787 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
788 * This happens in two steps:
789 * 1. If the tree isn't tall enough, then make it taller.
790 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
792 * Used when modifying the tree.
794 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
795 * be plugged into the ttree.
798 yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
799 yaffs_FileStructure *fStruct,
801 yaffs_Tnode *passedTn)
803 int requiredTallness;
811 /* Check sane level and page Id */
812 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
815 if (chunkId > YAFFS_MAX_CHUNK_ID)
818 /* First check we're tall enough (ie enough topLevel) */
820 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
821 requiredTallness = 0;
823 x >>= YAFFS_TNODES_INTERNAL_BITS;
828 if (requiredTallness > fStruct->topLevel) {
829 /* Not tall enough, gotta make the tree taller */
830 for (i = fStruct->topLevel; i < requiredTallness; i++) {
832 tn = yaffs_GetTnode(dev);
835 tn->internal[0] = fStruct->top;
840 (TSTR("yaffs: no more tnodes" TENDSTR)));
846 /* Traverse down to level 0, adding anything we need */
848 l = fStruct->topLevel;
852 while (l > 0 && tn) {
854 (YAFFS_TNODES_LEVEL0_BITS +
855 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
856 YAFFS_TNODES_INTERNAL_MASK;
859 if ((l > 1) && !tn->internal[x]) {
860 /* Add missing non-level-zero tnode */
861 tn->internal[x] = yaffs_GetTnode(dev);
865 /* Looking from level 1 at level 0 */
867 /* If we already have one, then release it.*/
869 yaffs_FreeTnode(dev, tn->internal[x]);
870 tn->internal[x] = passedTn;
872 } else if (!tn->internal[x]) {
873 /* Don't have one, none passed in */
874 tn->internal[x] = yaffs_GetTnode(dev);
880 tn = tn->internal[x];
886 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
887 yaffs_FreeTnode(dev, passedTn);
894 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
895 yaffs_ExtendedTags *tags, int objectId,
900 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
901 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
902 theChunk % dev->param.nChunksPerBlock)) {
904 if(dev->chunkGroupSize == 1)
907 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
909 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
921 /* Experimental code not being used yet. Might speed up file deletion */
922 /* DeleteWorker scans backwards through the tnode tree and deletes all the
923 * chunks and tnodes in the file.
924 * Returns 1 if the tree was deleted.
925 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
928 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
929 int chunkOffset, int *limit)
934 yaffs_ExtendedTags tags;
936 yaffs_Device *dev = in->myDev;
942 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
944 if (tn->internal[i]) {
945 if (limit && (*limit) < 0) {
949 yaffs_DeleteWorker(in,
957 YAFFS_TNODES_INTERNAL_BITS)
965 tn->internal[i] = NULL;
969 return (allDone) ? 1 : 0;
970 } else if (level == 0) {
973 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
975 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
978 chunkInInode = (chunkOffset <<
979 YAFFS_TNODES_LEVEL0_BITS) + i;
982 yaffs_FindChunkInGroup(dev,
988 if (foundChunk > 0) {
989 yaffs_DeleteChunk(dev,
1001 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1005 return (i < 0) ? 1 : 0;
1017 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1019 yaffs_BlockInfo *theBlock;
1022 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1024 blockNo = chunk / dev->param.nChunksPerBlock;
1025 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1027 theBlock->softDeletions++;
1029 yaffs2_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1033 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1034 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1036 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1039 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1040 __u32 level, int chunkOffset)
1045 yaffs_Device *dev = in->myDev;
1050 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1052 if (tn->internal[i]) {
1054 yaffs_SoftDeleteWorker(in,
1060 YAFFS_TNODES_INTERNAL_BITS)
1063 yaffs_FreeTnode(dev,
1066 tn->internal[i] = NULL;
1068 /* Hoosterman... how could this happen? */
1072 return (allDone) ? 1 : 0;
1073 } else if (level == 0) {
1075 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1076 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1078 /* Note this does not find the real chunk, only the chunk group.
1079 * We make an assumption that a chunk group is not larger than
1082 yaffs_SoftDeleteChunk(dev, theChunk);
1083 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1097 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1100 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1101 if (obj->nDataChunks <= 0) {
1102 /* Empty file with no duplicate object headers, just delete it immediately */
1103 yaffs_FreeTnode(obj->myDev,
1104 obj->variant.fileVariant.top);
1105 obj->variant.fileVariant.top = NULL;
1106 T(YAFFS_TRACE_TRACING,
1107 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1109 yaffs_DoGenericObjectDeletion(obj);
1111 yaffs_SoftDeleteWorker(obj,
1112 obj->variant.fileVariant.top,
1113 obj->variant.fileVariant.
1115 obj->softDeleted = 1;
1120 /* Pruning removes any part of the file structure tree that is beyond the
1121 * bounds of the file (ie that does not point to chunks).
1123 * A file should only get pruned when its size is reduced.
1125 * Before pruning, the chunks must be pulled from the tree and the
1126 * level 0 tnode entries must be zeroed out.
1127 * Could also use this for file deletion, but that's probably better handled
1128 * by a special case.
1130 * This function is recursive. For levels > 0 the function is called again on
1131 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1132 * If there is no data in a subtree then it is pruned.
1135 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1136 __u32 level, int del0)
1145 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1146 if (tn->internal[i]) {
1148 yaffs_PruneWorker(dev, tn->internal[i],
1150 (i == 0) ? del0 : 1);
1153 if (tn->internal[i])
1157 int tnodeSize_u32 = dev->tnodeSize/sizeof(__u32);
1158 __u32 *map = (__u32 *)tn;
1160 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1166 if (hasData == 0 && del0) {
1167 /* Free and return NULL */
1169 yaffs_FreeTnode(dev, tn);
1179 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1180 yaffs_FileStructure *fStruct)
1187 if (fStruct->topLevel > 0) {
1189 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1191 /* Now we have a tree with all the non-zero branches NULL but the height
1192 * is the same as it was.
1193 * Let's see if we can trim internal tnodes to shorten the tree.
1194 * We can do this if only the 0th element in the tnode is in use
1195 * (ie all the non-zero are NULL)
1198 while (fStruct->topLevel && !done) {
1202 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1203 if (tn->internal[i])
1208 fStruct->top = tn->internal[0];
1209 fStruct->topLevel--;
1210 yaffs_FreeTnode(dev, tn);
1220 /*-------------------- End of File Structure functions.-------------------*/
1223 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1224 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1226 yaffs_Object *obj = yaffs_AllocateRawObject(dev);
1231 /* Now sweeten it up... */
1233 memset(obj, 0, sizeof(yaffs_Object));
1234 obj->beingCreated = 1;
1238 obj->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1239 YINIT_LIST_HEAD(&(obj->hardLinks));
1240 YINIT_LIST_HEAD(&(obj->hashLink));
1241 YINIT_LIST_HEAD(&obj->siblings);
1244 /* Now make the directory sane */
1246 obj->parent = dev->rootDir;
1247 ylist_add(&(obj->siblings), &dev->rootDir->variant.directoryVariant.children);
1250 /* Add it to the lost and found directory.
1251 * NB Can't put root or lostNFound in lostNFound so
1252 * check if lostNFound exists first
1254 if (dev->lostNFoundDir)
1255 yaffs_AddObjectToDirectory(dev->lostNFoundDir, obj);
1257 obj->beingCreated = 0;
1260 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1265 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1270 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1272 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1273 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1274 obj->unlinkAllowed = 0; /* ... or unlink it */
1277 obj->yst_mode = mode;
1279 obj->hdrChunk = 0; /* Not a valid chunk. */
1286 static void yaffs_UnhashObject(yaffs_Object *obj)
1289 yaffs_Device *dev = obj->myDev;
1291 /* If it is still linked into the bucket list, free from the list */
1292 if (!ylist_empty(&obj->hashLink)) {
1293 ylist_del_init(&obj->hashLink);
1294 bucket = yaffs_HashFunction(obj->objectId);
1295 dev->objectBucket[bucket].count--;
1299 /* FreeObject frees up a Object and puts it back on the free list */
1300 static void yaffs_FreeObject(yaffs_Object *obj)
1302 yaffs_Device *dev = obj->myDev;
1304 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), obj, obj->myInode));
1310 if (!ylist_empty(&obj->siblings))
1315 /* We're still hooked up to a cached inode.
1316 * Don't delete now, but mark for later deletion
1318 obj->deferedFree = 1;
1322 yaffs_UnhashObject(obj);
1324 yaffs_FreeRawObject(dev,obj);
1326 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1330 void yaffs_HandleDeferedFree(yaffs_Object *obj)
1332 if (obj->deferedFree)
1333 yaffs_FreeObject(obj);
1336 static void yaffs_InitialiseTnodesAndObjects(yaffs_Device *dev)
1343 yaffs_InitialiseRawTnodesAndObjects(dev);
1345 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1346 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
1347 dev->objectBucket[i].count = 0;
1351 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1355 int lowest = 999999;
1358 /* Search for the shortest list or one that
1362 for (i = 0; i < 10 && lowest > 4; i++) {
1363 dev->bucketFinder++;
1364 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
1365 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
1366 lowest = dev->objectBucket[dev->bucketFinder].count;
1367 l = dev->bucketFinder;
1375 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1377 int bucket = yaffs_FindNiceObjectBucket(dev);
1379 /* Now find an object value that has not already been taken
1380 * by scanning the list.
1384 struct ylist_head *i;
1386 __u32 n = (__u32) bucket;
1388 /* yaffs_CheckObjectHashSanity(); */
1392 n += YAFFS_NOBJECT_BUCKETS;
1393 if (1 || dev->objectBucket[bucket].count > 0) {
1394 ylist_for_each(i, &dev->objectBucket[bucket].list) {
1395 /* If there is already one in the list */
1396 if (i && ylist_entry(i, yaffs_Object,
1397 hashLink)->objectId == n) {
1407 static void yaffs_HashObject(yaffs_Object *in)
1409 int bucket = yaffs_HashFunction(in->objectId);
1410 yaffs_Device *dev = in->myDev;
1412 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
1413 dev->objectBucket[bucket].count++;
1416 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
1418 int bucket = yaffs_HashFunction(number);
1419 struct ylist_head *i;
1422 ylist_for_each(i, &dev->objectBucket[bucket].list) {
1423 /* Look if it is in the list */
1425 in = ylist_entry(i, yaffs_Object, hashLink);
1426 if (in->objectId == number) {
1428 /* Don't tell the VFS about this one if it is defered free */
1429 if (in->deferedFree)
1440 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
1441 yaffs_ObjectType type)
1443 yaffs_Object *theObject=NULL;
1444 yaffs_Tnode *tn = NULL;
1447 number = yaffs_CreateNewObjectNumber(dev);
1449 if (type == YAFFS_OBJECT_TYPE_FILE) {
1450 tn = yaffs_GetTnode(dev);
1455 theObject = yaffs_AllocateEmptyObject(dev);
1458 yaffs_FreeTnode(dev,tn);
1464 theObject->fake = 0;
1465 theObject->renameAllowed = 1;
1466 theObject->unlinkAllowed = 1;
1467 theObject->objectId = number;
1468 yaffs_HashObject(theObject);
1469 theObject->variantType = type;
1470 #ifdef CONFIG_YAFFS_WINCE
1471 yfsd_WinFileTimeNow(theObject->win_atime);
1472 theObject->win_ctime[0] = theObject->win_mtime[0] =
1473 theObject->win_atime[0];
1474 theObject->win_ctime[1] = theObject->win_mtime[1] =
1475 theObject->win_atime[1];
1479 theObject->yst_atime = theObject->yst_mtime =
1480 theObject->yst_ctime = Y_CURRENT_TIME;
1483 case YAFFS_OBJECT_TYPE_FILE:
1484 theObject->variant.fileVariant.fileSize = 0;
1485 theObject->variant.fileVariant.scannedFileSize = 0;
1486 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1487 theObject->variant.fileVariant.topLevel = 0;
1488 theObject->variant.fileVariant.top = tn;
1490 case YAFFS_OBJECT_TYPE_DIRECTORY:
1491 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
1493 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
1496 case YAFFS_OBJECT_TYPE_SYMLINK:
1497 case YAFFS_OBJECT_TYPE_HARDLINK:
1498 case YAFFS_OBJECT_TYPE_SPECIAL:
1499 /* No action required */
1501 case YAFFS_OBJECT_TYPE_UNKNOWN:
1502 /* todo this should not happen */
1510 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
1512 yaffs_ObjectType type)
1514 yaffs_Object *theObject = NULL;
1517 theObject = yaffs_FindObjectByNumber(dev, number);
1520 theObject = yaffs_CreateNewObject(dev, number, type);
1527 YCHAR *yaffs_CloneString(const YCHAR *str)
1529 YCHAR *newStr = NULL;
1535 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
1536 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
1538 yaffs_strncpy(newStr, str,len);
1546 * Mknod (create) a new object.
1547 * equivalentObject only has meaning for a hard link;
1548 * aliasString only has meaning for a symlink.
1549 * rdev only has meaning for devices (a subset of special objects)
1552 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1553 yaffs_Object *parent,
1558 yaffs_Object *equivalentObject,
1559 const YCHAR *aliasString, __u32 rdev)
1564 yaffs_Device *dev = parent->myDev;
1566 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1567 if (yaffs_FindObjectByName(parent, name))
1570 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
1571 str = yaffs_CloneString(aliasString);
1576 in = yaffs_CreateNewObject(dev, -1, type);
1591 in->variantType = type;
1593 in->yst_mode = mode;
1595 #ifdef CONFIG_YAFFS_WINCE
1596 yfsd_WinFileTimeNow(in->win_atime);
1597 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1598 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1601 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1603 in->yst_rdev = rdev;
1607 in->nDataChunks = 0;
1609 yaffs_SetObjectName(in, name);
1612 yaffs_AddObjectToDirectory(parent, in);
1614 in->myDev = parent->myDev;
1617 case YAFFS_OBJECT_TYPE_SYMLINK:
1618 in->variant.symLinkVariant.alias = str;
1620 case YAFFS_OBJECT_TYPE_HARDLINK:
1621 in->variant.hardLinkVariant.equivalentObject =
1623 in->variant.hardLinkVariant.equivalentObjectId =
1624 equivalentObject->objectId;
1625 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
1627 case YAFFS_OBJECT_TYPE_FILE:
1628 case YAFFS_OBJECT_TYPE_DIRECTORY:
1629 case YAFFS_OBJECT_TYPE_SPECIAL:
1630 case YAFFS_OBJECT_TYPE_UNKNOWN:
1635 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0, NULL) < 0) {
1636 /* Could not create the object header, fail the creation */
1637 yaffs_DeleteObject(in);
1641 yaffs_UpdateParent(parent);
1647 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
1648 __u32 mode, __u32 uid, __u32 gid)
1650 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1651 uid, gid, NULL, NULL, 0);
1654 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
1655 __u32 mode, __u32 uid, __u32 gid)
1657 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1658 mode, uid, gid, NULL, NULL, 0);
1661 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
1662 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1664 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1665 uid, gid, NULL, NULL, rdev);
1668 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
1669 __u32 mode, __u32 uid, __u32 gid,
1672 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1673 uid, gid, NULL, alias, 0);
1676 /* yaffs_Link returns the object id of the equivalent object.*/
1677 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
1678 yaffs_Object *equivalentObject)
1680 /* Get the real object in case we were fed a hard link as an equivalent object */
1681 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1683 if (yaffs_MknodObject
1684 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1685 equivalentObject, NULL, 0)) {
1686 return equivalentObject;
1693 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
1694 const YCHAR *newName, int force, int shadows)
1699 yaffs_Object *existingTarget;
1702 newDir = obj->parent; /* use the old directory */
1704 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1705 T(YAFFS_TRACE_ALWAYS,
1707 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
1712 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1713 if (obj->myDev->param.isYaffs2)
1714 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1716 unlinkOp = (newDir == obj->myDev->unlinkedDir
1717 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1719 deleteOp = (newDir == obj->myDev->deletedDir);
1721 existingTarget = yaffs_FindObjectByName(newDir, newName);
1723 /* If the object is a file going into the unlinked directory,
1724 * then it is OK to just stuff it in since duplicate names are allowed.
1725 * else only proceed if the new name does not exist and if we're putting
1726 * it into a directory.
1733 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1734 yaffs_SetObjectName(obj, newName);
1737 yaffs_AddObjectToDirectory(newDir, obj);
1742 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1743 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows, NULL) >= 0)
1750 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
1751 yaffs_Object *newDir, const YCHAR *newName)
1753 yaffs_Object *obj = NULL;
1754 yaffs_Object *existingTarget = NULL;
1760 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1762 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1765 dev = oldDir->myDev;
1767 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1768 /* Special case for case insemsitive systems (eg. WinCE).
1769 * While look-up is case insensitive, the name isn't.
1770 * Therefore we might want to change x.txt to X.txt
1772 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
1776 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
1780 obj = yaffs_FindObjectByName(oldDir, oldName);
1782 if (obj && obj->renameAllowed) {
1784 /* Now do the handling for an existing target, if there is one */
1786 existingTarget = yaffs_FindObjectByName(newDir, newName);
1787 if (existingTarget &&
1788 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1789 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
1790 /* There is a target that is a non-empty directory, so we fail */
1791 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
1792 } else if (existingTarget && existingTarget != obj) {
1793 /* Nuke the target first, using shadowing,
1794 * but only if it isn't the same object.
1796 * Note we must disable gc otherwise it can mess up the shadowing.
1800 yaffs_ChangeObjectName(obj, newDir, newName, force,
1801 existingTarget->objectId);
1802 existingTarget->isShadowed = 1;
1803 yaffs_UnlinkObject(existingTarget);
1807 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1809 yaffs_UpdateParent(oldDir);
1810 if(newDir != oldDir)
1811 yaffs_UpdateParent(newDir);
1818 /*------------------------- Block Management and Page Allocation ----------------*/
1820 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
1822 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1824 dev->blockInfo = NULL;
1825 dev->chunkBits = NULL;
1827 dev->allocationBlock = -1; /* force it to get a new one */
1829 /* If the first allocation strategy fails, thry the alternate one */
1830 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1831 if (!dev->blockInfo) {
1832 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1833 dev->blockInfoAlt = 1;
1835 dev->blockInfoAlt = 0;
1837 if (dev->blockInfo) {
1838 /* Set up dynamic blockinfo stuff. */
1839 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
1840 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1841 if (!dev->chunkBits) {
1842 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1843 dev->chunkBitsAlt = 1;
1845 dev->chunkBitsAlt = 0;
1848 if (dev->blockInfo && dev->chunkBits) {
1849 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1850 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1857 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1859 if (dev->blockInfoAlt && dev->blockInfo)
1860 YFREE_ALT(dev->blockInfo);
1861 else if (dev->blockInfo)
1862 YFREE(dev->blockInfo);
1864 dev->blockInfoAlt = 0;
1866 dev->blockInfo = NULL;
1868 if (dev->chunkBitsAlt && dev->chunkBits)
1869 YFREE_ALT(dev->chunkBits);
1870 else if (dev->chunkBits)
1871 YFREE(dev->chunkBits);
1872 dev->chunkBitsAlt = 0;
1873 dev->chunkBits = NULL;
1876 void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
1878 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1882 /* If the block is still healthy erase it and mark as clean.
1883 * If the block has had a data failure, then retire it.
1886 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
1887 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
1888 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
1890 yaffs2_ClearOldestDirtySequence(dev,bi);
1892 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1894 /* If this is the block being garbage collected then stop gc'ing this block */
1895 if(blockNo == dev->gcBlock)
1898 /* If this block is currently the best candidate for gc then drop as a candidate */
1899 if(blockNo == dev->gcDirtiest){
1900 dev->gcDirtiest = 0;
1901 dev->gcPagesInUse = 0;
1904 if (!bi->needsRetiring) {
1905 yaffs2_InvalidateCheckpoint(dev);
1906 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1908 dev->nErasureFailures++;
1909 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1910 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1915 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
1917 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
1918 if (!yaffs_CheckChunkErased
1919 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
1920 T(YAFFS_TRACE_ERROR,
1922 (">>Block %d erasure supposedly OK, but chunk %d not erased"
1923 TENDSTR), blockNo, i));
1929 /* Clean it up... */
1930 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1931 bi->sequenceNumber = 0;
1932 dev->nErasedBlocks++;
1934 bi->softDeletions = 0;
1935 bi->hasShrinkHeader = 0;
1936 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
1937 bi->gcPrioritise = 0;
1938 yaffs_ClearChunkBits(dev, blockNo);
1940 T(YAFFS_TRACE_ERASE,
1941 (TSTR("Erased block %d" TENDSTR), blockNo));
1943 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
1945 yaffs_RetireBlock(dev, blockNo);
1946 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1947 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
1951 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
1955 yaffs_BlockInfo *bi;
1957 if (dev->nErasedBlocks < 1) {
1958 /* Hoosterman we've got a problem.
1959 * Can't get space to gc
1961 T(YAFFS_TRACE_ERROR,
1962 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
1967 /* Find an empty block. */
1969 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1970 dev->allocationBlockFinder++;
1971 if (dev->allocationBlockFinder < dev->internalStartBlock
1972 || dev->allocationBlockFinder > dev->internalEndBlock) {
1973 dev->allocationBlockFinder = dev->internalStartBlock;
1976 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
1978 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
1979 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1980 dev->sequenceNumber++;
1981 bi->sequenceNumber = dev->sequenceNumber;
1982 dev->nErasedBlocks--;
1983 T(YAFFS_TRACE_ALLOCATE,
1984 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
1985 dev->allocationBlockFinder, dev->sequenceNumber,
1986 dev->nErasedBlocks));
1987 return dev->allocationBlockFinder;
1991 T(YAFFS_TRACE_ALWAYS,
1993 ("yaffs tragedy: no more erased blocks, but there should have been %d"
1994 TENDSTR), dev->nErasedBlocks));
2001 * Check if there's space to allocate...
2002 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2004 int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
2007 int reservedBlocks = dev->param.nReservedBlocks;
2008 int checkpointBlocks;
2010 checkpointBlocks = yaffs2_CalcCheckpointBlocksRequired(dev);
2012 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
2014 return (dev->nFreeChunks > (reservedChunks + nChunks));
2017 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2018 yaffs_BlockInfo **blockUsedPtr)
2021 yaffs_BlockInfo *bi;
2023 if (dev->allocationBlock < 0) {
2024 /* Get next block to allocate off */
2025 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2026 dev->allocationPage = 0;
2029 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
2030 /* Not enough space to allocate unless we're allowed to use the reserve. */
2034 if (dev->nErasedBlocks < dev->param.nReservedBlocks
2035 && dev->allocationPage == 0) {
2036 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2039 /* Next page please.... */
2040 if (dev->allocationBlock >= 0) {
2041 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2043 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
2044 dev->allocationPage;
2046 yaffs_SetChunkBit(dev, dev->allocationBlock,
2047 dev->allocationPage);
2049 dev->allocationPage++;
2053 /* If the block is full set the state to full */
2054 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
2055 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2056 dev->allocationBlock = -1;
2065 T(YAFFS_TRACE_ERROR,
2066 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2071 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2075 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2077 if (dev->allocationBlock > 0)
2078 n += (dev->param.nChunksPerBlock - dev->allocationPage);
2085 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
2086 * if we don't want to write to it.
2088 void yaffs_SkipRestOfBlock(yaffs_Device *dev)
2090 if(dev->allocationBlock > 0){
2091 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2092 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
2093 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2094 dev->allocationBlock = -1;
2100 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2106 int retVal = YAFFS_OK;
2108 int isCheckpointBlock;
2112 int chunksBefore = yaffs_GetErasedChunks(dev);
2115 yaffs_ExtendedTags tags;
2117 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2119 yaffs_Object *object;
2121 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2124 T(YAFFS_TRACE_TRACING,
2125 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2128 bi->hasShrinkHeader,
2131 /*yaffs_VerifyFreeChunks(dev); */
2133 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
2134 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2136 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2140 if (isCheckpointBlock ||
2141 !yaffs_StillSomeChunkBits(dev, block)) {
2142 T(YAFFS_TRACE_TRACING,
2144 ("Collecting block %d that has no chunks in use" TENDSTR),
2146 yaffs_BlockBecameDirty(dev, block);
2149 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2151 yaffs_VerifyBlock(dev, bi, block);
2153 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
2154 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
2156 for (/* init already done */;
2157 retVal == YAFFS_OK &&
2158 dev->gcChunk < dev->param.nChunksPerBlock &&
2159 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
2161 dev->gcChunk++, oldChunk++) {
2162 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
2164 /* This page is in use and might need to be copied off */
2170 yaffs_InitialiseTags(&tags);
2172 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2176 yaffs_FindObjectByNumber(dev,
2179 T(YAFFS_TRACE_GC_DETAIL,
2181 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
2182 dev->gcChunk, tags.objectId, tags.chunkId,
2185 if (object && !yaffs_SkipVerification(dev)) {
2186 if (tags.chunkId == 0)
2187 matchingChunk = object->hdrChunk;
2188 else if (object->softDeleted)
2189 matchingChunk = oldChunk; /* Defeat the test */
2191 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
2193 if (oldChunk != matchingChunk)
2194 T(YAFFS_TRACE_ERROR,
2195 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2196 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
2201 T(YAFFS_TRACE_ERROR,
2203 ("page %d in gc has no object: %d %d %d "
2205 tags.objectId, tags.chunkId, tags.byteCount));
2210 object->softDeleted &&
2211 tags.chunkId != 0) {
2212 /* Data chunk in a soft deleted file, throw it away
2213 * It's a soft deleted data chunk,
2214 * No need to copy this, just forget about it and
2215 * fix up the object.
2218 /* Free chunks already includes softdeleted chunks.
2219 * How ever this chunk is going to soon be really deleted
2220 * which will increment free chunks.
2221 * We have to decrement free chunks so this works out properly.
2224 bi->softDeletions--;
2226 object->nDataChunks--;
2228 if (object->nDataChunks <= 0) {
2229 /* remeber to clean up the object */
2230 dev->gcCleanupList[dev->nCleanups] =
2236 /* Todo object && object->deleted && object->nDataChunks == 0 */
2237 /* Deleted object header with no data chunks.
2238 * Can be discarded and the file deleted.
2240 object->hdrChunk = 0;
2241 yaffs_FreeTnode(object->myDev,
2244 object->variant.fileVariant.top = NULL;
2245 yaffs_DoGenericObjectDeletion(object);
2247 } else if (object) {
2248 /* It's either a data chunk in a live file or
2249 * an ObjectHeader, so we're interested in it.
2250 * NB Need to keep the ObjectHeaders of deleted files
2251 * until the whole file has been deleted off
2253 tags.serialNumber++;
2257 if (tags.chunkId == 0) {
2258 /* It is an object Id,
2259 * We need to nuke the shrinkheader flags first
2260 * Also need to clean up shadowing.
2261 * We no longer want the shrinkHeader flag since its work is done
2262 * and if it is left in place it will mess up scanning.
2265 yaffs_ObjectHeader *oh;
2266 oh = (yaffs_ObjectHeader *)buffer;
2269 tags.extraIsShrinkHeader = 0;
2271 oh->shadowsObject = 0;
2272 oh->inbandShadowsObject = 0;
2273 tags.extraShadows = 0;
2275 /* Update file size */
2276 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
2277 oh->fileSize = object->variant.fileVariant.fileSize;
2278 tags.extraFileLength = oh->fileSize;
2281 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
2283 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
2286 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2289 retVal = YAFFS_FAIL;
2292 /* Ok, now fix up the Tnodes etc. */
2294 if (tags.chunkId == 0) {
2296 object->hdrChunk = newChunk;
2297 object->serial = tags.serialNumber;
2299 /* It's a data chunk */
2301 ok = yaffs_PutChunkIntoFile
2309 if (retVal == YAFFS_OK)
2310 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2315 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2321 yaffs_VerifyCollectedBlock(dev, bi, block);
2325 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2327 * The gc did not complete. Set block state back to FULL
2328 * because checkpointing does not restore gc.
2330 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2332 /* The gc completed. */
2333 /* Do any required cleanups */
2334 for (i = 0; i < dev->nCleanups; i++) {
2335 /* Time to delete the file too */
2337 yaffs_FindObjectByNumber(dev,
2338 dev->gcCleanupList[i]);
2340 yaffs_FreeTnode(dev,
2341 object->variant.fileVariant.
2343 object->variant.fileVariant.top = NULL;
2346 ("yaffs: About to finally delete object %d"
2347 TENDSTR), object->objectId));
2348 yaffs_DoGenericObjectDeletion(object);
2349 object->myDev->nDeletedFiles--;
2355 chunksAfter = yaffs_GetErasedChunks(dev);
2356 if (chunksBefore >= chunksAfter) {
2359 ("gc did not increase free chunks before %d after %d"
2360 TENDSTR), chunksBefore, chunksAfter));
2373 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2374 * for garbage collection.
2377 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2383 unsigned selected = 0;
2384 int prioritised = 0;
2385 int prioritisedExists = 0;
2386 yaffs_BlockInfo *bi;
2389 /* First let's see if we need to grab a prioritised block */
2390 if (dev->hasPendingPrioritisedGCs && !aggressive) {
2391 dev->gcDirtiest = 0;
2392 bi = dev->blockInfo;
2393 for (i = dev->internalStartBlock;
2394 i <= dev->internalEndBlock && !selected;
2397 if (bi->gcPrioritise) {
2398 prioritisedExists = 1;
2399 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2400 yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2409 * If there is a prioritised block and none was selected then
2410 * this happened because there is at least one old dirty block gumming
2411 * up the works. Let's gc the oldest dirty block.
2414 if(prioritisedExists &&
2416 dev->oldestDirtyBlock > 0)
2417 selected = dev->oldestDirtyBlock;
2419 if (!prioritisedExists) /* None found, so we can clear this */
2420 dev->hasPendingPrioritisedGCs = 0;
2423 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2425 * else (we're doing a leasurely gc), then we only bother to do this if the
2426 * block has only a few pages in use.
2431 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2433 threshold = dev->param.nChunksPerBlock;
2434 iterations = nBlocks;
2439 maxThreshold = dev->param.nChunksPerBlock/2;
2441 maxThreshold = dev->param.nChunksPerBlock/8;
2443 if(maxThreshold < YAFFS_GC_PASSIVE_THRESHOLD)
2444 maxThreshold = YAFFS_GC_PASSIVE_THRESHOLD;
2446 threshold = background ?
2447 (dev->gcNotDone + 2) * 2 : 0;
2448 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
2449 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2450 if(threshold > maxThreshold)
2451 threshold = maxThreshold;
2453 iterations = nBlocks / 16 + 1;
2454 if (iterations > 100)
2460 (dev->gcDirtiest < 1 ||
2461 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
2463 dev->gcBlockFinder++;
2464 if (dev->gcBlockFinder < dev->internalStartBlock ||
2465 dev->gcBlockFinder > dev->internalEndBlock)
2466 dev->gcBlockFinder = dev->internalStartBlock;
2468 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
2470 pagesUsed = bi->pagesInUse - bi->softDeletions;
2472 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2473 pagesUsed < dev->param.nChunksPerBlock &&
2474 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
2475 yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2476 dev->gcDirtiest = dev->gcBlockFinder;
2477 dev->gcPagesInUse = pagesUsed;
2481 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
2482 selected = dev->gcDirtiest;
2486 * If nothing has been selected for a while, try selecting the oldest dirty
2487 * because that's gumming up the works.
2490 if(!selected && dev->param.isYaffs2 &&
2491 dev->gcNotDone >= ( background ? 10 : 20)){
2492 yaffs2_FindOldestDirtySequence(dev);
2493 if(dev->oldestDirtyBlock > 0) {
2494 selected = dev->oldestDirtyBlock;
2495 dev->gcDirtiest = selected;
2496 dev->oldestDirtyGCs++;
2497 bi = yaffs_GetBlockInfo(dev, selected);
2498 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
2505 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
2507 dev->param.nChunksPerBlock - dev->gcPagesInUse,
2512 dev->backgroundGCs++;
2514 dev->gcDirtiest = 0;
2515 dev->gcPagesInUse = 0;
2517 if(dev->refreshSkip > 0)
2522 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
2523 dev->gcBlockFinder, dev->gcNotDone,
2525 dev->gcDirtiest, dev->gcPagesInUse,
2526 dev->oldestDirtyBlock,
2527 background ? " bg" : ""));
2533 /* New garbage collector
2534 * If we're very low on erased blocks then we do aggressive garbage collection
2535 * otherwise we do "leasurely" garbage collection.
2536 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2537 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2539 * The idea is to help clear out space in a more spread-out manner.
2540 * Dunno if it really does anything useful.
2542 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
2545 int gcOk = YAFFS_OK;
2549 int checkpointBlockAdjust;
2551 if(dev->param.gcControl &&
2552 (dev->param.gcControl(dev) & 1) == 0)
2555 if (dev->gcDisable) {
2556 /* Bail out so we don't get recursive gc */
2560 /* This loop should pass the first time.
2561 * We'll only see looping here if the collection does not increase space.
2567 checkpointBlockAdjust = yaffs2_CalcCheckpointBlocksRequired(dev);
2569 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
2570 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2572 /* If we need a block soon then do aggressive gc.*/
2573 if (dev->nErasedBlocks < minErased)
2576 if(!background && erasedChunks > (dev->nFreeChunks / 4))
2579 if(dev->gcSkip > 20)
2581 if(erasedChunks < dev->nFreeChunks/2 ||
2593 /* If we don't already have a block being gc'd then see if we should start another */
2595 if (dev->gcBlock < 1 && !aggressive) {
2596 dev->gcBlock = yaffs2_FindRefreshBlock(dev);
2600 if (dev->gcBlock < 1) {
2601 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
2606 if (dev->gcBlock > 0) {
2613 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2614 dev->nErasedBlocks, aggressive));
2616 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
2619 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
2622 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2623 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
2625 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
2626 (dev->gcBlock > 0) &&
2629 return aggressive ? gcOk : YAFFS_OK;
2633 * yaffs_BackgroundGarbageCollect()
2634 * Garbage collects. Intended to be called from a background thread.
2635 * Returns non-zero if at least half the free chunks are erased.
2637 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
2639 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2641 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
2643 yaffs_CheckGarbageCollection(dev, 1);
2644 return erasedChunks > dev->nFreeChunks/2;
2647 /*------------------------- TAGS --------------------------------*/
2649 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
2652 return (tags->chunkId == chunkInObject &&
2653 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2658 /*-------------------- Data file manipulation -----------------*/
2660 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
2661 yaffs_ExtendedTags *tags)
2663 /*Get the Tnode, then get the level 0 offset chunk offset */
2666 yaffs_ExtendedTags localTags;
2669 yaffs_Device *dev = in->myDev;
2672 /* Passed a NULL, so use our own tags space */
2676 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2679 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2682 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2688 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
2689 yaffs_ExtendedTags *tags)
2691 /* Get the Tnode, then get the level 0 offset chunk offset */
2694 yaffs_ExtendedTags localTags;
2696 yaffs_Device *dev = in->myDev;
2700 /* Passed a NULL, so use our own tags space */
2704 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2708 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2711 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2714 /* Delete the entry in the filestructure (if found) */
2716 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
2723 int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
2724 int chunkInNAND, int inScan)
2726 /* NB inScan is zero unless scanning.
2727 * For forward scanning, inScan is > 0;
2728 * for backward scanning inScan is < 0
2730 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
2734 yaffs_Device *dev = in->myDev;
2736 yaffs_ExtendedTags existingTags;
2737 yaffs_ExtendedTags newTags;
2738 unsigned existingSerial, newSerial;
2740 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2741 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2742 * If it is not during Scanning then something went wrong!
2745 T(YAFFS_TRACE_ERROR,
2747 ("yaffs tragedy:attempt to put data chunk into a non-file"
2752 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2756 tn = yaffs_AddOrFindLevel0Tnode(dev,
2757 &in->variant.fileVariant,
2764 /* Dummy insert, bail now */
2767 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2770 /* If we're scanning then we need to test for duplicates
2771 * NB This does not need to be efficient since it should only ever
2772 * happen when the power fails during a write, then only one
2773 * chunk should ever be affected.
2775 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2776 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2779 if (existingChunk > 0) {
2780 /* NB Right now existing chunk will not be real chunkId if the chunk group size > 1
2781 * thus we have to do a FindChunkInFile to get the real chunk id.
2783 * We have a duplicate now we need to decide which one to use:
2785 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2786 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2787 * YAFFS1: Get both sets of tags and compare serial numbers.
2791 /* Only do this for forward scanning */
2792 yaffs_ReadChunkWithTagsFromNAND(dev,
2796 /* Do a proper find */
2798 yaffs_FindChunkInFile(in, chunkInInode,
2802 if (existingChunk <= 0) {
2803 /*Hoosterman - how did this happen? */
2805 T(YAFFS_TRACE_ERROR,
2807 ("yaffs tragedy: existing chunk < 0 in scan"
2812 /* NB The deleted flags should be false, otherwise the chunks will
2813 * not be loaded during a scan
2817 newSerial = newTags.serialNumber;
2818 existingSerial = existingTags.serialNumber;
2822 (existingChunk <= 0 ||
2823 ((existingSerial + 1) & 3) == newSerial)) {
2824 /* Forward scanning.
2826 * Delete the old one and drop through to update the tnode
2828 yaffs_DeleteChunk(dev, existingChunk, 1,
2831 /* Backward scanning or we want to use the existing one
2833 * Delete the new one and return early so that the tnode isn't changed
2835 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2843 if (existingChunk == 0)
2846 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
2851 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
2854 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2856 if (chunkInNAND >= 0)
2857 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2860 T(YAFFS_TRACE_NANDACCESS,
2861 (TSTR("Chunk %d not found zero instead" TENDSTR),
2863 /* get sane (zero) data if you read a hole */
2864 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2870 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
2874 yaffs_ExtendedTags tags;
2875 yaffs_BlockInfo *bi;
2881 block = chunkId / dev->param.nChunksPerBlock;
2882 page = chunkId % dev->param.nChunksPerBlock;
2885 if (!yaffs_CheckChunkBit(dev, block, page))
2886 T(YAFFS_TRACE_VERIFY,
2887 (TSTR("Deleting invalid chunk %d"TENDSTR),
2890 bi = yaffs_GetBlockInfo(dev, block);
2892 yaffs2_UpdateOldestDirtySequence(dev, block, bi);
2894 T(YAFFS_TRACE_DELETION,
2895 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2897 if (!dev->param.isYaffs2 && markNAND &&
2898 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
2900 yaffs_InitialiseTags(&tags);
2902 tags.chunkDeleted = 1;
2904 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2905 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2907 dev->nUnmarkedDeletions++;
2910 /* Pull out of the management area.
2911 * If the whole block became dirty, this will kick off an erasure.
2913 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2914 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2915 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2916 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2919 yaffs_ClearChunkBit(dev, block, page);
2923 if (bi->pagesInUse == 0 &&
2924 !bi->hasShrinkHeader &&
2925 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2926 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2927 yaffs_BlockBecameDirty(dev, block);
2934 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
2935 const __u8 *buffer, int nBytes,
2938 /* Find old chunk Need to do this to get serial number
2939 * Write new one and patch into tree.
2940 * Invalidate old tags.
2944 yaffs_ExtendedTags prevTags;
2947 yaffs_ExtendedTags newTags;
2949 yaffs_Device *dev = in->myDev;
2951 yaffs_CheckGarbageCollection(dev,0);
2953 /* Get the previous chunk at this location in the file if it exists.
2954 * If it does not exist then put a zero into the tree. This creates
2955 * the tnode now, rather than later when it is harder to clean up.
2957 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2958 if(prevChunkId < 1 &&
2959 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
2962 /* Set up new tags */
2963 yaffs_InitialiseTags(&newTags);
2965 newTags.chunkId = chunkInInode;
2966 newTags.objectId = in->objectId;
2967 newTags.serialNumber =
2968 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
2969 newTags.byteCount = nBytes;
2971 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
2972 T(YAFFS_TRACE_ERROR,
2973 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
2979 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2982 if (newChunkId > 0) {
2983 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2985 if (prevChunkId > 0)
2986 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2988 yaffs_VerifyFileSanity(in);
2994 /* UpdateObjectHeader updates the header on NAND for an object.
2995 * If name is not NULL, then that new name is used.
2997 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
2998 int isShrink, int shadows, yaffs_XAttrMod *xmod)
3001 yaffs_BlockInfo *bi;
3003 yaffs_Device *dev = in->myDev;
3010 yaffs_ExtendedTags newTags;
3011 yaffs_ExtendedTags oldTags;
3012 const YCHAR *alias = NULL;
3014 __u8 *buffer = NULL;
3015 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3017 yaffs_ObjectHeader *oh = NULL;
3019 yaffs_strcpy(oldName, _Y("silly old name"));
3023 in == dev->rootDir || /* The rootDir should also be saved */
3026 yaffs_CheckGarbageCollection(dev,0);
3027 yaffs_CheckObjectDetailsLoaded(in);
3029 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3030 oh = (yaffs_ObjectHeader *) buffer;
3032 prevChunkId = in->hdrChunk;
3034 if (prevChunkId > 0) {
3035 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3038 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3040 memcpy(oldName, oh->name, sizeof(oh->name));
3041 memset(buffer, 0xFF, sizeof(yaffs_ObjectHeader));
3043 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3045 oh->type = in->variantType;
3046 oh->yst_mode = in->yst_mode;
3047 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3049 #ifdef CONFIG_YAFFS_WINCE
3050 oh->win_atime[0] = in->win_atime[0];
3051 oh->win_ctime[0] = in->win_ctime[0];
3052 oh->win_mtime[0] = in->win_mtime[0];
3053 oh->win_atime[1] = in->win_atime[1];
3054 oh->win_ctime[1] = in->win_ctime[1];
3055 oh->win_mtime[1] = in->win_mtime[1];
3057 oh->yst_uid = in->yst_uid;
3058 oh->yst_gid = in->yst_gid;
3059 oh->yst_atime = in->yst_atime;
3060 oh->yst_mtime = in->yst_mtime;
3061 oh->yst_ctime = in->yst_ctime;
3062 oh->yst_rdev = in->yst_rdev;
3065 oh->parentObjectId = in->parent->objectId;
3067 oh->parentObjectId = 0;
3069 if (name && *name) {
3070 memset(oh->name, 0, sizeof(oh->name));
3071 yaffs_LoadObjectHeaderFromName(dev,oh->name,name);
3072 } else if (prevChunkId > 0)
3073 memcpy(oh->name, oldName, sizeof(oh->name));
3075 memset(oh->name, 0, sizeof(oh->name));
3077 oh->isShrink = isShrink;
3079 switch (in->variantType) {
3080 case YAFFS_OBJECT_TYPE_UNKNOWN:
3081 /* Should not happen */
3083 case YAFFS_OBJECT_TYPE_FILE:
3085 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3086 || oh->parentObjectId ==
3087 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3088 fileVariant.fileSize;
3090 case YAFFS_OBJECT_TYPE_HARDLINK:
3091 oh->equivalentObjectId =
3092 in->variant.hardLinkVariant.equivalentObjectId;
3094 case YAFFS_OBJECT_TYPE_SPECIAL:
3097 case YAFFS_OBJECT_TYPE_DIRECTORY:
3100 case YAFFS_OBJECT_TYPE_SYMLINK:
3101 alias = in->variant.symLinkVariant.alias;
3103 alias = _Y("no alias");
3104 yaffs_strncpy(oh->alias,
3106 YAFFS_MAX_ALIAS_LENGTH);
3107 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3111 /* process any xattrib modifications */
3113 yaffs_ApplyXMod(in, (char *)buffer, xmod);
3117 yaffs_InitialiseTags(&newTags);
3119 newTags.chunkId = 0;
3120 newTags.objectId = in->objectId;
3121 newTags.serialNumber = in->serial;
3123 /* Add extra info for file header */
3125 newTags.extraHeaderInfoAvailable = 1;
3126 newTags.extraParentObjectId = oh->parentObjectId;
3127 newTags.extraFileLength = oh->fileSize;
3128 newTags.extraIsShrinkHeader = oh->isShrink;
3129 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3130 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3131 newTags.extraObjectType = in->variantType;
3133 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3135 /* Create new chunk in NAND */
3137 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3138 (prevChunkId > 0) ? 1 : 0);
3140 if (newChunkId >= 0) {
3142 in->hdrChunk = newChunkId;
3144 if (prevChunkId > 0) {
3145 yaffs_DeleteChunk(dev, prevChunkId, 1,
3149 if (!yaffs_ObjectHasCachedWriteData(in))
3152 /* If this was a shrink, then mark the block that the chunk lives on */
3154 bi = yaffs_GetBlockInfo(in->myDev,
3155 newChunkId / in->myDev->param.nChunksPerBlock);
3156 bi->hasShrinkHeader = 1;
3161 retVal = newChunkId;
3166 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3171 /*------------------------ Short Operations Cache ----------------------------------------
3172 * In many situations where there is no high level buffering (eg WinCE) a lot of
3173 * reads might be short sequential reads, and a lot of writes may be short
3174 * sequential writes. eg. scanning/writing a jpeg file.
3175 * In these cases, a short read/write cache can provide a huge perfomance benefit
3176 * with dumb-as-a-rock code.
3177 * In Linux, the page cache provides read buffering aand the short op cache provides write
3180 * There are a limited number (~10) of cache chunks per device so that we don't
3181 * need a very intelligent search.
3184 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3186 yaffs_Device *dev = obj->myDev;
3188 yaffs_ChunkCache *cache;
3189 int nCaches = obj->myDev->param.nShortOpCaches;
3191 for (i = 0; i < nCaches; i++) {
3192 cache = &dev->srCache[i];
3193 if (cache->object == obj &&
3202 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3204 yaffs_Device *dev = obj->myDev;
3205 int lowest = -99; /* Stop compiler whining. */
3207 yaffs_ChunkCache *cache;
3208 int chunkWritten = 0;
3209 int nCaches = obj->myDev->param.nShortOpCaches;
3215 /* Find the dirty cache for this object with the lowest chunk id. */
3216 for (i = 0; i < nCaches; i++) {
3217 if (dev->srCache[i].object == obj &&
3218 dev->srCache[i].dirty) {
3220 || dev->srCache[i].chunkId <
3222 cache = &dev->srCache[i];
3223 lowest = cache->chunkId;
3228 if (cache && !cache->locked) {
3229 /* Write it out and free it up */
3232 yaffs_WriteChunkDataToObject(cache->object,
3238 cache->object = NULL;
3241 } while (cache && chunkWritten > 0);
3244 /* Hoosterman, disk full while writing cache out. */
3245 T(YAFFS_TRACE_ERROR,
3246 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3253 /*yaffs_FlushEntireDeviceCache(dev)
3258 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3261 int nCaches = dev->param.nShortOpCaches;
3264 /* Find a dirty object in the cache and flush it...
3265 * until there are no further dirty objects.
3269 for (i = 0; i < nCaches && !obj; i++) {
3270 if (dev->srCache[i].object &&
3271 dev->srCache[i].dirty)
3272 obj = dev->srCache[i].object;
3276 yaffs_FlushFilesChunkCache(obj);
3283 /* Grab us a cache chunk for use.
3284 * First look for an empty one.
3285 * Then look for the least recently used non-dirty one.
3286 * Then look for the least recently used dirty one...., flush and look again.
3288 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3292 if (dev->param.nShortOpCaches > 0) {
3293 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3294 if (!dev->srCache[i].object)
3295 return &dev->srCache[i];
3302 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3304 yaffs_ChunkCache *cache;
3305 yaffs_Object *theObj;
3310 if (dev->param.nShortOpCaches > 0) {
3311 /* Try find a non-dirty one... */
3313 cache = yaffs_GrabChunkCacheWorker(dev);
3316 /* They were all dirty, find the last recently used object and flush
3317 * its cache, then find again.
3318 * NB what's here is not very accurate, we actually flush the object
3319 * the last recently used page.
3322 /* With locking we can't assume we can use entry zero */
3329 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3330 if (dev->srCache[i].object &&
3331 !dev->srCache[i].locked &&
3332 (dev->srCache[i].lastUse < usage || !cache)) {
3333 usage = dev->srCache[i].lastUse;
3334 theObj = dev->srCache[i].object;
3335 cache = &dev->srCache[i];
3340 if (!cache || cache->dirty) {
3341 /* Flush and try again */
3342 yaffs_FlushFilesChunkCache(theObj);
3343 cache = yaffs_GrabChunkCacheWorker(dev);
3353 /* Find a cached chunk */
3354 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
3357 yaffs_Device *dev = obj->myDev;
3359 if (dev->param.nShortOpCaches > 0) {
3360 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3361 if (dev->srCache[i].object == obj &&
3362 dev->srCache[i].chunkId == chunkId) {
3365 return &dev->srCache[i];
3372 /* Mark the chunk for the least recently used algorithym */
3373 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
3377 if (dev->param.nShortOpCaches > 0) {
3378 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3379 /* Reset the cache usages */
3381 for (i = 1; i < dev->param.nShortOpCaches; i++)
3382 dev->srCache[i].lastUse = 0;
3389 cache->lastUse = dev->srLastUse;
3396 /* Invalidate a single cache page.
3397 * Do this when a whole page gets written,
3398 * ie the short cache for this page is no longer valid.
3400 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3402 if (object->myDev->param.nShortOpCaches > 0) {
3403 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3406 cache->object = NULL;
3410 /* Invalidate all the cache pages associated with this object
3411 * Do this whenever ther file is deleted or resized.
3413 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3416 yaffs_Device *dev = in->myDev;
3418 if (dev->param.nShortOpCaches > 0) {
3419 /* Invalidate it. */
3420 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3421 if (dev->srCache[i].object == in)
3422 dev->srCache[i].object = NULL;
3428 /*--------------------- File read/write ------------------------
3429 * Read and write have very similar structures.
3430 * In general the read/write has three parts to it
3431 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3432 * Some complete chunks
3433 * An incomplete chunk to end off with
3435 * Curve-balls: the first chunk might also be the last chunk.
3438 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
3447 yaffs_ChunkCache *cache;
3454 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
3455 /* start = offset % dev->nDataBytesPerChunk; */
3456 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3459 /* OK now check for the curveball where the start and end are in
3462 if ((start + n) < dev->nDataBytesPerChunk)
3465 nToCopy = dev->nDataBytesPerChunk - start;
3467 cache = yaffs_FindChunkCache(in, chunk);
3469 /* If the chunk is already in the cache or it is less than a whole chunk
3470 * or we're using inband tags then use the cache (if there is caching)
3471 * else bypass the cache.
3473 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3474 if (dev->param.nShortOpCaches > 0) {
3476 /* If we can't find the data in the cache, then load it up. */
3479 cache = yaffs_GrabChunkCache(in->myDev);
3481 cache->chunkId = chunk;
3484 yaffs_ReadChunkDataFromObject(in, chunk,
3490 yaffs_UseChunkCache(dev, cache, 0);
3495 memcpy(buffer, &cache->data[start], nToCopy);
3499 /* Read into the local buffer then copy..*/
3502 yaffs_GetTempBuffer(dev, __LINE__);
3503 yaffs_ReadChunkDataFromObject(in, chunk,
3506 memcpy(buffer, &localBuffer[start], nToCopy);
3509 yaffs_ReleaseTempBuffer(dev, localBuffer,
3515 /* A full chunk. Read directly into the supplied buffer. */
3516 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3530 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3531 int nBytes, int writeThrough)
3540 int startOfWrite = offset;
3541 int chunkWritten = 0;
3549 while (n > 0 && chunkWritten >= 0) {
3550 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3552 if (chunk * dev->nDataBytesPerChunk + start != offset ||
3553 start >= dev->nDataBytesPerChunk) {
3554 T(YAFFS_TRACE_ERROR, (
3555 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
3557 (int)offset, chunk, start));
3559 chunk++; /* File pos to chunk in file offset */
3561 /* OK now check for the curveball where the start and end are in
3565 if ((start + n) < dev->nDataBytesPerChunk) {
3568 /* Now folks, to calculate how many bytes to write back....
3569 * If we're overwriting and not writing to then end of file then
3570 * we need to write back as much as was there before.
3573 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
3575 if (chunkStart > in->variant.fileVariant.fileSize)
3576 nBytesRead = 0; /* Past end of file */
3578 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
3580 if (nBytesRead > dev->nDataBytesPerChunk)
3581 nBytesRead = dev->nDataBytesPerChunk;
3585 (start + n)) ? nBytesRead : (start + n);
3587 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
3591 nToCopy = dev->nDataBytesPerChunk - start;
3592 nToWriteBack = dev->nDataBytesPerChunk;
3595 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3596 /* An incomplete start or end chunk (or maybe both start and end chunk),
3597 * or we're using inband tags, so we want to use the cache buffers.
3599 if (dev->param.nShortOpCaches > 0) {
3600 yaffs_ChunkCache *cache;
3601 /* If we can't find the data in the cache, then load the cache */
3602 cache = yaffs_FindChunkCache(in, chunk);
3605 && yaffs_CheckSpaceForAllocation(dev, 1)) {
3606 cache = yaffs_GrabChunkCache(dev);
3608 cache->chunkId = chunk;
3611 yaffs_ReadChunkDataFromObject(in, chunk,
3615 !yaffs_CheckSpaceForAllocation(dev, 1)) {
3616 /* Drop the cache if it was a read cache item and
3617 * no space check has been made for it.
3623 yaffs_UseChunkCache(dev, cache, 1);
3627 memcpy(&cache->data[start], buffer,
3632 cache->nBytes = nToWriteBack;
3636 yaffs_WriteChunkDataToObject
3639 cache->data, cache->nBytes,
3645 chunkWritten = -1; /* fail the write */
3648 /* An incomplete start or end chunk (or maybe both start and end chunk)
3649 * Read into the local buffer then copy, then copy over and write back.
3653 yaffs_GetTempBuffer(dev, __LINE__);
3655 yaffs_ReadChunkDataFromObject(in, chunk,
3660 memcpy(&localBuffer[start], buffer, nToCopy);
3663 yaffs_WriteChunkDataToObject(in, chunk,
3668 yaffs_ReleaseTempBuffer(dev, localBuffer,
3674 /* A full chunk. Write directly from the supplied buffer. */
3679 yaffs_WriteChunkDataToObject(in, chunk, buffer,
3680 dev->nDataBytesPerChunk,
3683 /* Since we've overwritten the cached data, we better invalidate it. */
3684 yaffs_InvalidateChunkCache(in, chunk);
3687 if (chunkWritten >= 0) {
3696 /* Update file object */
3698 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3699 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3706 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3707 int nBytes, int writeThrough)
3709 yaffs2_HandleHole(in,offset);
3710 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
3715 /* ---------------------- File resizing stuff ------------------ */
3717 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
3720 yaffs_Device *dev = in->myDev;
3721 int oldFileSize = in->variant.fileVariant.fileSize;
3723 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
3725 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
3726 dev->nDataBytesPerChunk;
3730 /* Delete backwards so that we don't end up with holes if
3731 * power is lost part-way through the operation.
3733 for (i = lastDel; i >= startDel; i--) {
3734 /* NB this could be optimised somewhat,
3735 * eg. could retrieve the tags and write them without
3736 * using yaffs_DeleteChunk
3739 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3742 (dev->internalStartBlock * dev->param.nChunksPerBlock)
3744 ((dev->internalEndBlock +
3745 1) * dev->param.nChunksPerBlock)) {
3746 T(YAFFS_TRACE_ALWAYS,
3747 (TSTR("Found daft chunkId %d for %d" TENDSTR),
3751 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3759 void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
3762 __u32 newSizeOfPartialChunk;
3763 yaffs_Device *dev = obj->myDev;
3765 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
3767 yaffs_PruneResizedChunks(obj, newSize);
3769 if (newSizeOfPartialChunk != 0) {
3770 int lastChunk = 1 + newFullChunks;
3771 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3773 /* Got to read and rewrite the last chunk with its new size and zero pad */
3774 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
3775 memset(localBuffer + newSizeOfPartialChunk, 0,
3776 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
3778 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
3779 newSizeOfPartialChunk, 1);
3781 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3784 obj->variant.fileVariant.fileSize = newSize;
3786 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
3790 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
3792 yaffs_Device *dev = in->myDev;
3793 int oldFileSize = in->variant.fileVariant.fileSize;
3795 yaffs_FlushFilesChunkCache(in);
3796 yaffs_InvalidateWholeChunkCache(in);
3798 yaffs_CheckGarbageCollection(dev,0);
3800 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3803 if (newSize == oldFileSize)
3806 if(newSize > oldFileSize){
3807 yaffs2_HandleHole(in,newSize);
3808 in->variant.fileVariant.fileSize = newSize;
3810 /* newSize < oldFileSize */
3811 yaffs_ResizeDown(in, newSize);
3814 /* Write a new object header to reflect the resize.
3815 * show we've shrunk the file, if need be
3816 * Do this only if the file is not in the deleted directories
3817 * and is not shadowed.
3821 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3822 in->parent->objectId != YAFFS_OBJECTID_DELETED)
3823 yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL);
3829 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3831 YCHAR *alias = NULL;
3832 obj = yaffs_GetEquivalentObject(obj);
3834 switch (obj->variantType) {
3835 case YAFFS_OBJECT_TYPE_FILE:
3836 return obj->variant.fileVariant.fileSize;
3837 case YAFFS_OBJECT_TYPE_SYMLINK:
3838 alias = obj->variant.symLinkVariant.alias;
3841 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
3849 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
3853 yaffs_FlushFilesChunkCache(in);
3854 if(dataSync) /* Only sync data */
3858 #ifdef CONFIG_YAFFS_WINCE
3859 yfsd_WinFileTimeNow(in->win_mtime);
3862 in->yst_mtime = Y_CURRENT_TIME;
3867 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL) >=
3868 0) ? YAFFS_OK : YAFFS_FAIL;
3878 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3881 /* First off, invalidate the file's data in the cache, without flushing. */
3882 yaffs_InvalidateWholeChunkCache(in);
3884 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3885 /* Move to the unlinked directory so we have a record that it was deleted. */
3886 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
3890 yaffs_RemoveObjectFromDirectory(in);
3891 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
3894 yaffs_FreeObject(in);
3899 /* yaffs_DeleteFile deletes the whole file data
3900 * and the inode associated with the file.
3901 * It does not delete the links associated with the file.
3903 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
3907 int immediateDeletion = 0;
3908 yaffs_Device *dev = in->myDev;
3911 immediateDeletion = 1;
3913 if (immediateDeletion) {
3915 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3916 _Y("deleted"), 0, 0);
3917 T(YAFFS_TRACE_TRACING,
3918 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3921 in->myDev->nDeletedFiles++;
3922 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3923 yaffs_ResizeFile(in, 0);
3924 yaffs_SoftDeleteFile(in);
3927 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3928 _Y("unlinked"), 0, 0);
3935 int yaffs_DeleteFile(yaffs_Object *in)
3937 int retVal = YAFFS_OK;
3938 int deleted; /* Need to cache value on stack if in is freed */
3939 yaffs_Device *dev = in->myDev;
3941 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3942 yaffs_ResizeFile(in, 0);
3944 if (in->nDataChunks > 0) {
3945 /* Use soft deletion if there is data in the file.
3946 * That won't be the case if it has been resized to zero.
3949 retVal = yaffs_UnlinkFileIfNeeded(in);
3951 deleted = in->deleted;
3953 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3956 in->myDev->nDeletedFiles++;
3957 yaffs_SoftDeleteFile(in);
3959 return deleted ? YAFFS_OK : YAFFS_FAIL;
3961 /* The file has no data chunks so we toss it immediately */
3962 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3963 in->variant.fileVariant.top = NULL;
3964 yaffs_DoGenericObjectDeletion(in);
3970 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
3972 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3973 !(ylist_empty(&obj->variant.directoryVariant.children));
3976 static int yaffs_DeleteDirectory(yaffs_Object *obj)
3978 /* First check that the directory is empty. */
3979 if (yaffs_IsNonEmptyDirectory(obj))
3982 return yaffs_DoGenericObjectDeletion(obj);
3985 static int yaffs_DeleteSymLink(yaffs_Object *in)
3987 if(in->variant.symLinkVariant.alias)
3988 YFREE(in->variant.symLinkVariant.alias);
3989 in->variant.symLinkVariant.alias=NULL;
3991 return yaffs_DoGenericObjectDeletion(in);
3994 static int yaffs_DeleteHardLink(yaffs_Object *in)
3996 /* remove this hardlink from the list assocaited with the equivalent
3999 ylist_del_init(&in->hardLinks);
4000 return yaffs_DoGenericObjectDeletion(in);
4003 int yaffs_DeleteObject(yaffs_Object *obj)
4006 switch (obj->variantType) {
4007 case YAFFS_OBJECT_TYPE_FILE:
4008 retVal = yaffs_DeleteFile(obj);
4010 case YAFFS_OBJECT_TYPE_DIRECTORY:
4011 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
4012 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
4013 ylist_del_init(&obj->variant.directoryVariant.dirty);
4015 return yaffs_DeleteDirectory(obj);
4017 case YAFFS_OBJECT_TYPE_SYMLINK:
4018 retVal = yaffs_DeleteSymLink(obj);
4020 case YAFFS_OBJECT_TYPE_HARDLINK:
4021 retVal = yaffs_DeleteHardLink(obj);
4023 case YAFFS_OBJECT_TYPE_SPECIAL:
4024 retVal = yaffs_DoGenericObjectDeletion(obj);
4026 case YAFFS_OBJECT_TYPE_UNKNOWN:
4028 break; /* should not happen. */
4034 static int yaffs_UnlinkWorker(yaffs_Object *obj)
4037 int immediateDeletion = 0;
4040 immediateDeletion = 1;
4043 yaffs_UpdateParent(obj->parent);
4045 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4046 return yaffs_DeleteHardLink(obj);
4047 } else if (!ylist_empty(&obj->hardLinks)) {
4048 /* Curve ball: We're unlinking an object that has a hardlink.
4050 * This problem arises because we are not strictly following
4051 * The Linux link/inode model.
4053 * We can't really delete the object.
4054 * Instead, we do the following:
4055 * - Select a hardlink.
4056 * - Unhook it from the hard links
4057 * - Move it from its parent directory (so that the rename can work)
4058 * - Rename the object to the hardlink's name.
4059 * - Delete the hardlink
4063 yaffs_Object *parent;
4065 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4067 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4069 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4070 parent = hl->parent;
4072 ylist_del_init(&hl->hardLinks);
4074 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
4076 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
4078 if (retVal == YAFFS_OK)
4079 retVal = yaffs_DoGenericObjectDeletion(hl);
4083 } else if (immediateDeletion) {
4084 switch (obj->variantType) {
4085 case YAFFS_OBJECT_TYPE_FILE:
4086 return yaffs_DeleteFile(obj);
4088 case YAFFS_OBJECT_TYPE_DIRECTORY:
4089 ylist_del_init(&obj->variant.directoryVariant.dirty);
4090 return yaffs_DeleteDirectory(obj);
4092 case YAFFS_OBJECT_TYPE_SYMLINK:
4093 return yaffs_DeleteSymLink(obj);
4095 case YAFFS_OBJECT_TYPE_SPECIAL:
4096 return yaffs_DoGenericObjectDeletion(obj);
4098 case YAFFS_OBJECT_TYPE_HARDLINK:
4099 case YAFFS_OBJECT_TYPE_UNKNOWN:
4103 } else if(yaffs_IsNonEmptyDirectory(obj))
4106 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
4107 _Y("unlinked"), 0, 0);
4111 static int yaffs_UnlinkObject(yaffs_Object *obj)
4114 if (obj && obj->unlinkAllowed)
4115 return yaffs_UnlinkWorker(obj);
4120 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
4124 obj = yaffs_FindObjectByName(dir, name);
4125 return yaffs_UnlinkObject(obj);
4128 /*----------------------- Initialisation Scanning ---------------------- */
4130 void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
4131 int backwardScanning)
4135 if (!backwardScanning) {
4136 /* Handle YAFFS1 forward scanning case
4137 * For YAFFS1 we always do the deletion
4141 /* Handle YAFFS2 case (backward scanning)
4142 * If the shadowed object exists then ignore.
4144 obj = yaffs_FindObjectByNumber(dev, objId);
4149 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4150 * We put it in unlinked dir to be cleaned up after the scanning
4153 yaffs_FindOrCreateObjectByNumber(dev, objId,
4154 YAFFS_OBJECT_TYPE_FILE);
4157 obj->isShadowed = 1;
4158 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4159 obj->variant.fileVariant.shrinkSize = 0;
4160 obj->valid = 1; /* So that we don't read any other info for this file */
4165 void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4172 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4174 in = yaffs_FindObjectByNumber(dev,
4175 hl->variant.hardLinkVariant.
4176 equivalentObjectId);
4179 /* Add the hardlink pointers */
4180 hl->variant.hardLinkVariant.equivalentObject = in;
4181 ylist_add(&hl->hardLinks, &in->hardLinks);
4183 /* Todo Need to report/handle this better.
4184 * Got a problem... hardlink to a non-existant object
4186 hl->variant.hardLinkVariant.equivalentObject = NULL;
4187 YINIT_LIST_HEAD(&hl->hardLinks);
4194 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
4197 * Sort out state of unlinked and deleted objects after scanning.
4199 struct ylist_head *i;
4200 struct ylist_head *n;
4206 /* Soft delete all the unlinked files */
4207 ylist_for_each_safe(i, n,
4208 &dev->unlinkedDir->variant.directoryVariant.children) {
4210 l = ylist_entry(i, yaffs_Object, siblings);
4211 yaffs_DeleteObject(l);
4215 ylist_for_each_safe(i, n,
4216 &dev->deletedDir->variant.directoryVariant.children) {
4218 l = ylist_entry(i, yaffs_Object, siblings);
4219 yaffs_DeleteObject(l);
4226 * This code iterates through all the objects making sure that they are rooted.
4227 * Any unrooted objects are re-rooted in lost+found.
4228 * An object needs to be in one of:
4229 * - Directly under deleted, unlinked
4230 * - Directly or indirectly under root.
4233 * This code assumes that we don't ever change the current relationships between
4235 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
4236 * lostNfound->parent == rootDir
4238 * This fixes the problem where directories might have inadvertently been deleted
4239 * leaving the object "hanging" without being rooted in the directory tree.
4242 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
4244 return (obj == dev->deletedDir ||
4245 obj == dev->unlinkedDir||
4246 obj == dev->rootDir);
4249 static void yaffs_FixHangingObjects(yaffs_Device *dev)
4252 yaffs_Object *parent;
4254 struct ylist_head *lh;
4255 struct ylist_head *n;
4262 /* Iterate through the objects in each hash entry,
4263 * looking at each object.
4264 * Make sure it is rooted.
4267 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
4268 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
4270 obj = ylist_entry(lh, yaffs_Object, hashLink);
4271 parent= obj->parent;
4273 if(yaffs_HasNULLParent(dev,obj)){
4274 /* These directories are not hanging */
4277 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4279 else if(yaffs_HasNULLParent(dev,parent))
4283 * Need to follow the parent chain to see if it is hanging.
4288 while(parent != dev->rootDir &&
4290 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
4292 parent = parent->parent;
4295 if(parent != dev->rootDir)
4300 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
4302 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
4311 * Delete directory contents for cleaning up lost and found.
4313 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
4316 struct ylist_head *lh;
4317 struct ylist_head *n;
4319 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4322 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
4324 obj = ylist_entry(lh, yaffs_Object, siblings);
4325 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
4326 yaffs_DeleteDirectoryContents(obj);
4329 (TSTR("Deleting lost_found object %d" TENDSTR),
4332 /* Need to use UnlinkObject since Delete would not handle
4333 * hardlinked objects correctly.
4335 yaffs_UnlinkObject(obj);
4341 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
4343 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
4346 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4349 yaffs_ObjectHeader *oh;
4351 yaffs_ExtendedTags tags;
4353 int alloc_failed = 0;
4361 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
4363 in->lazyLoaded ? "not yet" : "already"));
4366 if (in->lazyLoaded && in->hdrChunk > 0) {
4368 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4370 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
4371 oh = (yaffs_ObjectHeader *) chunkData;
4373 in->yst_mode = oh->yst_mode;
4374 #ifdef CONFIG_YAFFS_WINCE
4375 in->win_atime[0] = oh->win_atime[0];
4376 in->win_ctime[0] = oh->win_ctime[0];
4377 in->win_mtime[0] = oh->win_mtime[0];
4378 in->win_atime[1] = oh->win_atime[1];
4379 in->win_ctime[1] = oh->win_ctime[1];
4380 in->win_mtime[1] = oh->win_mtime[1];
4382 in->yst_uid = oh->yst_uid;
4383 in->yst_gid = oh->yst_gid;
4384 in->yst_atime = oh->yst_atime;
4385 in->yst_mtime = oh->yst_mtime;
4386 in->yst_ctime = oh->yst_ctime;
4387 in->yst_rdev = oh->yst_rdev;
4390 yaffs_SetObjectNameFromOH(in, oh);
4392 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
4393 in->variant.symLinkVariant.alias =
4394 yaffs_CloneString(oh->alias);
4395 if (!in->variant.symLinkVariant.alias)
4396 alloc_failed = 1; /* Not returned to caller */
4399 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4403 /*------------------------------ Directory Functions ----------------------------- */
4406 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
4407 * link (ie. name) is created or deleted in the directory.
4410 * create dir/a : update dir's mtime/ctime
4411 * rm dir/a: update dir's mtime/ctime
4412 * modify dir/a: don't update dir's mtimme/ctime
4414 * This can be handled immediately or defered. Defering helps reduce the number
4415 * of updates when many files in a directory are changed within a brief period.
4417 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
4418 * called periodically.
4421 static void yaffs_UpdateParent(yaffs_Object *obj)
4426 #ifndef CONFIG_YAFFS_WINCE
4430 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
4431 if(dev->param.deferDirectoryUpdate){
4432 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
4434 if(ylist_empty(link)){
4435 ylist_add(link,&dev->dirtyDirectories);
4436 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
4440 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4444 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
4446 struct ylist_head *link;
4448 yaffs_DirectoryStructure *dS;
4449 yaffs_ObjectVariant *oV;
4451 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
4453 while(!ylist_empty(&dev->dirtyDirectories)){
4454 link = dev->dirtyDirectories.next;
4455 ylist_del_init(link);
4457 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
4458 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
4459 obj = ylist_entry(oV,yaffs_Object,variant);
4461 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
4464 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4468 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4470 yaffs_Device *dev = obj->myDev;
4471 yaffs_Object *parent;
4473 yaffs_VerifyObjectInDirectory(obj);
4474 parent = obj->parent;
4476 yaffs_VerifyDirectory(parent);
4478 if (dev && dev->param.removeObjectCallback)
4479 dev->param.removeObjectCallback(obj);
4482 ylist_del_init(&obj->siblings);
4485 yaffs_VerifyDirectory(parent);
4488 void yaffs_AddObjectToDirectory(yaffs_Object *directory,
4492 T(YAFFS_TRACE_ALWAYS,
4494 ("tragedy: Trying to add an object to a null pointer directory"
4499 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4500 T(YAFFS_TRACE_ALWAYS,
4502 ("tragedy: Trying to add an object to a non-directory"
4507 if (obj->siblings.prev == NULL) {
4508 /* Not initialised */
4513 yaffs_VerifyDirectory(directory);
4515 yaffs_RemoveObjectFromDirectory(obj);
4519 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
4520 obj->parent = directory;
4522 if (directory == obj->myDev->unlinkedDir
4523 || directory == obj->myDev->deletedDir) {
4525 obj->myDev->nUnlinkedFiles++;
4526 obj->renameAllowed = 0;
4529 yaffs_VerifyDirectory(directory);
4530 yaffs_VerifyObjectInDirectory(obj);
4533 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
4538 struct ylist_head *i;
4539 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4547 T(YAFFS_TRACE_ALWAYS,
4549 ("tragedy: yaffs_FindObjectByName: null pointer directory"
4554 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4555 T(YAFFS_TRACE_ALWAYS,
4557 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4561 sum = yaffs_CalcNameSum(name);
4563 ylist_for_each(i, &directory->variant.directoryVariant.children) {
4565 l = ylist_entry(i, yaffs_Object, siblings);
4567 if (l->parent != directory)
4570 yaffs_CheckObjectDetailsLoaded(l);
4572 /* Special case for lost-n-found */
4573 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4574 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
4576 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
4577 /* LostnFound chunk called Objxxx
4580 yaffs_GetObjectName(l, buffer,
4581 YAFFS_MAX_NAME_LENGTH + 1);
4582 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
4593 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
4594 int (*fn) (yaffs_Object *))
4596 struct ylist_head *i;
4600 T(YAFFS_TRACE_ALWAYS,
4602 ("tragedy: yaffs_FindObjectByName: null pointer directory"
4607 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4608 T(YAFFS_TRACE_ALWAYS,
4610 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4615 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
4617 l = ylist_entry(i, yaffs_Object, siblings);
4628 /* GetEquivalentObject dereferences any hard links to get to the
4632 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4634 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4635 /* We want the object id of the equivalent object, not this one */
4636 obj = obj->variant.hardLinkVariant.equivalentObject;
4637 yaffs_CheckObjectDetailsLoaded(obj);
4643 * A note or two on object names.
4644 * * If the object name is missing, we then make one up in the form objnnn
4646 * * ASCII names are stored in the object header's name field from byte zero
4647 * * Unicode names are historically stored starting from byte zero.
4649 * Then there are automatic Unicode names...
4650 * The purpose of these is to save names in a way that can be read as
4651 * ASCII or Unicode names as appropriate, thus allowing a Unicode and ASCII
4652 * system to share files.
4654 * These automatic unicode are stored slightly differently...
4655 * - If the name can fit in the ASCII character space then they are saved as
4656 * ascii names as per above.
4657 * - If the name needs Unicode then the name is saved in Unicode
4658 * starting at oh->name[1].
4661 static void yaffs_FixNullName(yaffs_Object * obj,YCHAR * name, int buffSize)
4663 /* Create an object name if we could not find one. */
4664 if(yaffs_strnlen(name,YAFFS_MAX_NAME_LENGTH) == 0){
4666 YCHAR numString[20];
4667 YCHAR *x = &numString[19];
4668 unsigned v = obj->objectId;
4672 *x = '0' + (v % 10);
4675 /* make up a name */
4676 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
4677 yaffs_strcat(locName,x);
4678 yaffs_strncpy(name, locName, buffSize - 1);
4682 static void yaffs_LoadNameFromObjectHeader(yaffs_Device *dev,YCHAR *name, const YCHAR *ohName, int bufferSize)
4684 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4685 if(dev->param.autoUnicode){
4687 /* It is an ASCII name, so do an ASCII to unicode conversion */
4688 const char *asciiOhName = (const char *)ohName;
4689 int n = bufferSize - 1;
4690 while(n > 0 && *asciiOhName){
4691 *name = *asciiOhName;
4697 yaffs_strncpy(name,ohName+1, bufferSize -1);
4700 yaffs_strncpy(name, ohName, bufferSize - 1);
4704 static void yaffs_LoadObjectHeaderFromName(yaffs_Device *dev, YCHAR *ohName, const YCHAR *name)
4706 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4711 if(dev->param.autoUnicode){
4716 /* Figure out if the name will fit in ascii character set */
4717 while(isAscii && *w){
4724 /* It is an ASCII name, so do a unicode to ascii conversion */
4725 char *asciiOhName = (char *)ohName;
4726 int n = YAFFS_MAX_NAME_LENGTH - 1;
4727 while(n > 0 && *name){
4728 *asciiOhName= *name;
4734 /* It is a unicode name, so save starting at the second YCHAR */
4736 yaffs_strncpy(ohName+1,name, YAFFS_MAX_NAME_LENGTH -2);
4741 yaffs_strncpy(ohName,name, YAFFS_MAX_NAME_LENGTH - 1);
4745 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
4747 memset(name, 0, buffSize * sizeof(YCHAR));
4749 yaffs_CheckObjectDetailsLoaded(obj);
4751 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4752 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
4754 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4755 else if (obj->shortName[0]) {
4756 yaffs_strcpy(name, obj->shortName);
4759 else if(obj->hdrChunk > 0) {
4761 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
4763 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
4765 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
4767 if (obj->hdrChunk > 0) {
4768 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
4769 obj->hdrChunk, buffer,
4772 yaffs_LoadNameFromObjectHeader(obj->myDev,name,oh->name,buffSize);
4774 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
4777 yaffs_FixNullName(obj,name,buffSize);
4779 return yaffs_strnlen(name,YAFFS_MAX_NAME_LENGTH);
4783 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4785 /* Dereference any hard linking */
4786 obj = yaffs_GetEquivalentObject(obj);
4788 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4789 return obj->variant.fileVariant.fileSize;
4790 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
4791 if(!obj->variant.symLinkVariant.alias)
4793 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
4795 /* Only a directory should drop through to here */
4796 return obj->myDev->nDataBytesPerChunk;
4800 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4803 struct ylist_head *i;
4806 count++; /* the object itself */
4808 ylist_for_each(i, &obj->hardLinks)
4809 count++; /* add the hard links; */
4814 int yaffs_GetObjectInode(yaffs_Object *obj)
4816 obj = yaffs_GetEquivalentObject(obj);
4818 return obj->objectId;
4821 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4823 obj = yaffs_GetEquivalentObject(obj);
4825 switch (obj->variantType) {
4826 case YAFFS_OBJECT_TYPE_FILE:
4829 case YAFFS_OBJECT_TYPE_DIRECTORY:
4832 case YAFFS_OBJECT_TYPE_SYMLINK:
4835 case YAFFS_OBJECT_TYPE_HARDLINK:
4838 case YAFFS_OBJECT_TYPE_SPECIAL:
4839 if (S_ISFIFO(obj->yst_mode))
4841 if (S_ISCHR(obj->yst_mode))
4843 if (S_ISBLK(obj->yst_mode))
4845 if (S_ISSOCK(obj->yst_mode))
4853 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4855 obj = yaffs_GetEquivalentObject(obj);
4856 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4857 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4859 return yaffs_CloneString(_Y(""));
4862 #ifndef CONFIG_YAFFS_WINCE
4864 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4866 unsigned int valid = attr->ia_valid;
4868 if (valid & ATTR_MODE)
4869 obj->yst_mode = attr->ia_mode;
4870 if (valid & ATTR_UID)
4871 obj->yst_uid = attr->ia_uid;
4872 if (valid & ATTR_GID)
4873 obj->yst_gid = attr->ia_gid;
4875 if (valid & ATTR_ATIME)
4876 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
4877 if (valid & ATTR_CTIME)
4878 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
4879 if (valid & ATTR_MTIME)
4880 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
4882 if (valid & ATTR_SIZE)
4883 yaffs_ResizeFile(obj, attr->ia_size);
4885 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0, NULL);
4890 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4892 unsigned int valid = 0;
4894 attr->ia_mode = obj->yst_mode;
4896 attr->ia_uid = obj->yst_uid;
4898 attr->ia_gid = obj->yst_gid;
4901 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
4902 valid |= ATTR_ATIME;
4903 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
4904 valid |= ATTR_CTIME;
4905 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
4906 valid |= ATTR_MTIME;
4908 attr->ia_size = yaffs_GetFileSize(obj);
4911 attr->ia_valid = valid;
4919 static int yaffs_DoXMod(yaffs_Object *obj, int set, const YCHAR *name, const void *value, int size, int flags)
4921 yaffs_XAttrMod xmod;
4930 xmod.result = -ENOSPC;
4932 result = yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, &xmod);
4940 static int yaffs_ApplyXMod(yaffs_Object *obj, char *buffer, yaffs_XAttrMod *xmod)
4943 int x_offs = sizeof(yaffs_ObjectHeader);
4944 yaffs_Device *dev = obj->myDev;
4945 int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4947 char * x_buffer = buffer + x_offs;
4950 retval = nval_set(x_buffer, x_size, xmod->name, xmod->data, xmod->size, xmod->flags);
4952 retval = nval_del(x_buffer, x_size, xmod->name);
4954 obj->hasXattr = nval_hasvalues(x_buffer, x_size);
4955 obj->xattrKnown = 1;
4957 xmod->result = retval;
4962 static int yaffs_DoXFetch(yaffs_Object *obj, const YCHAR *name, void *value, int size)
4964 char *buffer = NULL;
4966 yaffs_ExtendedTags tags;
4967 yaffs_Device *dev = obj->myDev;
4968 int x_offs = sizeof(yaffs_ObjectHeader);
4969 int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4975 if(obj->hdrChunk < 1)
4978 /* If we know that the object has no xattribs then don't do all the
4979 * reading and parsing.
4981 if(obj->xattrKnown && !obj->hasXattr){
4988 buffer = (char *) yaffs_GetTempBuffer(dev, __LINE__);
4992 result = yaffs_ReadChunkWithTagsFromNAND(dev,obj->hdrChunk, (__u8 *)buffer, &tags);
4994 if(result != YAFFS_OK)
4997 x_buffer = buffer + x_offs;
4999 if (!obj->xattrKnown){
5000 obj->hasXattr = nval_hasvalues(x_buffer, x_size);
5001 obj->xattrKnown = 1;
5005 retval = nval_get(x_buffer, x_size, name, value, size);
5007 retval = nval_list(x_buffer, x_size, value,size);
5009 yaffs_ReleaseTempBuffer(dev,(__u8 *)buffer,__LINE__);
5013 int yaffs_SetXAttribute(yaffs_Object *obj, const YCHAR *name, const void * value, int size, int flags)
5015 return yaffs_DoXMod(obj, 1, name, value, size, flags);
5018 int yaffs_RemoveXAttribute(yaffs_Object *obj, const YCHAR *name)
5020 return yaffs_DoXMod(obj, 0, name, NULL, 0, 0);
5023 int yaffs_GetXAttribute(yaffs_Object *obj, const YCHAR *name, void *value, int size)
5025 return yaffs_DoXFetch(obj, name, value, size);
5028 int yaffs_ListXAttributes(yaffs_Object *obj, char *buffer, int size)
5030 return yaffs_DoXFetch(obj, NULL, buffer,size);
5036 int yaffs_DumpObject(yaffs_Object *obj)
5040 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
5042 T(YAFFS_TRACE_ALWAYS,
5044 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5045 " chunk %d type %d size %d\n"
5046 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5047 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
5048 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5054 /*---------------------------- Initialisation code -------------------------------------- */
5056 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
5059 /* Common functions, gotta have */
5060 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
5063 #ifdef CONFIG_YAFFS_YAFFS2
5065 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5066 if (dev->param.writeChunkWithTagsToNAND &&
5067 dev->param.readChunkWithTagsFromNAND &&
5068 !dev->param.writeChunkToNAND &&
5069 !dev->param.readChunkFromNAND &&
5070 dev->param.markNANDBlockBad &&
5071 dev->param.queryNANDBlock)
5075 /* Can use the "spare" style interface for yaffs1 */
5076 if (!dev->param.isYaffs2 &&
5077 !dev->param.writeChunkWithTagsToNAND &&
5078 !dev->param.readChunkWithTagsFromNAND &&
5079 dev->param.writeChunkToNAND &&
5080 dev->param.readChunkFromNAND &&
5081 !dev->param.markNANDBlockBad &&
5082 !dev->param.queryNANDBlock)
5089 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
5091 /* Initialise the unlinked, deleted, root and lost and found directories */
5093 dev->lostNFoundDir = dev->rootDir = NULL;
5094 dev->unlinkedDir = dev->deletedDir = NULL;
5097 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5100 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5103 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5104 YAFFS_ROOT_MODE | S_IFDIR);
5105 dev->lostNFoundDir =
5106 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5107 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5109 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
5110 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5117 int yaffs_GutsInitialise(yaffs_Device *dev)
5119 int init_failed = 0;
5123 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5125 /* Check stuff that must be set */
5128 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5132 dev->internalStartBlock = dev->param.startBlock;
5133 dev->internalEndBlock = dev->param.endBlock;
5134 dev->blockOffset = 0;
5135 dev->chunkOffset = 0;
5136 dev->nFreeChunks = 0;
5140 if (dev->param.startBlock == 0) {
5141 dev->internalStartBlock = dev->param.startBlock + 1;
5142 dev->internalEndBlock = dev->param.endBlock + 1;
5143 dev->blockOffset = 1;
5144 dev->chunkOffset = dev->param.nChunksPerBlock;
5147 /* Check geometry parameters. */
5149 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
5150 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
5151 (dev->param.inbandTags && !dev->param.isYaffs2) ||
5152 dev->param.nChunksPerBlock < 2 ||
5153 dev->param.nReservedBlocks < 2 ||
5154 dev->internalStartBlock <= 0 ||
5155 dev->internalEndBlock <= 0 ||
5156 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
5157 T(YAFFS_TRACE_ALWAYS,
5159 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
5160 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
5164 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5165 T(YAFFS_TRACE_ALWAYS,
5166 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5170 /* Sort out space for inband tags, if required */
5171 if (dev->param.inbandTags)
5172 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
5174 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
5176 /* Got the right mix of functions? */
5177 if (!yaffs_CheckDevFunctions(dev)) {
5178 /* Function missing */
5179 T(YAFFS_TRACE_ALWAYS,
5181 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5186 /* This is really a compilation check. */
5187 if (!yaffs_CheckStructures()) {
5188 T(YAFFS_TRACE_ALWAYS,
5189 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5193 if (dev->isMounted) {
5194 T(YAFFS_TRACE_ALWAYS,
5195 (TSTR("yaffs: device already mounted\n" TENDSTR)));
5199 /* Finished with most checks. One or two more checks happen later on too. */
5203 /* OK now calculate a few things for the device */
5206 * Calculate all the chunk size manipulation numbers:
5208 x = dev->nDataBytesPerChunk;
5209 /* We always use dev->chunkShift and dev->chunkDiv */
5210 dev->chunkShift = Shifts(x);
5211 x >>= dev->chunkShift;
5213 /* We only use chunk mask if chunkDiv is 1 */
5214 dev->chunkMask = (1<<dev->chunkShift) - 1;
5217 * Calculate chunkGroupBits.
5218 * We need to find the next power of 2 > than internalEndBlock
5221 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
5225 /* Set up tnode width if wide tnodes are enabled. */
5226 if (!dev->param.wideTnodesDisabled) {
5227 /* bits must be even so that we end up with 32-bit words */
5231 dev->tnodeWidth = 16;
5233 dev->tnodeWidth = bits;
5235 dev->tnodeWidth = 16;
5237 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5239 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5240 * so if the bitwidth of the
5241 * chunk range we're using is greater than 16 we need
5242 * to figure out chunk shift and chunkGroupSize
5245 if (bits <= dev->tnodeWidth)
5246 dev->chunkGroupBits = 0;
5248 dev->chunkGroupBits = bits - dev->tnodeWidth;
5250 dev->tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
5251 if(dev->tnodeSize < sizeof(yaffs_Tnode))
5252 dev->tnodeSize = sizeof(yaffs_Tnode);
5254 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5256 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
5257 /* We have a problem because the soft delete won't work if
5258 * the chunk group size > chunks per block.
5259 * This can be remedied by using larger "virtual blocks".
5261 T(YAFFS_TRACE_ALWAYS,
5262 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5267 /* OK, we've finished verifying the device, lets continue with initialisation */
5269 /* More device initialisation */
5271 dev->passiveGCs = 0;
5272 dev->oldestDirtyGCs = 0;
5273 dev->backgroundGCs = 0;
5274 dev->gcBlockFinder = 0;
5275 dev->bufferedBlock = -1;
5276 dev->doingBufferedBlockRewrite = 0;
5277 dev->nDeletedFiles = 0;
5278 dev->nBackgroundDeletions = 0;
5279 dev->nUnlinkedFiles = 0;
5281 dev->eccUnfixed = 0;
5282 dev->tagsEccFixed = 0;
5283 dev->tagsEccUnfixed = 0;
5284 dev->nErasureFailures = 0;
5285 dev->nErasedBlocks = 0;
5287 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
5288 YINIT_LIST_HEAD(&dev->dirtyDirectories);
5289 dev->oldestDirtySequence = 0;
5290 dev->oldestDirtyBlock = 0;
5292 /* Initialise temporary buffers and caches. */
5293 if (!yaffs_InitialiseTempBuffers(dev))
5296 dev->srCache = NULL;
5297 dev->gcCleanupList = NULL;
5301 dev->param.nShortOpCaches > 0) {
5304 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
5306 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
5307 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5309 dev->srCache = YMALLOC(srCacheBytes);
5311 buf = (__u8 *) dev->srCache;
5314 memset(dev->srCache, 0, srCacheBytes);
5316 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
5317 dev->srCache[i].object = NULL;
5318 dev->srCache[i].lastUse = 0;
5319 dev->srCache[i].dirty = 0;
5320 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
5331 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
5332 if (!dev->gcCleanupList)
5336 if (dev->param.isYaffs2)
5337 dev->param.useHeaderFileSize = 1;
5339 if (!init_failed && !yaffs_InitialiseBlocks(dev))
5342 yaffs_InitialiseTnodesAndObjects(dev);
5344 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5349 /* Now scan the flash. */
5350 if (dev->param.isYaffs2) {
5351 if (yaffs2_CheckpointRestore(dev)) {
5352 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
5353 T(YAFFS_TRACE_ALWAYS,
5354 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
5357 /* Clean up the mess caused by an aborted checkpoint load
5358 * and scan backwards.
5360 yaffs_DeinitialiseBlocks(dev);
5362 yaffs_DeinitialiseTnodesAndObjects(dev);
5364 dev->nErasedBlocks = 0;
5365 dev->nFreeChunks = 0;
5366 dev->allocationBlock = -1;
5367 dev->allocationPage = -1;
5368 dev->nDeletedFiles = 0;
5369 dev->nUnlinkedFiles = 0;
5370 dev->nBackgroundDeletions = 0;
5372 if (!init_failed && !yaffs_InitialiseBlocks(dev))
5375 yaffs_InitialiseTnodesAndObjects(dev);
5377 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5380 if (!init_failed && !yaffs2_ScanBackwards(dev))
5383 } else if (!yaffs1_Scan(dev))
5386 yaffs_StripDeletedObjects(dev);
5387 yaffs_FixHangingObjects(dev);
5388 if(dev->param.emptyLostAndFound)
5389 yaffs_EmptyLostAndFound(dev);
5393 /* Clean up the mess */
5394 T(YAFFS_TRACE_TRACING,
5395 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
5397 yaffs_Deinitialise(dev);
5401 /* Zero out stats */
5402 dev->nPageReads = 0;
5403 dev->nPageWrites = 0;
5404 dev->nBlockErasures = 0;
5406 dev->nRetriedWrites = 0;
5408 dev->nRetiredBlocks = 0;
5410 yaffs_VerifyFreeChunks(dev);
5411 yaffs_VerifyBlocks(dev);
5413 /* Clean up any aborted checkpoint data */
5414 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
5415 yaffs2_InvalidateCheckpoint(dev);
5417 T(YAFFS_TRACE_TRACING,
5418 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5423 void yaffs_Deinitialise(yaffs_Device *dev)
5425 if (dev->isMounted) {
5428 yaffs_DeinitialiseBlocks(dev);
5429 yaffs_DeinitialiseTnodesAndObjects(dev);
5430 if (dev->param.nShortOpCaches > 0 &&
5433 for (i = 0; i < dev->param.nShortOpCaches; i++) {
5434 if (dev->srCache[i].data)
5435 YFREE(dev->srCache[i].data);
5436 dev->srCache[i].data = NULL;
5439 YFREE(dev->srCache);
5440 dev->srCache = NULL;
5443 YFREE(dev->gcCleanupList);
5445 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5446 YFREE(dev->tempBuffer[i].buffer);
5450 if (dev->param.deinitialiseNAND)
5451 dev->param.deinitialiseNAND(dev);
5455 int yaffs_CountFreeChunks(yaffs_Device *dev)
5460 yaffs_BlockInfo *blk;
5462 blk = dev->blockInfo;
5463 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
5464 switch (blk->blockState) {
5465 case YAFFS_BLOCK_STATE_EMPTY:
5466 case YAFFS_BLOCK_STATE_ALLOCATING:
5467 case YAFFS_BLOCK_STATE_COLLECTING:
5468 case YAFFS_BLOCK_STATE_FULL:
5470 (dev->param.nChunksPerBlock - blk->pagesInUse +
5471 blk->softDeletions);
5482 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
5484 /* This is what we report to the outside world */
5487 int nDirtyCacheChunks;
5488 int blocksForCheckpoint;
5492 nFree = dev->nFreeChunks;
5494 nFree = yaffs_CountFreeChunks(dev);
5497 nFree += dev->nDeletedFiles;
5499 /* Now count the number of dirty chunks in the cache and subtract those */
5501 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
5502 if (dev->srCache[i].dirty)
5503 nDirtyCacheChunks++;
5506 nFree -= nDirtyCacheChunks;
5508 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
5510 /* Now we figure out how much to reserve for the checkpoint and report that... */
5511 blocksForCheckpoint = yaffs2_CalcCheckpointBlocksRequired(dev);
5513 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
5523 /*---------------------------------------- YAFFS test code ----------------------*/
5525 #define yaffs_CheckStruct(structure, syze, name) \
5527 if (sizeof(structure) != syze) { \
5528 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
5529 name, syze, (int) sizeof(structure))); \
5530 return YAFFS_FAIL; \
5534 static int yaffs_CheckStructures(void)
5536 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
5537 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
5538 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
5539 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
5541 #ifndef CONFIG_YAFFS_WINCE
5542 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");