2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2010 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
14 #include "yaffs_trace.h"
16 #include "yaffsinterface.h"
17 #include "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
21 #include "yaffs_tagscompat.h"
22 #ifndef CONFIG_YAFFS_USE_OWN_SORT
23 #include "yaffs_qsort.h"
25 #include "yaffs_nand.h"
27 #include "yaffs_checkptrw.h"
29 #include "yaffs_nand.h"
30 #include "yaffs_packedtags2.h"
32 #include "yaffs_nameval.h"
35 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
36 #define YAFFS_GC_GOOD_ENOUGH 2
37 #define YAFFS_GC_PASSIVE_THRESHOLD 4
39 #define YAFFS_SMALL_HOLE_THRESHOLD 3
42 * Checkpoints are really no benefit on very small partitions.
44 * To save space on small partitions don't bother with checkpoints unless
45 * the partition is at least this big.
47 #define YAFFS_CHECKPOINT_MIN_BLOCKS 60
49 #include "yaffs_ecc.h"
51 /* Private structure for doing xattr modifications */
53 int set; /* If 0 then this is a deletion */
61 /* Robustification (if it ever comes about...) */
62 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
63 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
65 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
67 const yaffs_ExtendedTags *tags);
68 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
69 const yaffs_ExtendedTags *tags);
71 /* Other local prototypes */
72 static void yaffs_UpdateParent(yaffs_Object *obj);
73 static int yaffs_UnlinkObject(yaffs_Object *obj);
74 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
76 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
78 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
80 yaffs_ExtendedTags *tags,
82 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
83 int chunkInNAND, int inScan);
85 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
86 yaffs_ObjectType type);
87 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
89 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
90 int force, int isShrink, int shadows, yaffs_XAttrMod *xop);
91 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod);
93 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
94 static int yaffs_CheckStructures(void);
95 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
97 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
100 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
103 static int yaffs_UnlinkWorker(yaffs_Object *obj);
105 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
108 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
109 yaffs_BlockInfo **blockUsedPtr);
111 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
113 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
115 static void yaffs_VerifyDirectory(yaffs_Object *directory);
116 #ifdef YAFFS_PARANOID
117 static int yaffs_CheckFileSanity(yaffs_Object *in);
119 #define yaffs_CheckFileSanity(in)
122 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
123 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
125 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
127 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
128 yaffs_ExtendedTags *tags);
130 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
132 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
133 yaffs_FileStructure *fStruct,
136 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize);
137 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
138 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
141 yaffs_ExtendedTags *tags);
143 /* Function to calculate chunk and offset */
145 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
151 chunk = (__u32)(addr >> dev->chunkShift);
153 if (dev->chunkDiv == 1) {
154 /* easy power of 2 case */
155 offset = (__u32)(addr & dev->chunkMask);
157 /* Non power-of-2 case */
161 chunk /= dev->chunkDiv;
163 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
164 offset = (__u32)(addr - chunkBase);
171 /* Function to return the number of shifts for a power of 2 greater than or
172 * equal to the given number
173 * Note we don't try to cater for all possible numbers and this does not have to
174 * be hellishly efficient.
177 static __u32 ShiftsGE(__u32 x)
182 nShifts = extraBits = 0;
197 /* Function to return the number of shifts to get a 1 in bit 0
200 static __u32 Shifts(__u32 x)
220 * Temporary buffer manipulations.
223 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
226 __u8 *buf = (__u8 *)1;
228 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
230 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
231 dev->tempBuffer[i].line = 0; /* not in use */
232 dev->tempBuffer[i].buffer = buf =
233 YMALLOC_DMA(dev->param.totalBytesPerChunk);
236 return buf ? YAFFS_OK : YAFFS_FAIL;
239 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
244 if (dev->tempInUse > dev->maxTemp)
245 dev->maxTemp = dev->tempInUse;
247 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
248 if (dev->tempBuffer[i].line == 0) {
249 dev->tempBuffer[i].line = lineNo;
250 if ((i + 1) > dev->maxTemp) {
251 dev->maxTemp = i + 1;
252 for (j = 0; j <= i; j++)
253 dev->tempBuffer[j].maxLine =
254 dev->tempBuffer[j].line;
257 return dev->tempBuffer[i].buffer;
261 T(YAFFS_TRACE_BUFFERS,
262 (TSTR("Out of temp buffers at line %d, other held by lines:"),
264 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
265 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
267 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
270 * If we got here then we have to allocate an unmanaged one
274 dev->unmanagedTempAllocations++;
275 return YMALLOC(dev->nDataBytesPerChunk);
279 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
286 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
287 if (dev->tempBuffer[i].buffer == buffer) {
288 dev->tempBuffer[i].line = 0;
294 /* assume it is an unmanaged one. */
295 T(YAFFS_TRACE_BUFFERS,
296 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
299 dev->unmanagedTempDeallocations++;
305 * Determine if we have a managed buffer.
307 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
311 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
312 if (dev->tempBuffer[i].buffer == buffer)
316 for (i = 0; i < dev->param.nShortOpCaches; i++) {
317 if (dev->srCache[i].data == buffer)
321 if (buffer == dev->checkpointBuffer)
324 T(YAFFS_TRACE_ALWAYS,
325 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
332 * Chunk bitmap manipulations
335 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
337 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
339 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
343 return dev->chunkBits +
344 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
347 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
349 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
350 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
352 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
358 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
360 __u8 *blkBits = yaffs_BlockBits(dev, blk);
362 memset(blkBits, 0, dev->chunkBitmapStride);
365 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
367 __u8 *blkBits = yaffs_BlockBits(dev, blk);
369 yaffs_VerifyChunkBitId(dev, blk, chunk);
371 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
374 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
376 __u8 *blkBits = yaffs_BlockBits(dev, blk);
378 yaffs_VerifyChunkBitId(dev, blk, chunk);
380 blkBits[chunk / 8] |= (1 << (chunk & 7));
383 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
385 __u8 *blkBits = yaffs_BlockBits(dev, blk);
386 yaffs_VerifyChunkBitId(dev, blk, chunk);
388 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
391 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
393 __u8 *blkBits = yaffs_BlockBits(dev, blk);
395 for (i = 0; i < dev->chunkBitmapStride; i++) {
403 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
405 __u8 *blkBits = yaffs_BlockBits(dev, blk);
408 for (i = 0; i < dev->chunkBitmapStride; i++) {
425 static int yaffs_SkipVerification(yaffs_Device *dev)
428 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
431 static int yaffs_SkipFullVerification(yaffs_Device *dev)
434 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
437 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
440 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
443 static const char *blockStateName[] = {
456 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
461 if (yaffs_SkipVerification(dev))
464 /* Report illegal runtime states */
465 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
466 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
468 switch (bi->blockState) {
469 case YAFFS_BLOCK_STATE_UNKNOWN:
470 case YAFFS_BLOCK_STATE_SCANNING:
471 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
472 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
473 n, blockStateName[bi->blockState]));
476 /* Check pages in use and soft deletions are legal */
478 actuallyUsed = bi->pagesInUse - bi->softDeletions;
480 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
481 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
482 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
483 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
484 n, bi->pagesInUse, bi->softDeletions));
487 /* Check chunk bitmap legal */
488 inUse = yaffs_CountChunkBits(dev, n);
489 if (inUse != bi->pagesInUse)
490 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
491 n, bi->pagesInUse, inUse));
493 /* Check that the sequence number is valid.
494 * Ten million is legal, but is very unlikely
496 if (dev->param.isYaffs2 &&
497 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
498 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
499 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
500 n, bi->sequenceNumber));
503 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
506 yaffs_VerifyBlock(dev, bi, n);
508 /* After collection the block should be in the erased state */
509 /* This will need to change if we do partial gc */
511 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
512 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
513 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
518 static void yaffs_VerifyBlocks(yaffs_Device *dev)
521 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
522 int nIllegalBlockStates = 0;
524 if (yaffs_SkipVerification(dev))
527 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
529 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
530 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
531 yaffs_VerifyBlock(dev, bi, i);
533 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
534 nBlocksPerState[bi->blockState]++;
536 nIllegalBlockStates++;
539 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
540 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
542 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
543 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
544 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
546 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
547 T(YAFFS_TRACE_VERIFY,
548 (TSTR("%s %d blocks"TENDSTR),
549 blockStateName[i], nBlocksPerState[i]));
551 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
552 T(YAFFS_TRACE_VERIFY,
553 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
554 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
556 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
557 T(YAFFS_TRACE_VERIFY,
558 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
559 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
561 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
562 T(YAFFS_TRACE_VERIFY,
563 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
564 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
566 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
571 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
572 * case those tests will not be performed.
574 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
576 if (obj && yaffs_SkipVerification(obj->myDev))
579 if (!(tags && obj && oh)) {
580 T(YAFFS_TRACE_VERIFY,
581 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
586 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
587 oh->type > YAFFS_OBJECT_TYPE_MAX)
588 T(YAFFS_TRACE_VERIFY,
589 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
590 tags->objectId, oh->type));
592 if (tags->objectId != obj->objectId)
593 T(YAFFS_TRACE_VERIFY,
594 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
595 tags->objectId, obj->objectId));
599 * Check that the object's parent ids match if parentCheck requested.
601 * Tests do not apply to the root object.
604 if (parentCheck && tags->objectId > 1 && !obj->parent)
605 T(YAFFS_TRACE_VERIFY,
606 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
607 tags->objectId, oh->parentObjectId));
609 if (parentCheck && obj->parent &&
610 oh->parentObjectId != obj->parent->objectId &&
611 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
612 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
613 T(YAFFS_TRACE_VERIFY,
614 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
615 tags->objectId, oh->parentObjectId, obj->parent->objectId));
617 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
618 T(YAFFS_TRACE_VERIFY,
619 (TSTR("Obj %d header name is NULL"TENDSTR),
622 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
623 T(YAFFS_TRACE_VERIFY,
624 (TSTR("Obj %d header name is 0xFF"TENDSTR),
630 /* Not being used, but don't want to throw away yet */
631 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
632 __u32 level, int chunkOffset)
635 yaffs_Device *dev = obj->myDev;
641 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
642 if (tn->internal[i]) {
643 ok = yaffs_VerifyTnodeWorker(obj,
646 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
649 } else if (level == 0) {
650 yaffs_ExtendedTags tags;
651 __u32 objectId = obj->objectId;
653 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
655 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
656 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
659 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
660 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
661 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
662 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
663 objectId, chunkOffset, theChunk,
664 tags.objectId, tags.chunkId));
678 static void yaffs_VerifyFile(yaffs_Object *obj)
680 int requiredTallness;
686 yaffs_ExtendedTags tags;
693 if (yaffs_SkipVerification(obj->myDev))
697 objectId = obj->objectId;
699 /* Check file size is consistent with tnode depth */
700 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
701 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
702 requiredTallness = 0;
704 x >>= YAFFS_TNODES_INTERNAL_BITS;
708 actualTallness = obj->variant.fileVariant.topLevel;
710 /* Check that the chunks in the tnode tree are all correct.
711 * We do this by scanning through the tnode tree and
712 * checking the tags for every chunk match.
715 if (yaffs_SkipNANDVerification(dev))
718 for (i = 1; i <= lastChunk; i++) {
719 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
722 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
724 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
725 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
726 if (tags.objectId != objectId || tags.chunkId != i) {
727 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
728 objectId, i, theChunk,
729 tags.objectId, tags.chunkId));
737 static void yaffs_VerifyHardLink(yaffs_Object *obj)
739 if (obj && yaffs_SkipVerification(obj->myDev))
742 /* Verify sane equivalent object */
745 static void yaffs_VerifySymlink(yaffs_Object *obj)
747 if (obj && yaffs_SkipVerification(obj->myDev))
750 /* Verify symlink string */
753 static void yaffs_VerifySpecial(yaffs_Object *obj)
755 if (obj && yaffs_SkipVerification(obj->myDev))
759 static void yaffs_VerifyObject(yaffs_Object *obj)
768 __u32 chunkShouldNotBeDeleted;
774 if (obj->beingCreated)
779 if (yaffs_SkipVerification(dev))
782 /* Check sane object header chunk */
784 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
785 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
787 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
788 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
789 chunkValid = chunkInRange &&
790 yaffs_CheckChunkBit(dev,
791 obj->hdrChunk / dev->param.nChunksPerBlock,
792 obj->hdrChunk % dev->param.nChunksPerBlock);
793 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
796 (!chunkIdOk || chunkShouldNotBeDeleted)) {
797 T(YAFFS_TRACE_VERIFY,
798 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
799 obj->objectId, obj->hdrChunk,
800 chunkIdOk ? "" : ",out of range",
801 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
804 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
805 yaffs_ExtendedTags tags;
806 yaffs_ObjectHeader *oh;
807 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
809 oh = (yaffs_ObjectHeader *)buffer;
811 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
814 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
816 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
819 /* Verify it has a parent */
820 if (obj && !obj->fake &&
821 (!obj->parent || obj->parent->myDev != dev)) {
822 T(YAFFS_TRACE_VERIFY,
823 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
824 obj->objectId, obj->parent));
827 /* Verify parent is a directory */
828 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
829 T(YAFFS_TRACE_VERIFY,
830 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
831 obj->objectId, obj->parent->variantType));
834 switch (obj->variantType) {
835 case YAFFS_OBJECT_TYPE_FILE:
836 yaffs_VerifyFile(obj);
838 case YAFFS_OBJECT_TYPE_SYMLINK:
839 yaffs_VerifySymlink(obj);
841 case YAFFS_OBJECT_TYPE_DIRECTORY:
842 yaffs_VerifyDirectory(obj);
844 case YAFFS_OBJECT_TYPE_HARDLINK:
845 yaffs_VerifyHardLink(obj);
847 case YAFFS_OBJECT_TYPE_SPECIAL:
848 yaffs_VerifySpecial(obj);
850 case YAFFS_OBJECT_TYPE_UNKNOWN:
852 T(YAFFS_TRACE_VERIFY,
853 (TSTR("Obj %d has illegaltype %d"TENDSTR),
854 obj->objectId, obj->variantType));
859 static void yaffs_VerifyObjects(yaffs_Device *dev)
863 struct ylist_head *lh;
865 if (yaffs_SkipVerification(dev))
868 /* Iterate through the objects in each hash entry */
870 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
871 ylist_for_each(lh, &dev->objectBucket[i].list) {
873 obj = ylist_entry(lh, yaffs_Object, hashLink);
874 yaffs_VerifyObject(obj);
882 * Simple hash function. Needs to have a reasonable spread
885 static Y_INLINE int yaffs_HashFunction(int n)
888 return n % YAFFS_NOBJECT_BUCKETS;
892 * Access functions to useful fake objects.
893 * Note that root might have a presence in NAND if permissions are set.
896 yaffs_Object *yaffs_Root(yaffs_Device *dev)
901 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
903 return dev->lostNFoundDir;
908 * Erased NAND checking functions
911 int yaffs_CheckFF(__u8 *buffer, int nBytes)
913 /* Horrible, slow implementation */
922 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
925 int retval = YAFFS_OK;
926 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
927 yaffs_ExtendedTags tags;
930 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
932 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
935 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
936 T(YAFFS_TRACE_NANDACCESS,
937 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
941 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
948 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
951 yaffs_ExtendedTags *tags)
953 int retval = YAFFS_OK;
954 yaffs_ExtendedTags tempTags;
955 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
958 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
959 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
960 tempTags.objectId != tags->objectId ||
961 tempTags.chunkId != tags->chunkId ||
962 tempTags.byteCount != tags->byteCount)
965 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
970 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
972 yaffs_ExtendedTags *tags,
979 yaffs_InvalidateCheckpoint(dev);
982 yaffs_BlockInfo *bi = 0;
985 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
991 /* First check this chunk is erased, if it needs
992 * checking. The checking policy (unless forced
993 * always on) is as follows:
995 * Check the first page we try to write in a block.
996 * If the check passes then we don't need to check any
997 * more. If the check fails, we check again...
998 * If the block has been erased, we don't need to check.
1000 * However, if the block has been prioritised for gc,
1001 * then we think there might be something odd about
1002 * this block and stop using it.
1004 * Rationale: We should only ever see chunks that have
1005 * not been erased if there was a partially written
1006 * chunk due to power loss. This checking policy should
1007 * catch that case with very few checks and thus save a
1008 * lot of checks that are most likely not needed.
1011 * If an erase check fails or the write fails we skip the
1012 * rest of the block.
1015 /* let's give it a try */
1018 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
1019 bi->skipErasedCheck = 0;
1021 if (!bi->skipErasedCheck) {
1022 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1023 if (erasedOk != YAFFS_OK) {
1024 T(YAFFS_TRACE_ERROR,
1025 (TSTR("**>> yaffs chunk %d was not erased"
1028 /* If not erased, delete this one,
1029 * skip rest of block and
1030 * try another chunk */
1031 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1032 yaffs_SkipRestOfBlock(dev);
1037 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1040 if(!bi->skipErasedCheck)
1041 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1043 if (writeOk != YAFFS_OK) {
1044 /* Clean up aborted write, skip to next block and
1045 * try another chunk */
1046 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1050 bi->skipErasedCheck = 1;
1052 /* Copy the data into the robustification buffer */
1053 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1055 } while (writeOk != YAFFS_OK &&
1056 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1062 T(YAFFS_TRACE_ERROR,
1063 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1066 dev->nRetriedWrites += (attempts - 1);
1074 * Oldest Dirty Sequence Number handling.
1077 /* yaffs_CalcOldestDirtySequence()
1078 * yaffs_FindOldestDirtySequence()
1079 * Calculate the oldest dirty sequence number if we don't know it.
1081 static void yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1085 unsigned blockNo = 0;
1088 if(!dev->param.isYaffs2)
1091 /* Find the oldest dirty sequence number. */
1092 seq = dev->sequenceNumber + 1;
1094 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1095 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1096 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1097 b->sequenceNumber < seq) {
1098 seq = b->sequenceNumber;
1105 dev->oldestDirtySequence = seq;
1106 dev->oldestDirtyBlock = blockNo;
1112 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1114 if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1115 yaffs_CalcOldestDirtySequence(dev);
1119 * yaffs_ClearOldestDirtySequence()
1120 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1121 * becomes invalid). If the value matches the oldest then we clear
1122 * dev->oldestDirtySequence to force its recomputation.
1124 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1127 if(!dev->param.isYaffs2)
1130 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence){
1131 dev->oldestDirtySequence = 0;
1132 dev->oldestDirtyBlock = 0;
1137 * yaffs_UpdateOldestDirtySequence()
1138 * Update the oldest dirty sequence number whenever we dirty a block.
1139 * Only do this if the oldestDirtySequence is actually being tracked.
1141 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, unsigned blockNo, yaffs_BlockInfo *bi)
1143 if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1144 if(dev->oldestDirtySequence > bi->sequenceNumber){
1145 dev->oldestDirtySequence = bi->sequenceNumber;
1146 dev->oldestDirtyBlock = blockNo;
1152 * Block retiring for handling a broken block.
1155 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1157 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1159 yaffs_InvalidateCheckpoint(dev);
1161 yaffs_ClearOldestDirtySequence(dev,bi);
1163 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1164 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1165 T(YAFFS_TRACE_ALWAYS, (TSTR(
1166 "yaffs: Failed to mark bad and erase block %d"
1167 TENDSTR), blockInNAND));
1169 yaffs_ExtendedTags tags;
1170 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1172 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1174 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1175 yaffs_InitialiseTags(&tags);
1176 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1177 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1178 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1179 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1180 TCONT("write bad block marker to block %d")
1181 TENDSTR), blockInNAND));
1183 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1187 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1188 bi->gcPrioritise = 0;
1189 bi->needsRetiring = 0;
1191 dev->nRetiredBlocks++;
1195 * Functions for robustisizing TODO
1199 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1201 const yaffs_ExtendedTags *tags)
1204 chunkInNAND=chunkInNAND;
1209 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1210 const yaffs_ExtendedTags *tags)
1213 chunkInNAND=chunkInNAND;
1217 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1219 if (!bi->gcPrioritise) {
1220 bi->gcPrioritise = 1;
1221 dev->hasPendingPrioritisedGCs = 1;
1222 bi->chunkErrorStrikes++;
1224 if (bi->chunkErrorStrikes > 3) {
1225 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1226 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1232 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1235 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1236 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1238 yaffs_HandleChunkError(dev, bi);
1241 /* Was an actual write failure, so mark the block for retirement */
1242 bi->needsRetiring = 1;
1243 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1244 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1247 /* Delete the chunk */
1248 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1249 yaffs_SkipRestOfBlock(dev);
1253 /*---------------- Name handling functions ------------*/
1255 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1260 const YUCHAR *bname = (const YUCHAR *) name;
1262 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1264 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1265 sum += yaffs_toupper(*bname) * i;
1267 sum += (*bname) * i;
1276 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1278 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1279 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1280 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1281 yaffs_strcpy(obj->shortName, name);
1283 obj->shortName[0] = _Y('\0');
1285 obj->sum = yaffs_CalcNameSum(name);
1288 /*-------------------- TNODES -------------------
1290 * List of spare tnodes
1291 * The list is hooked together using the first pointer
1295 /* yaffs_CreateTnodes creates a bunch more tnodes and
1296 * adds them to the tnode free list.
1297 * Don't use this function directly
1299 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1302 /* Calculate the tnode size in bytes for variable width tnode support.
1303 * Must be a multiple of 32-bits */
1304 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1306 if (tnodeSize < sizeof(yaffs_Tnode))
1307 tnodeSize = sizeof(yaffs_Tnode);
1311 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1314 int tnodeSize = yaffs_CalcTnodeSize(dev);
1315 yaffs_Tnode *newTnodes;
1319 yaffs_TnodeList *tnl;
1325 /* make these things */
1327 newTnodes = YMALLOC(nTnodes * tnodeSize);
1328 mem = (__u8 *)newTnodes;
1331 T(YAFFS_TRACE_ERROR,
1332 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1336 /* Hook them into the free list */
1338 for (i = 0; i < nTnodes - 1; i++) {
1339 newTnodes[i].internal[0] = &newTnodes[i + 1];
1340 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1341 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1345 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1346 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1347 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1349 dev->freeTnodes = newTnodes;
1351 /* New hookup for wide tnodes */
1352 for (i = 0; i < nTnodes - 1; i++) {
1353 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1354 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1355 curr->internal[0] = next;
1358 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1359 curr->internal[0] = dev->freeTnodes;
1360 dev->freeTnodes = (yaffs_Tnode *)mem;
1365 dev->nFreeTnodes += nTnodes;
1366 dev->nTnodesCreated += nTnodes;
1368 /* Now add this bunch of tnodes to a list for freeing up.
1369 * NB If we can't add this to the management list it isn't fatal
1370 * but it just means we can't free this bunch of tnodes later.
1373 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1375 T(YAFFS_TRACE_ERROR,
1377 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1380 tnl->tnodes = newTnodes;
1381 tnl->next = dev->allocatedTnodeList;
1382 dev->allocatedTnodeList = tnl;
1385 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1390 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1392 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1394 yaffs_Tnode *tn = NULL;
1396 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1397 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1399 dev->nTnodesCreated++;
1401 /* If there are none left make more */
1402 if (!dev->freeTnodes)
1403 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1405 if (dev->freeTnodes) {
1406 tn = dev->freeTnodes;
1407 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1408 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1409 /* Hoosterman, this thing looks like it isn't in the list */
1410 T(YAFFS_TRACE_ALWAYS,
1411 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1414 dev->freeTnodes = dev->freeTnodes->internal[0];
1418 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1423 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1425 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1426 int tnodeSize = yaffs_CalcTnodeSize(dev);
1429 memset(tn, 0, tnodeSize);
1434 /* FreeTnode frees up a tnode and puts it back on the free list */
1435 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1438 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1440 dev->nTnodesCreated--;
1442 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1443 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1444 /* Hoosterman, this thing looks like it is already in the list */
1445 T(YAFFS_TRACE_ALWAYS,
1446 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1448 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1450 tn->internal[0] = dev->freeTnodes;
1451 dev->freeTnodes = tn;
1455 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1458 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1460 /* Free the list of allocated tnodes */
1461 yaffs_TnodeList *tmp;
1463 while (dev->allocatedTnodeList) {
1464 tmp = dev->allocatedTnodeList->next;
1466 YFREE(dev->allocatedTnodeList->tnodes);
1467 YFREE(dev->allocatedTnodeList);
1468 dev->allocatedTnodeList = tmp;
1472 dev->freeTnodes = NULL;
1473 dev->nFreeTnodes = 0;
1474 dev->nTnodesCreated = 0;
1477 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1479 dev->allocatedTnodeList = NULL;
1480 dev->freeTnodes = NULL;
1481 dev->nFreeTnodes = 0;
1482 dev->nTnodesCreated = 0;
1486 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1489 __u32 *map = (__u32 *)tn;
1495 pos &= YAFFS_TNODES_LEVEL0_MASK;
1496 val >>= dev->chunkGroupBits;
1498 bitInMap = pos * dev->tnodeWidth;
1499 wordInMap = bitInMap / 32;
1500 bitInWord = bitInMap & (32 - 1);
1502 mask = dev->tnodeMask << bitInWord;
1504 map[wordInMap] &= ~mask;
1505 map[wordInMap] |= (mask & (val << bitInWord));
1507 if (dev->tnodeWidth > (32 - bitInWord)) {
1508 bitInWord = (32 - bitInWord);
1510 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1511 map[wordInMap] &= ~mask;
1512 map[wordInMap] |= (mask & (val >> bitInWord));
1516 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1519 __u32 *map = (__u32 *)tn;
1525 pos &= YAFFS_TNODES_LEVEL0_MASK;
1527 bitInMap = pos * dev->tnodeWidth;
1528 wordInMap = bitInMap / 32;
1529 bitInWord = bitInMap & (32 - 1);
1531 val = map[wordInMap] >> bitInWord;
1533 if (dev->tnodeWidth > (32 - bitInWord)) {
1534 bitInWord = (32 - bitInWord);
1536 val |= (map[wordInMap] << bitInWord);
1539 val &= dev->tnodeMask;
1540 val <<= dev->chunkGroupBits;
1545 /* ------------------- End of individual tnode manipulation -----------------*/
1547 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1548 * The look up tree is represented by the top tnode and the number of topLevel
1549 * in the tree. 0 means only the level 0 tnode is in the tree.
1552 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1553 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1554 yaffs_FileStructure *fStruct,
1557 yaffs_Tnode *tn = fStruct->top;
1559 int requiredTallness;
1560 int level = fStruct->topLevel;
1564 /* Check sane level and chunk Id */
1565 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1568 if (chunkId > YAFFS_MAX_CHUNK_ID)
1571 /* First check we're tall enough (ie enough topLevel) */
1573 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1574 requiredTallness = 0;
1576 i >>= YAFFS_TNODES_INTERNAL_BITS;
1580 if (requiredTallness > fStruct->topLevel)
1581 return NULL; /* Not tall enough, so we can't find it */
1583 /* Traverse down to level 0 */
1584 while (level > 0 && tn) {
1585 tn = tn->internal[(chunkId >>
1586 (YAFFS_TNODES_LEVEL0_BITS +
1588 YAFFS_TNODES_INTERNAL_BITS)) &
1589 YAFFS_TNODES_INTERNAL_MASK];
1596 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1597 * This happens in two steps:
1598 * 1. If the tree isn't tall enough, then make it taller.
1599 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1601 * Used when modifying the tree.
1603 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1604 * be plugged into the ttree.
1607 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1608 yaffs_FileStructure *fStruct,
1610 yaffs_Tnode *passedTn)
1612 int requiredTallness;
1620 /* Check sane level and page Id */
1621 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1624 if (chunkId > YAFFS_MAX_CHUNK_ID)
1627 /* First check we're tall enough (ie enough topLevel) */
1629 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1630 requiredTallness = 0;
1632 x >>= YAFFS_TNODES_INTERNAL_BITS;
1637 if (requiredTallness > fStruct->topLevel) {
1638 /* Not tall enough, gotta make the tree taller */
1639 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1641 tn = yaffs_GetTnode(dev);
1644 tn->internal[0] = fStruct->top;
1646 fStruct->topLevel++;
1648 T(YAFFS_TRACE_ERROR,
1649 (TSTR("yaffs: no more tnodes" TENDSTR)));
1655 /* Traverse down to level 0, adding anything we need */
1657 l = fStruct->topLevel;
1661 while (l > 0 && tn) {
1663 (YAFFS_TNODES_LEVEL0_BITS +
1664 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1665 YAFFS_TNODES_INTERNAL_MASK;
1668 if ((l > 1) && !tn->internal[x]) {
1669 /* Add missing non-level-zero tnode */
1670 tn->internal[x] = yaffs_GetTnode(dev);
1671 if(!tn->internal[x])
1673 } else if (l == 1) {
1674 /* Looking from level 1 at level 0 */
1676 /* If we already have one, then release it.*/
1677 if (tn->internal[x])
1678 yaffs_FreeTnode(dev, tn->internal[x]);
1679 tn->internal[x] = passedTn;
1681 } else if (!tn->internal[x]) {
1682 /* Don't have one, none passed in */
1683 tn->internal[x] = yaffs_GetTnode(dev);
1684 if(!tn->internal[x])
1689 tn = tn->internal[x];
1693 /* top is level 0 */
1695 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1696 yaffs_FreeTnode(dev, passedTn);
1703 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1704 yaffs_ExtendedTags *tags, int objectId,
1709 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1710 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1711 theChunk % dev->param.nChunksPerBlock)) {
1713 if(dev->chunkGroupSize == 1)
1716 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1718 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1730 /* Experimental code not being used yet. Might speed up file deletion */
1731 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1732 * chunks and tnodes in the file.
1733 * Returns 1 if the tree was deleted.
1734 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1737 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1738 int chunkOffset, int *limit)
1743 yaffs_ExtendedTags tags;
1745 yaffs_Device *dev = in->myDev;
1751 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1753 if (tn->internal[i]) {
1754 if (limit && (*limit) < 0) {
1758 yaffs_DeleteWorker(in,
1766 YAFFS_TNODES_INTERNAL_BITS)
1771 yaffs_FreeTnode(dev,
1774 tn->internal[i] = NULL;
1778 return (allDone) ? 1 : 0;
1779 } else if (level == 0) {
1782 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1784 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1787 chunkInInode = (chunkOffset <<
1788 YAFFS_TNODES_LEVEL0_BITS) + i;
1791 yaffs_FindChunkInGroup(dev,
1797 if (foundChunk > 0) {
1798 yaffs_DeleteChunk(dev,
1803 *limit = *limit - 1;
1810 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1814 return (i < 0) ? 1 : 0;
1826 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1828 yaffs_BlockInfo *theBlock;
1831 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1833 blockNo = chunk / dev->param.nChunksPerBlock;
1834 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1836 theBlock->softDeletions++;
1838 yaffs_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1842 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1843 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1845 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1848 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1849 __u32 level, int chunkOffset)
1854 yaffs_Device *dev = in->myDev;
1859 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1861 if (tn->internal[i]) {
1863 yaffs_SoftDeleteWorker(in,
1869 YAFFS_TNODES_INTERNAL_BITS)
1872 yaffs_FreeTnode(dev,
1875 tn->internal[i] = NULL;
1877 /* Hoosterman... how could this happen? */
1881 return (allDone) ? 1 : 0;
1882 } else if (level == 0) {
1884 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1885 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1887 /* Note this does not find the real chunk, only the chunk group.
1888 * We make an assumption that a chunk group is not larger than
1891 yaffs_SoftDeleteChunk(dev, theChunk);
1892 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1906 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1909 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1910 if (obj->nDataChunks <= 0) {
1911 /* Empty file with no duplicate object headers, just delete it immediately */
1912 yaffs_FreeTnode(obj->myDev,
1913 obj->variant.fileVariant.top);
1914 obj->variant.fileVariant.top = NULL;
1915 T(YAFFS_TRACE_TRACING,
1916 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1918 yaffs_DoGenericObjectDeletion(obj);
1920 yaffs_SoftDeleteWorker(obj,
1921 obj->variant.fileVariant.top,
1922 obj->variant.fileVariant.
1924 obj->softDeleted = 1;
1929 /* Pruning removes any part of the file structure tree that is beyond the
1930 * bounds of the file (ie that does not point to chunks).
1932 * A file should only get pruned when its size is reduced.
1934 * Before pruning, the chunks must be pulled from the tree and the
1935 * level 0 tnode entries must be zeroed out.
1936 * Could also use this for file deletion, but that's probably better handled
1937 * by a special case.
1939 * This function is recursive. For levels > 0 the function is called again on
1940 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1941 * If there is no data in a subtree then it is pruned.
1944 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1945 __u32 level, int del0)
1954 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1955 if (tn->internal[i]) {
1957 yaffs_PruneWorker(dev, tn->internal[i],
1959 (i == 0) ? del0 : 1);
1962 if (tn->internal[i])
1966 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1967 __u32 *map = (__u32 *)tn;
1969 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1975 if (hasData == 0 && del0) {
1976 /* Free and return NULL */
1978 yaffs_FreeTnode(dev, tn);
1988 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1989 yaffs_FileStructure *fStruct)
1996 if (fStruct->topLevel > 0) {
1998 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
2000 /* Now we have a tree with all the non-zero branches NULL but the height
2001 * is the same as it was.
2002 * Let's see if we can trim internal tnodes to shorten the tree.
2003 * We can do this if only the 0th element in the tnode is in use
2004 * (ie all the non-zero are NULL)
2007 while (fStruct->topLevel && !done) {
2011 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
2012 if (tn->internal[i])
2017 fStruct->top = tn->internal[0];
2018 fStruct->topLevel--;
2019 yaffs_FreeTnode(dev, tn);
2029 /*-------------------- End of File Structure functions.-------------------*/
2031 /* yaffs_CreateFreeObjects creates a bunch more objects and
2032 * adds them to the object free list.
2034 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2037 yaffs_Object *newObjects;
2038 yaffs_ObjectList *list;
2043 /* make these things */
2044 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2045 list = YMALLOC(sizeof(yaffs_ObjectList));
2047 if (!newObjects || !list) {
2056 T(YAFFS_TRACE_ALLOCATE,
2057 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2061 /* Hook them into the free list */
2062 for (i = 0; i < nObjects - 1; i++) {
2063 newObjects[i].siblings.next =
2064 (struct ylist_head *)(&newObjects[i + 1]);
2067 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2068 dev->freeObjects = newObjects;
2069 dev->nFreeObjects += nObjects;
2070 dev->nObjectsCreated += nObjects;
2072 /* Now add this bunch of Objects to a list for freeing up. */
2074 list->objects = newObjects;
2075 list->next = dev->allocatedObjectList;
2076 dev->allocatedObjectList = list;
2082 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2083 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2085 yaffs_Object *tn = NULL;
2087 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2088 tn = YMALLOC(sizeof(yaffs_Object));
2090 dev->nObjectsCreated++;
2092 /* If there are none left make more */
2093 if (!dev->freeObjects)
2094 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2096 if (dev->freeObjects) {
2097 tn = dev->freeObjects;
2099 (yaffs_Object *) (dev->freeObjects->siblings.next);
2100 dev->nFreeObjects--;
2104 /* Now sweeten it up... */
2106 memset(tn, 0, sizeof(yaffs_Object));
2107 tn->beingCreated = 1;
2111 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2112 YINIT_LIST_HEAD(&(tn->hardLinks));
2113 YINIT_LIST_HEAD(&(tn->hashLink));
2114 YINIT_LIST_HEAD(&tn->siblings);
2117 /* Now make the directory sane */
2119 tn->parent = dev->rootDir;
2120 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2123 /* Add it to the lost and found directory.
2124 * NB Can't put root or lostNFound in lostNFound so
2125 * check if lostNFound exists first
2127 if (dev->lostNFoundDir)
2128 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2130 tn->beingCreated = 0;
2133 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2138 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2143 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2145 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2146 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2147 obj->unlinkAllowed = 0; /* ... or unlink it */
2150 obj->yst_mode = mode;
2152 obj->hdrChunk = 0; /* Not a valid chunk. */
2159 static void yaffs_UnhashObject(yaffs_Object *tn)
2162 yaffs_Device *dev = tn->myDev;
2164 /* If it is still linked into the bucket list, free from the list */
2165 if (!ylist_empty(&tn->hashLink)) {
2166 ylist_del_init(&tn->hashLink);
2167 bucket = yaffs_HashFunction(tn->objectId);
2168 dev->objectBucket[bucket].count--;
2172 /* FreeObject frees up a Object and puts it back on the free list */
2173 static void yaffs_FreeObject(yaffs_Object *tn)
2175 yaffs_Device *dev = tn->myDev;
2177 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2183 if (!ylist_empty(&tn->siblings))
2188 /* We're still hooked up to a cached inode.
2189 * Don't delete now, but mark for later deletion
2191 tn->deferedFree = 1;
2195 yaffs_UnhashObject(tn);
2197 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2199 dev->nObjectsCreated--;
2202 /* Link into the free list. */
2203 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2204 dev->freeObjects = tn;
2205 dev->nFreeObjects++;
2207 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2211 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2213 if (obj->deferedFree)
2214 yaffs_FreeObject(obj);
2218 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2220 /* Free the list of allocated Objects */
2222 yaffs_ObjectList *tmp;
2224 while (dev->allocatedObjectList) {
2225 tmp = dev->allocatedObjectList->next;
2226 YFREE(dev->allocatedObjectList->objects);
2227 YFREE(dev->allocatedObjectList);
2229 dev->allocatedObjectList = tmp;
2232 dev->freeObjects = NULL;
2233 dev->nFreeObjects = 0;
2234 dev->nObjectsCreated = 0;
2237 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2241 dev->allocatedObjectList = NULL;
2242 dev->freeObjects = NULL;
2243 dev->nFreeObjects = 0;
2245 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2246 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2247 dev->objectBucket[i].count = 0;
2251 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2255 int lowest = 999999;
2258 /* Search for the shortest list or one that
2262 for (i = 0; i < 10 && lowest > 4; i++) {
2263 dev->bucketFinder++;
2264 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2265 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2266 lowest = dev->objectBucket[dev->bucketFinder].count;
2267 l = dev->bucketFinder;
2275 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2277 int bucket = yaffs_FindNiceObjectBucket(dev);
2279 /* Now find an object value that has not already been taken
2280 * by scanning the list.
2284 struct ylist_head *i;
2286 __u32 n = (__u32) bucket;
2288 /* yaffs_CheckObjectHashSanity(); */
2292 n += YAFFS_NOBJECT_BUCKETS;
2293 if (1 || dev->objectBucket[bucket].count > 0) {
2294 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2295 /* If there is already one in the list */
2296 if (i && ylist_entry(i, yaffs_Object,
2297 hashLink)->objectId == n) {
2307 static void yaffs_HashObject(yaffs_Object *in)
2309 int bucket = yaffs_HashFunction(in->objectId);
2310 yaffs_Device *dev = in->myDev;
2312 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2313 dev->objectBucket[bucket].count++;
2316 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2318 int bucket = yaffs_HashFunction(number);
2319 struct ylist_head *i;
2322 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2323 /* Look if it is in the list */
2325 in = ylist_entry(i, yaffs_Object, hashLink);
2326 if (in->objectId == number) {
2328 /* Don't tell the VFS about this one if it is defered free */
2329 if (in->deferedFree)
2340 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2341 yaffs_ObjectType type)
2343 yaffs_Object *theObject=NULL;
2344 yaffs_Tnode *tn = NULL;
2347 number = yaffs_CreateNewObjectNumber(dev);
2349 if (type == YAFFS_OBJECT_TYPE_FILE) {
2350 tn = yaffs_GetTnode(dev);
2355 theObject = yaffs_AllocateEmptyObject(dev);
2358 yaffs_FreeTnode(dev,tn);
2364 theObject->fake = 0;
2365 theObject->renameAllowed = 1;
2366 theObject->unlinkAllowed = 1;
2367 theObject->objectId = number;
2368 yaffs_HashObject(theObject);
2369 theObject->variantType = type;
2370 #ifdef CONFIG_YAFFS_WINCE
2371 yfsd_WinFileTimeNow(theObject->win_atime);
2372 theObject->win_ctime[0] = theObject->win_mtime[0] =
2373 theObject->win_atime[0];
2374 theObject->win_ctime[1] = theObject->win_mtime[1] =
2375 theObject->win_atime[1];
2379 theObject->yst_atime = theObject->yst_mtime =
2380 theObject->yst_ctime = Y_CURRENT_TIME;
2383 case YAFFS_OBJECT_TYPE_FILE:
2384 theObject->variant.fileVariant.fileSize = 0;
2385 theObject->variant.fileVariant.scannedFileSize = 0;
2386 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2387 theObject->variant.fileVariant.topLevel = 0;
2388 theObject->variant.fileVariant.top = tn;
2390 case YAFFS_OBJECT_TYPE_DIRECTORY:
2391 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2393 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2396 case YAFFS_OBJECT_TYPE_SYMLINK:
2397 case YAFFS_OBJECT_TYPE_HARDLINK:
2398 case YAFFS_OBJECT_TYPE_SPECIAL:
2399 /* No action required */
2401 case YAFFS_OBJECT_TYPE_UNKNOWN:
2402 /* todo this should not happen */
2410 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2412 yaffs_ObjectType type)
2414 yaffs_Object *theObject = NULL;
2417 theObject = yaffs_FindObjectByNumber(dev, number);
2420 theObject = yaffs_CreateNewObject(dev, number, type);
2427 static YCHAR *yaffs_CloneString(const YCHAR *str)
2429 YCHAR *newStr = NULL;
2435 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2436 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2438 yaffs_strncpy(newStr, str,len);
2446 * Mknod (create) a new object.
2447 * equivalentObject only has meaning for a hard link;
2448 * aliasString only has meaning for a symlink.
2449 * rdev only has meaning for devices (a subset of special objects)
2452 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2453 yaffs_Object *parent,
2458 yaffs_Object *equivalentObject,
2459 const YCHAR *aliasString, __u32 rdev)
2464 yaffs_Device *dev = parent->myDev;
2466 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2467 if (yaffs_FindObjectByName(parent, name))
2470 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2471 str = yaffs_CloneString(aliasString);
2476 in = yaffs_CreateNewObject(dev, -1, type);
2491 in->variantType = type;
2493 in->yst_mode = mode;
2495 #ifdef CONFIG_YAFFS_WINCE
2496 yfsd_WinFileTimeNow(in->win_atime);
2497 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2498 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2501 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2503 in->yst_rdev = rdev;
2507 in->nDataChunks = 0;
2509 yaffs_SetObjectName(in, name);
2512 yaffs_AddObjectToDirectory(parent, in);
2514 in->myDev = parent->myDev;
2517 case YAFFS_OBJECT_TYPE_SYMLINK:
2518 in->variant.symLinkVariant.alias = str;
2520 case YAFFS_OBJECT_TYPE_HARDLINK:
2521 in->variant.hardLinkVariant.equivalentObject =
2523 in->variant.hardLinkVariant.equivalentObjectId =
2524 equivalentObject->objectId;
2525 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2527 case YAFFS_OBJECT_TYPE_FILE:
2528 case YAFFS_OBJECT_TYPE_DIRECTORY:
2529 case YAFFS_OBJECT_TYPE_SPECIAL:
2530 case YAFFS_OBJECT_TYPE_UNKNOWN:
2535 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0, NULL) < 0) {
2536 /* Could not create the object header, fail the creation */
2537 yaffs_DeleteObject(in);
2541 yaffs_UpdateParent(parent);
2547 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2548 __u32 mode, __u32 uid, __u32 gid)
2550 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2551 uid, gid, NULL, NULL, 0);
2554 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2555 __u32 mode, __u32 uid, __u32 gid)
2557 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2558 mode, uid, gid, NULL, NULL, 0);
2561 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2562 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2564 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2565 uid, gid, NULL, NULL, rdev);
2568 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2569 __u32 mode, __u32 uid, __u32 gid,
2572 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2573 uid, gid, NULL, alias, 0);
2576 /* yaffs_Link returns the object id of the equivalent object.*/
2577 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2578 yaffs_Object *equivalentObject)
2580 /* Get the real object in case we were fed a hard link as an equivalent object */
2581 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2583 if (yaffs_MknodObject
2584 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2585 equivalentObject, NULL, 0)) {
2586 return equivalentObject;
2593 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2594 const YCHAR *newName, int force, int shadows)
2599 yaffs_Object *existingTarget;
2602 newDir = obj->parent; /* use the old directory */
2604 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2605 T(YAFFS_TRACE_ALWAYS,
2607 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2612 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2613 if (obj->myDev->param.isYaffs2)
2614 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2616 unlinkOp = (newDir == obj->myDev->unlinkedDir
2617 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2619 deleteOp = (newDir == obj->myDev->deletedDir);
2621 existingTarget = yaffs_FindObjectByName(newDir, newName);
2623 /* If the object is a file going into the unlinked directory,
2624 * then it is OK to just stuff it in since duplicate names are allowed.
2625 * else only proceed if the new name does not exist and if we're putting
2626 * it into a directory.
2633 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2634 yaffs_SetObjectName(obj, newName);
2637 yaffs_AddObjectToDirectory(newDir, obj);
2642 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2643 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows, NULL) >= 0)
2650 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2651 yaffs_Object *newDir, const YCHAR *newName)
2653 yaffs_Object *obj = NULL;
2654 yaffs_Object *existingTarget = NULL;
2660 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2662 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2665 dev = oldDir->myDev;
2667 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2668 /* Special case for case insemsitive systems (eg. WinCE).
2669 * While look-up is case insensitive, the name isn't.
2670 * Therefore we might want to change x.txt to X.txt
2672 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2676 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2680 obj = yaffs_FindObjectByName(oldDir, oldName);
2682 if (obj && obj->renameAllowed) {
2684 /* Now do the handling for an existing target, if there is one */
2686 existingTarget = yaffs_FindObjectByName(newDir, newName);
2687 if (existingTarget &&
2688 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2689 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2690 /* There is a target that is a non-empty directory, so we fail */
2691 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2692 } else if (existingTarget && existingTarget != obj) {
2693 /* Nuke the target first, using shadowing,
2694 * but only if it isn't the same object.
2696 * Note we must disable gc otherwise it can mess up the shadowing.
2700 yaffs_ChangeObjectName(obj, newDir, newName, force,
2701 existingTarget->objectId);
2702 existingTarget->isShadowed = 1;
2703 yaffs_UnlinkObject(existingTarget);
2707 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2709 yaffs_UpdateParent(oldDir);
2710 if(newDir != oldDir)
2711 yaffs_UpdateParent(newDir);
2718 /*------------------------- Block Management and Page Allocation ----------------*/
2720 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2722 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2724 dev->blockInfo = NULL;
2725 dev->chunkBits = NULL;
2727 dev->allocationBlock = -1; /* force it to get a new one */
2729 /* If the first allocation strategy fails, thry the alternate one */
2730 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2731 if (!dev->blockInfo) {
2732 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2733 dev->blockInfoAlt = 1;
2735 dev->blockInfoAlt = 0;
2737 if (dev->blockInfo) {
2738 /* Set up dynamic blockinfo stuff. */
2739 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2740 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2741 if (!dev->chunkBits) {
2742 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2743 dev->chunkBitsAlt = 1;
2745 dev->chunkBitsAlt = 0;
2748 if (dev->blockInfo && dev->chunkBits) {
2749 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2750 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2757 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2759 if (dev->blockInfoAlt && dev->blockInfo)
2760 YFREE_ALT(dev->blockInfo);
2761 else if (dev->blockInfo)
2762 YFREE(dev->blockInfo);
2764 dev->blockInfoAlt = 0;
2766 dev->blockInfo = NULL;
2768 if (dev->chunkBitsAlt && dev->chunkBits)
2769 YFREE_ALT(dev->chunkBits);
2770 else if (dev->chunkBits)
2771 YFREE(dev->chunkBits);
2772 dev->chunkBitsAlt = 0;
2773 dev->chunkBits = NULL;
2776 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2777 yaffs_BlockInfo *bi)
2780 if (!dev->param.isYaffs2)
2781 return 1; /* disqualification only applies to yaffs2. */
2783 if (!bi->hasShrinkHeader)
2784 return 1; /* can gc */
2786 yaffs_FindOldestDirtySequence(dev);
2788 /* Can't do gc of this block if there are any blocks older than this one that have
2791 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2795 * yaffs_FindRefreshBlock()
2796 * periodically finds the oldest full block by sequence number for refreshing.
2799 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2804 __u32 oldestSequence = 0;
2806 yaffs_BlockInfo *bi;
2809 * If refresh period < 10 then refreshing is disabled.
2811 if(dev->param.refreshPeriod < 10 ||
2812 !dev->param.isYaffs2)
2816 * Fix broken values.
2818 if(dev->refreshSkip > dev->param.refreshPeriod)
2819 dev->refreshSkip = dev->param.refreshPeriod;
2821 if(dev->refreshSkip > 0)
2825 * Refresh skip is now zero.
2826 * We'll do a refresh this time around....
2827 * Update the refresh skip and find the oldest block.
2829 dev->refreshSkip = dev->param.refreshPeriod;
2830 dev->refreshCount++;
2831 bi = dev->blockInfo;
2832 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2834 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2837 bi->sequenceNumber < oldestSequence){
2839 oldestSequence = bi->sequenceNumber;
2847 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2848 dev->refreshCount, oldest, oldestSequence));
2855 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2857 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2861 /* If the block is still healthy erase it and mark as clean.
2862 * If the block has had a data failure, then retire it.
2865 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2866 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2867 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2869 yaffs_ClearOldestDirtySequence(dev,bi);
2871 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2873 /* If this is the block being garbage collected then stop gc'ing this block */
2874 if(blockNo == dev->gcBlock)
2877 /* If this block is currently the best candidate for gc then drop as a candidate */
2878 if(blockNo == dev->gcDirtiest){
2879 dev->gcDirtiest = 0;
2880 dev->gcPagesInUse = 0;
2883 if (!bi->needsRetiring) {
2884 yaffs_InvalidateCheckpoint(dev);
2885 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2887 dev->nErasureFailures++;
2888 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2889 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2894 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2896 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2897 if (!yaffs_CheckChunkErased
2898 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2899 T(YAFFS_TRACE_ERROR,
2901 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2902 TENDSTR), blockNo, i));
2908 /* Clean it up... */
2909 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2910 bi->sequenceNumber = 0;
2911 dev->nErasedBlocks++;
2913 bi->softDeletions = 0;
2914 bi->hasShrinkHeader = 0;
2915 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2916 bi->gcPrioritise = 0;
2917 yaffs_ClearChunkBits(dev, blockNo);
2919 T(YAFFS_TRACE_ERASE,
2920 (TSTR("Erased block %d" TENDSTR), blockNo));
2922 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2924 yaffs_RetireBlock(dev, blockNo);
2925 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2926 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2930 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2934 yaffs_BlockInfo *bi;
2936 if (dev->nErasedBlocks < 1) {
2937 /* Hoosterman we've got a problem.
2938 * Can't get space to gc
2940 T(YAFFS_TRACE_ERROR,
2941 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2946 /* Find an empty block. */
2948 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2949 dev->allocationBlockFinder++;
2950 if (dev->allocationBlockFinder < dev->internalStartBlock
2951 || dev->allocationBlockFinder > dev->internalEndBlock) {
2952 dev->allocationBlockFinder = dev->internalStartBlock;
2955 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2957 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2958 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2959 dev->sequenceNumber++;
2960 bi->sequenceNumber = dev->sequenceNumber;
2961 dev->nErasedBlocks--;
2962 T(YAFFS_TRACE_ALLOCATE,
2963 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2964 dev->allocationBlockFinder, dev->sequenceNumber,
2965 dev->nErasedBlocks));
2966 return dev->allocationBlockFinder;
2970 T(YAFFS_TRACE_ALWAYS,
2972 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2973 TENDSTR), dev->nErasedBlocks));
2980 static int yaffs_CheckpointRequired(yaffs_Device *dev)
2982 int nblocks = dev->internalEndBlock - dev->internalStartBlock + 1 ;
2983 return dev->param.isYaffs2 &&
2984 !dev->param.skipCheckpointWrite &&
2985 (nblocks >= YAFFS_CHECKPOINT_MIN_BLOCKS);
2987 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2989 if (!dev->nCheckpointBlocksRequired &&
2990 yaffs_CheckpointRequired(dev)){
2991 /* Not a valid value so recalculate */
2994 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2995 int tnodeSize = yaffs_CalcTnodeSize(dev);
2997 nBytes += sizeof(yaffs_CheckpointValidity);
2998 nBytes += sizeof(yaffs_CheckpointDevice);
2999 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
3000 nBytes += devBlocks * dev->chunkBitmapStride;
3001 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
3002 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
3003 nBytes += sizeof(yaffs_CheckpointValidity);
3004 nBytes += sizeof(__u32); /* checksum*/
3006 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
3008 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
3010 dev->nCheckpointBlocksRequired = nBlocks;
3013 return dev->nCheckpointBlocksRequired;
3017 * Check if there's space to allocate...
3018 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3020 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
3023 int reservedBlocks = dev->param.nReservedBlocks;
3024 int checkpointBlocks;
3026 if (dev->param.isYaffs2) {
3027 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
3028 dev->blocksInCheckpoint;
3029 if (checkpointBlocks < 0)
3030 checkpointBlocks = 0;
3032 checkpointBlocks = 0;
3035 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3037 return (dev->nFreeChunks > (reservedChunks + nChunks));
3040 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3041 yaffs_BlockInfo **blockUsedPtr)
3044 yaffs_BlockInfo *bi;
3046 if (dev->allocationBlock < 0) {
3047 /* Get next block to allocate off */
3048 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3049 dev->allocationPage = 0;
3052 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
3053 /* Not enough space to allocate unless we're allowed to use the reserve. */
3057 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3058 && dev->allocationPage == 0) {
3059 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3062 /* Next page please.... */
3063 if (dev->allocationBlock >= 0) {
3064 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3066 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3067 dev->allocationPage;
3069 yaffs_SetChunkBit(dev, dev->allocationBlock,
3070 dev->allocationPage);
3072 dev->allocationPage++;
3076 /* If the block is full set the state to full */
3077 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3078 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3079 dev->allocationBlock = -1;
3088 T(YAFFS_TRACE_ERROR,
3089 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3094 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3098 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3100 if (dev->allocationBlock > 0)
3101 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3108 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3109 * if we don't want to write to it.
3111 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3113 if(dev->allocationBlock > 0){
3114 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3115 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3116 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3117 dev->allocationBlock = -1;
3123 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3129 int retVal = YAFFS_OK;
3132 int isCheckpointBlock;
3136 int chunksBefore = yaffs_GetErasedChunks(dev);
3139 yaffs_ExtendedTags tags;
3141 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3143 yaffs_Object *object;
3145 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3148 T(YAFFS_TRACE_TRACING,
3149 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3152 bi->hasShrinkHeader,
3155 /*yaffs_VerifyFreeChunks(dev); */
3157 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3158 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3160 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3164 if (isCheckpointBlock ||
3165 !yaffs_StillSomeChunkBits(dev, block)) {
3166 T(YAFFS_TRACE_TRACING,
3168 ("Collecting block %d that has no chunks in use" TENDSTR),
3170 yaffs_BlockBecameDirty(dev, block);
3173 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3175 yaffs_VerifyBlock(dev, bi, block);
3177 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
3178 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3180 for (/* init already done */;
3181 retVal == YAFFS_OK &&
3182 dev->gcChunk < dev->param.nChunksPerBlock &&
3183 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3185 dev->gcChunk++, oldChunk++) {
3186 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3188 /* This page is in use and might need to be copied off */
3194 yaffs_InitialiseTags(&tags);
3196 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3200 yaffs_FindObjectByNumber(dev,
3203 T(YAFFS_TRACE_GC_DETAIL,
3205 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3206 dev->gcChunk, tags.objectId, tags.chunkId,
3209 if (object && !yaffs_SkipVerification(dev)) {
3210 if (tags.chunkId == 0)
3211 matchingChunk = object->hdrChunk;
3212 else if (object->softDeleted)
3213 matchingChunk = oldChunk; /* Defeat the test */
3215 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3217 if (oldChunk != matchingChunk)
3218 T(YAFFS_TRACE_ERROR,
3219 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3220 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3225 T(YAFFS_TRACE_ERROR,
3227 ("page %d in gc has no object: %d %d %d "
3229 tags.objectId, tags.chunkId, tags.byteCount));
3234 object->softDeleted &&
3235 tags.chunkId != 0) {
3236 /* Data chunk in a soft deleted file, throw it away
3237 * It's a soft deleted data chunk,
3238 * No need to copy this, just forget about it and
3239 * fix up the object.
3242 /* Free chunks already includes softdeleted chunks.
3243 * How ever this chunk is going to soon be really deleted
3244 * which will increment free chunks.
3245 * We have to decrement free chunks so this works out properly.
3249 object->nDataChunks--;
3251 if (object->nDataChunks <= 0) {
3252 /* remeber to clean up the object */
3253 dev->gcCleanupList[cleanups] =
3259 /* Todo object && object->deleted && object->nDataChunks == 0 */
3260 /* Deleted object header with no data chunks.
3261 * Can be discarded and the file deleted.
3263 object->hdrChunk = 0;
3264 yaffs_FreeTnode(object->myDev,
3267 object->variant.fileVariant.top = NULL;
3268 yaffs_DoGenericObjectDeletion(object);
3270 } else if (object) {
3271 /* It's either a data chunk in a live file or
3272 * an ObjectHeader, so we're interested in it.
3273 * NB Need to keep the ObjectHeaders of deleted files
3274 * until the whole file has been deleted off
3276 tags.serialNumber++;
3280 if (tags.chunkId == 0) {
3281 /* It is an object Id,
3282 * We need to nuke the shrinkheader flags first
3283 * Also need to clean up shadowing.
3284 * We no longer want the shrinkHeader flag since its work is done
3285 * and if it is left in place it will mess up scanning.
3288 yaffs_ObjectHeader *oh;
3289 oh = (yaffs_ObjectHeader *)buffer;
3292 tags.extraIsShrinkHeader = 0;
3294 oh->shadowsObject = 0;
3295 oh->inbandShadowsObject = 0;
3296 tags.extraShadows = 0;
3298 /* Update file size */
3299 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3300 oh->fileSize = object->variant.fileVariant.fileSize;
3301 tags.extraFileLength = oh->fileSize;
3304 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3306 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3309 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3312 retVal = YAFFS_FAIL;
3315 /* Ok, now fix up the Tnodes etc. */
3317 if (tags.chunkId == 0) {
3319 object->hdrChunk = newChunk;
3320 object->serial = tags.serialNumber;
3322 /* It's a data chunk */
3324 ok = yaffs_PutChunkIntoFile
3332 if (retVal == YAFFS_OK)
3333 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3338 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3341 /* Do any required cleanups */
3342 for (i = 0; i < cleanups; i++) {
3343 /* Time to delete the file too */
3345 yaffs_FindObjectByNumber(dev,
3346 dev->gcCleanupList[i]);
3348 yaffs_FreeTnode(dev,
3349 object->variant.fileVariant.
3351 object->variant.fileVariant.top = NULL;
3354 ("yaffs: About to finally delete object %d"
3355 TENDSTR), object->objectId));
3356 yaffs_DoGenericObjectDeletion(object);
3357 object->myDev->nDeletedFiles--;
3364 yaffs_VerifyCollectedBlock(dev, bi, block);
3368 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3370 * The gc did not complete. Set block state back to FULL
3371 * because checkpointing does not restore gc.
3373 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3375 /* The gc completed. */
3376 chunksAfter = yaffs_GetErasedChunks(dev);
3377 if (chunksBefore >= chunksAfter) {
3380 ("gc did not increase free chunks before %d after %d"
3381 TENDSTR), chunksBefore, chunksAfter));
3393 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
3394 * for garbage collection.
3397 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
3403 unsigned selected = 0;
3404 int prioritised = 0;
3405 int prioritisedExists = 0;
3406 yaffs_BlockInfo *bi;
3409 /* First let's see if we need to grab a prioritised block */
3410 if (dev->hasPendingPrioritisedGCs && !aggressive) {
3411 dev->gcDirtiest = 0;
3412 bi = dev->blockInfo;
3413 for (i = dev->internalStartBlock;
3414 i <= dev->internalEndBlock && !selected;
3417 if (bi->gcPrioritise) {
3418 prioritisedExists = 1;
3419 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3420 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3429 * If there is a prioritised block and none was selected then
3430 * this happened because there is at least one old dirty block gumming
3431 * up the works. Let's gc the oldest dirty block.
3434 if(prioritisedExists &&
3436 dev->oldestDirtyBlock > 0)
3437 selected = dev->oldestDirtyBlock;
3439 if (!prioritisedExists) /* None found, so we can clear this */
3440 dev->hasPendingPrioritisedGCs = 0;
3443 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
3445 * else (we're doing a leasurely gc), then we only bother to do this if the
3446 * block has only a few pages in use.
3451 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3453 threshold = dev->param.nChunksPerBlock;
3454 iterations = nBlocks;
3456 int maxThreshold = dev->param.nChunksPerBlock/2;
3457 threshold = background ?
3458 (dev->gcNotDone + 2) * 2 : 0;
3459 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
3460 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
3461 if(threshold > maxThreshold)
3462 threshold = maxThreshold;
3464 iterations = nBlocks / 16 + 1;
3465 if (iterations > 100)
3471 (dev->gcDirtiest < 1 ||
3472 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
3474 dev->gcBlockFinder++;
3475 if (dev->gcBlockFinder < dev->internalStartBlock ||
3476 dev->gcBlockFinder > dev->internalEndBlock)
3477 dev->gcBlockFinder = dev->internalStartBlock;
3479 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
3481 pagesUsed = bi->pagesInUse - bi->softDeletions;
3483 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3484 pagesUsed < dev->param.nChunksPerBlock &&
3485 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
3486 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3487 dev->gcDirtiest = dev->gcBlockFinder;
3488 dev->gcPagesInUse = pagesUsed;
3492 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
3493 selected = dev->gcDirtiest;
3497 * If nothing has been selected for a while, try selecting the oldest dirty
3498 * because that's gumming up the works.
3501 if(!selected && dev->param.isYaffs2 &&
3502 dev->gcNotDone >= ( background ? 10 : 20)){
3503 yaffs_FindOldestDirtySequence(dev);
3504 if(dev->oldestDirtyBlock > 0) {
3505 selected = dev->oldestDirtyBlock;
3506 dev->gcDirtiest = selected;
3507 dev->oldestDirtyGCs++;
3508 bi = yaffs_GetBlockInfo(dev, selected);
3509 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
3516 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
3518 dev->param.nChunksPerBlock - dev->gcPagesInUse,
3522 dev->backgroundGCs++;
3523 dev->gcDirtiest = 0;
3524 dev->gcPagesInUse = 0;
3526 if(dev->refreshSkip > 0)
3531 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
3532 dev->gcBlockFinder, dev->gcNotDone,
3534 dev->gcDirtiest, dev->gcPagesInUse,
3535 dev->oldestDirtyBlock,
3536 background ? " bg" : ""));
3542 /* New garbage collector
3543 * If we're very low on erased blocks then we do aggressive garbage collection
3544 * otherwise we do "leasurely" garbage collection.
3545 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3546 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3548 * The idea is to help clear out space in a more spread-out manner.
3549 * Dunno if it really does anything useful.
3551 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
3554 int gcOk = YAFFS_OK;
3560 int checkpointBlockAdjust;
3562 if(dev->param.gcControl &&
3563 (dev->param.gcControl(dev) & 1) == 0)
3566 if (dev->gcDisable) {
3567 /* Bail out so we don't get recursive gc */
3571 /* This loop should pass the first time.
3572 * We'll only see looping here if the collection does not increase space.
3578 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3579 if (checkpointBlockAdjust < 0)
3580 checkpointBlockAdjust = 0;
3582 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
3583 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3585 /* If we need a block soon then do aggressive gc.*/
3586 if (dev->nErasedBlocks < minErased)
3589 if(dev->gcSkip > 20)
3591 if(erasedChunks < dev->nFreeChunks/2 ||
3603 /* If we don't already have a block being gc'd then see if we should start another */
3605 if (dev->gcBlock < 1 && !aggressive) {
3606 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3609 if (dev->gcBlock < 1) {
3610 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
3614 if (dev->gcBlock > 0) {
3621 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3622 dev->nErasedBlocks, aggressive));
3624 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
3627 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
3630 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3631 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
3633 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3634 (dev->gcBlock > 0) &&
3637 return aggressive ? gcOk : YAFFS_OK;
3641 * yaffs_BackgroundGarbageCollect()
3642 * Garbage collects. Intended to be called from a background thread.
3643 * Returns non-zero if at least half the free chunks are erased.
3645 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
3647 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3649 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
3651 yaffs_CheckGarbageCollection(dev, 1);
3652 return erasedChunks > dev->nFreeChunks/2;
3655 /*------------------------- TAGS --------------------------------*/
3657 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3660 return (tags->chunkId == chunkInObject &&
3661 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3666 /*-------------------- Data file manipulation -----------------*/
3668 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3669 yaffs_ExtendedTags *tags)
3671 /*Get the Tnode, then get the level 0 offset chunk offset */
3674 yaffs_ExtendedTags localTags;
3677 yaffs_Device *dev = in->myDev;
3680 /* Passed a NULL, so use our own tags space */
3684 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3687 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3690 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3696 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3697 yaffs_ExtendedTags *tags)
3699 /* Get the Tnode, then get the level 0 offset chunk offset */
3702 yaffs_ExtendedTags localTags;
3704 yaffs_Device *dev = in->myDev;
3708 /* Passed a NULL, so use our own tags space */
3712 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3716 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3719 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3722 /* Delete the entry in the filestructure (if found) */
3724 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3730 #ifdef YAFFS_PARANOID
3732 static int yaffs_CheckFileSanity(yaffs_Object *in)
3740 yaffs_Tags localTags;
3741 yaffs_Tags *tags = &localTags;
3745 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3748 objId = in->objectId;
3749 fSize = in->variant.fileVariant.fileSize;
3751 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3753 for (chunk = 1; chunk <= nChunks; chunk++) {
3754 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3759 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3761 if (yaffs_CheckChunkBits
3762 (dev, theChunk / dev->param.nChunksPerBlock,
3763 theChunk % dev->param.nChunksPerBlock)) {
3765 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3769 (tags, in->objectId, chunk, chunkDeleted)) {
3779 /* T(("No level 0 found for %d\n", chunk)); */
3783 return failed ? YAFFS_FAIL : YAFFS_OK;
3788 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3789 int chunkInNAND, int inScan)
3791 /* NB inScan is zero unless scanning.
3792 * For forward scanning, inScan is > 0;
3793 * for backward scanning inScan is < 0
3795 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3799 yaffs_Device *dev = in->myDev;
3801 yaffs_ExtendedTags existingTags;
3802 yaffs_ExtendedTags newTags;
3803 unsigned existingSerial, newSerial;
3805 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3806 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3807 * If it is not during Scanning then something went wrong!
3810 T(YAFFS_TRACE_ERROR,
3812 ("yaffs tragedy:attempt to put data chunk into a non-file"
3817 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3821 tn = yaffs_AddOrFindLevel0Tnode(dev,
3822 &in->variant.fileVariant,
3829 /* Dummy insert, bail now */
3832 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3835 /* If we're scanning then we need to test for duplicates
3836 * NB This does not need to be efficient since it should only ever
3837 * happen when the power fails during a write, then only one
3838 * chunk should ever be affected.
3840 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3841 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3844 if (existingChunk > 0) {
3845 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3846 * thus we have to do a FindChunkInFile to get the real chunk id.
3848 * We have a duplicate now we need to decide which one to use:
3850 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3851 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3852 * YAFFS1: Get both sets of tags and compare serial numbers.
3856 /* Only do this for forward scanning */
3857 yaffs_ReadChunkWithTagsFromNAND(dev,
3861 /* Do a proper find */
3863 yaffs_FindChunkInFile(in, chunkInInode,
3867 if (existingChunk <= 0) {
3868 /*Hoosterman - how did this happen? */
3870 T(YAFFS_TRACE_ERROR,
3872 ("yaffs tragedy: existing chunk < 0 in scan"
3877 /* NB The deleted flags should be false, otherwise the chunks will
3878 * not be loaded during a scan
3882 newSerial = newTags.serialNumber;
3883 existingSerial = existingTags.serialNumber;
3887 (in->myDev->param.isYaffs2 ||
3888 existingChunk <= 0 ||
3889 ((existingSerial + 1) & 3) == newSerial)) {
3890 /* Forward scanning.
3892 * Delete the old one and drop through to update the tnode
3894 yaffs_DeleteChunk(dev, existingChunk, 1,
3897 /* Backward scanning or we want to use the existing one
3899 * Delete the new one and return early so that the tnode isn't changed
3901 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3909 if (existingChunk == 0)
3912 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3917 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3920 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3922 if (chunkInNAND >= 0)
3923 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3926 T(YAFFS_TRACE_NANDACCESS,
3927 (TSTR("Chunk %d not found zero instead" TENDSTR),
3929 /* get sane (zero) data if you read a hole */
3930 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3936 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3940 yaffs_ExtendedTags tags;
3941 yaffs_BlockInfo *bi;
3947 block = chunkId / dev->param.nChunksPerBlock;
3948 page = chunkId % dev->param.nChunksPerBlock;
3951 if (!yaffs_CheckChunkBit(dev, block, page))
3952 T(YAFFS_TRACE_VERIFY,
3953 (TSTR("Deleting invalid chunk %d"TENDSTR),
3956 bi = yaffs_GetBlockInfo(dev, block);
3958 yaffs_UpdateOldestDirtySequence(dev, block, bi);
3960 T(YAFFS_TRACE_DELETION,
3961 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3964 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3966 yaffs_InitialiseTags(&tags);
3968 tags.chunkDeleted = 1;
3970 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3971 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3973 dev->nUnmarkedDeletions++;
3976 /* Pull out of the management area.
3977 * If the whole block became dirty, this will kick off an erasure.
3979 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3980 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3981 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3982 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3985 yaffs_ClearChunkBit(dev, block, page);
3989 if (bi->pagesInUse == 0 &&
3990 !bi->hasShrinkHeader &&
3991 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3992 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3993 yaffs_BlockBecameDirty(dev, block);
4000 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
4001 const __u8 *buffer, int nBytes,
4004 /* Find old chunk Need to do this to get serial number
4005 * Write new one and patch into tree.
4006 * Invalidate old tags.
4010 yaffs_ExtendedTags prevTags;
4013 yaffs_ExtendedTags newTags;
4015 yaffs_Device *dev = in->myDev;
4017 yaffs_CheckGarbageCollection(dev,0);
4019 /* Get the previous chunk at this location in the file if it exists.
4020 * If it does not exist then put a zero into the tree. This creates
4021 * the tnode now, rather than later when it is harder to clean up.
4023 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
4024 if(prevChunkId < 1 &&
4025 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
4028 /* Set up new tags */
4029 yaffs_InitialiseTags(&newTags);
4031 newTags.chunkId = chunkInInode;
4032 newTags.objectId = in->objectId;
4033 newTags.serialNumber =
4034 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
4035 newTags.byteCount = nBytes;
4037 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
4038 T(YAFFS_TRACE_ERROR,
4039 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
4045 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4048 if (newChunkId > 0) {
4049 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
4051 if (prevChunkId > 0)
4052 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
4054 yaffs_CheckFileSanity(in);
4060 /* UpdateObjectHeader updates the header on NAND for an object.
4061 * If name is not NULL, then that new name is used.
4063 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
4064 int isShrink, int shadows, yaffs_XAttrMod *xmod)
4067 yaffs_BlockInfo *bi;
4069 yaffs_Device *dev = in->myDev;
4076 yaffs_ExtendedTags newTags;
4077 yaffs_ExtendedTags oldTags;
4078 YCHAR *alias = NULL;
4080 __u8 *buffer = NULL;
4081 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
4083 yaffs_ObjectHeader *oh = NULL;
4085 yaffs_strcpy(oldName, _Y("silly old name"));
4089 in == dev->rootDir || /* The rootDir should also be saved */
4092 yaffs_CheckGarbageCollection(dev,0);
4093 yaffs_CheckObjectDetailsLoaded(in);
4095 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
4096 oh = (yaffs_ObjectHeader *) buffer;
4098 prevChunkId = in->hdrChunk;
4100 if (prevChunkId > 0) {
4101 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
4104 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
4106 memcpy(oldName, oh->name, sizeof(oh->name));
4107 memset(buffer, 0xFF, sizeof(yaffs_ObjectHeader));
4109 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
4111 oh->type = in->variantType;
4112 oh->yst_mode = in->yst_mode;
4113 oh->shadowsObject = oh->inbandShadowsObject = shadows;
4115 #ifdef CONFIG_YAFFS_WINCE
4116 oh->win_atime[0] = in->win_atime[0];
4117 oh->win_ctime[0] = in->win_ctime[0];
4118 oh->win_mtime[0] = in->win_mtime[0];
4119 oh->win_atime[1] = in->win_atime[1];
4120 oh->win_ctime[1] = in->win_ctime[1];
4121 oh->win_mtime[1] = in->win_mtime[1];
4123 oh->yst_uid = in->yst_uid;
4124 oh->yst_gid = in->yst_gid;
4125 oh->yst_atime = in->yst_atime;
4126 oh->yst_mtime = in->yst_mtime;
4127 oh->yst_ctime = in->yst_ctime;
4128 oh->yst_rdev = in->yst_rdev;
4131 oh->parentObjectId = in->parent->objectId;
4133 oh->parentObjectId = 0;
4135 if (name && *name) {
4136 memset(oh->name, 0, sizeof(oh->name));
4137 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
4138 } else if (prevChunkId > 0)
4139 memcpy(oh->name, oldName, sizeof(oh->name));
4141 memset(oh->name, 0, sizeof(oh->name));
4143 oh->isShrink = isShrink;
4145 switch (in->variantType) {
4146 case YAFFS_OBJECT_TYPE_UNKNOWN:
4147 /* Should not happen */
4149 case YAFFS_OBJECT_TYPE_FILE:
4151 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4152 || oh->parentObjectId ==
4153 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4154 fileVariant.fileSize;
4156 case YAFFS_OBJECT_TYPE_HARDLINK:
4157 oh->equivalentObjectId =
4158 in->variant.hardLinkVariant.equivalentObjectId;
4160 case YAFFS_OBJECT_TYPE_SPECIAL:
4163 case YAFFS_OBJECT_TYPE_DIRECTORY:
4166 case YAFFS_OBJECT_TYPE_SYMLINK:
4167 alias = in->variant.symLinkVariant.alias;
4169 alias = _Y("no alias");
4170 yaffs_strncpy(oh->alias,
4172 YAFFS_MAX_ALIAS_LENGTH);
4173 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4177 /* process any xattrib modifications */
4179 yaffs_ApplyXMod(dev, (char *)buffer, xmod);
4183 yaffs_InitialiseTags(&newTags);
4185 newTags.chunkId = 0;
4186 newTags.objectId = in->objectId;
4187 newTags.serialNumber = in->serial;
4189 /* Add extra info for file header */
4191 newTags.extraHeaderInfoAvailable = 1;
4192 newTags.extraParentObjectId = oh->parentObjectId;
4193 newTags.extraFileLength = oh->fileSize;
4194 newTags.extraIsShrinkHeader = oh->isShrink;
4195 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4196 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4197 newTags.extraObjectType = in->variantType;
4199 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4201 /* Create new chunk in NAND */
4203 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4204 (prevChunkId > 0) ? 1 : 0);
4206 if (newChunkId >= 0) {
4208 in->hdrChunk = newChunkId;
4210 if (prevChunkId > 0) {
4211 yaffs_DeleteChunk(dev, prevChunkId, 1,
4215 if (!yaffs_ObjectHasCachedWriteData(in))
4218 /* If this was a shrink, then mark the block that the chunk lives on */
4220 bi = yaffs_GetBlockInfo(in->myDev,
4221 newChunkId / in->myDev->param.nChunksPerBlock);
4222 bi->hasShrinkHeader = 1;
4227 retVal = newChunkId;
4232 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4237 /*------------------------ Short Operations Cache ----------------------------------------
4238 * In many situations where there is no high level buffering (eg WinCE) a lot of
4239 * reads might be short sequential reads, and a lot of writes may be short
4240 * sequential writes. eg. scanning/writing a jpeg file.
4241 * In these cases, a short read/write cache can provide a huge perfomance benefit
4242 * with dumb-as-a-rock code.
4243 * In Linux, the page cache provides read buffering aand the short op cache provides write
4246 * There are a limited number (~10) of cache chunks per device so that we don't
4247 * need a very intelligent search.
4250 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4252 yaffs_Device *dev = obj->myDev;
4254 yaffs_ChunkCache *cache;
4255 int nCaches = obj->myDev->param.nShortOpCaches;
4257 for (i = 0; i < nCaches; i++) {
4258 cache = &dev->srCache[i];
4259 if (cache->object == obj &&
4268 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4270 yaffs_Device *dev = obj->myDev;
4271 int lowest = -99; /* Stop compiler whining. */
4273 yaffs_ChunkCache *cache;
4274 int chunkWritten = 0;
4275 int nCaches = obj->myDev->param.nShortOpCaches;
4281 /* Find the dirty cache for this object with the lowest chunk id. */
4282 for (i = 0; i < nCaches; i++) {
4283 if (dev->srCache[i].object == obj &&
4284 dev->srCache[i].dirty) {
4286 || dev->srCache[i].chunkId <
4288 cache = &dev->srCache[i];
4289 lowest = cache->chunkId;
4294 if (cache && !cache->locked) {
4295 /* Write it out and free it up */
4298 yaffs_WriteChunkDataToObject(cache->object,
4304 cache->object = NULL;
4307 } while (cache && chunkWritten > 0);
4310 /* Hoosterman, disk full while writing cache out. */
4311 T(YAFFS_TRACE_ERROR,
4312 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4319 /*yaffs_FlushEntireDeviceCache(dev)
4324 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4327 int nCaches = dev->param.nShortOpCaches;
4330 /* Find a dirty object in the cache and flush it...
4331 * until there are no further dirty objects.
4335 for (i = 0; i < nCaches && !obj; i++) {
4336 if (dev->srCache[i].object &&
4337 dev->srCache[i].dirty)
4338 obj = dev->srCache[i].object;
4342 yaffs_FlushFilesChunkCache(obj);
4349 /* Grab us a cache chunk for use.
4350 * First look for an empty one.
4351 * Then look for the least recently used non-dirty one.
4352 * Then look for the least recently used dirty one...., flush and look again.
4354 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4358 if (dev->param.nShortOpCaches > 0) {
4359 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4360 if (!dev->srCache[i].object)
4361 return &dev->srCache[i];
4368 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4370 yaffs_ChunkCache *cache;
4371 yaffs_Object *theObj;
4376 if (dev->param.nShortOpCaches > 0) {
4377 /* Try find a non-dirty one... */
4379 cache = yaffs_GrabChunkCacheWorker(dev);
4382 /* They were all dirty, find the last recently used object and flush
4383 * its cache, then find again.
4384 * NB what's here is not very accurate, we actually flush the object
4385 * the last recently used page.
4388 /* With locking we can't assume we can use entry zero */
4395 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4396 if (dev->srCache[i].object &&
4397 !dev->srCache[i].locked &&
4398 (dev->srCache[i].lastUse < usage || !cache)) {
4399 usage = dev->srCache[i].lastUse;
4400 theObj = dev->srCache[i].object;
4401 cache = &dev->srCache[i];
4406 if (!cache || cache->dirty) {
4407 /* Flush and try again */
4408 yaffs_FlushFilesChunkCache(theObj);
4409 cache = yaffs_GrabChunkCacheWorker(dev);
4419 /* Find a cached chunk */
4420 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4423 yaffs_Device *dev = obj->myDev;
4425 if (dev->param.nShortOpCaches > 0) {
4426 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4427 if (dev->srCache[i].object == obj &&
4428 dev->srCache[i].chunkId == chunkId) {
4431 return &dev->srCache[i];
4438 /* Mark the chunk for the least recently used algorithym */
4439 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4443 if (dev->param.nShortOpCaches > 0) {
4444 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4445 /* Reset the cache usages */
4447 for (i = 1; i < dev->param.nShortOpCaches; i++)
4448 dev->srCache[i].lastUse = 0;
4455 cache->lastUse = dev->srLastUse;
4462 /* Invalidate a single cache page.
4463 * Do this when a whole page gets written,
4464 * ie the short cache for this page is no longer valid.
4466 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4468 if (object->myDev->param.nShortOpCaches > 0) {
4469 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4472 cache->object = NULL;
4476 /* Invalidate all the cache pages associated with this object
4477 * Do this whenever ther file is deleted or resized.
4479 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4482 yaffs_Device *dev = in->myDev;
4484 if (dev->param.nShortOpCaches > 0) {
4485 /* Invalidate it. */
4486 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4487 if (dev->srCache[i].object == in)
4488 dev->srCache[i].object = NULL;
4493 /*--------------------- Checkpointing --------------------*/
4496 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4498 yaffs_CheckpointValidity cp;
4500 memset(&cp, 0, sizeof(cp));
4502 cp.structType = sizeof(cp);
4503 cp.magic = YAFFS_MAGIC;
4504 cp.version = YAFFS_CHECKPOINT_VERSION;
4505 cp.head = (head) ? 1 : 0;
4507 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4511 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4513 yaffs_CheckpointValidity cp;
4516 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4519 ok = (cp.structType == sizeof(cp)) &&
4520 (cp.magic == YAFFS_MAGIC) &&
4521 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4522 (cp.head == ((head) ? 1 : 0));
4526 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4529 cp->nErasedBlocks = dev->nErasedBlocks;
4530 cp->allocationBlock = dev->allocationBlock;
4531 cp->allocationPage = dev->allocationPage;
4532 cp->nFreeChunks = dev->nFreeChunks;
4534 cp->nDeletedFiles = dev->nDeletedFiles;
4535 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4536 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4537 cp->sequenceNumber = dev->sequenceNumber;
4541 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4542 yaffs_CheckpointDevice *cp)
4544 dev->nErasedBlocks = cp->nErasedBlocks;
4545 dev->allocationBlock = cp->allocationBlock;
4546 dev->allocationPage = cp->allocationPage;
4547 dev->nFreeChunks = cp->nFreeChunks;
4549 dev->nDeletedFiles = cp->nDeletedFiles;
4550 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4551 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4552 dev->sequenceNumber = cp->sequenceNumber;
4556 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4558 yaffs_CheckpointDevice cp;
4560 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4564 /* Write device runtime values*/
4565 yaffs_DeviceToCheckpointDevice(&cp, dev);
4566 cp.structType = sizeof(cp);
4568 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4570 /* Write block info */
4572 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4573 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4576 /* Write chunk bits */
4578 nBytes = nBlocks * dev->chunkBitmapStride;
4579 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4585 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4587 yaffs_CheckpointDevice cp;
4589 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4593 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4597 if (cp.structType != sizeof(cp))
4601 yaffs_CheckpointDeviceToDevice(dev, &cp);
4603 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4605 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4609 nBytes = nBlocks * dev->chunkBitmapStride;
4611 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4616 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4620 cp->objectId = obj->objectId;
4621 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4622 cp->hdrChunk = obj->hdrChunk;
4623 cp->variantType = obj->variantType;
4624 cp->deleted = obj->deleted;
4625 cp->softDeleted = obj->softDeleted;
4626 cp->unlinked = obj->unlinked;
4627 cp->fake = obj->fake;
4628 cp->renameAllowed = obj->renameAllowed;
4629 cp->unlinkAllowed = obj->unlinkAllowed;
4630 cp->serial = obj->serial;
4631 cp->nDataChunks = obj->nDataChunks;
4633 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4634 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4635 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4636 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4639 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4642 yaffs_Object *parent;
4644 if (obj->variantType != cp->variantType) {
4645 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4646 TCONT("chunk %d does not match existing object type %d")
4647 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4652 obj->objectId = cp->objectId;
4655 parent = yaffs_FindOrCreateObjectByNumber(
4658 YAFFS_OBJECT_TYPE_DIRECTORY);
4663 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4664 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4665 TCONT(" chunk %d Parent type, %d, not directory")
4667 cp->objectId, cp->parentId, cp->variantType,
4668 cp->hdrChunk, parent->variantType));
4671 yaffs_AddObjectToDirectory(parent, obj);
4674 obj->hdrChunk = cp->hdrChunk;
4675 obj->variantType = cp->variantType;
4676 obj->deleted = cp->deleted;
4677 obj->softDeleted = cp->softDeleted;
4678 obj->unlinked = cp->unlinked;
4679 obj->fake = cp->fake;
4680 obj->renameAllowed = cp->renameAllowed;
4681 obj->unlinkAllowed = cp->unlinkAllowed;
4682 obj->serial = cp->serial;
4683 obj->nDataChunks = cp->nDataChunks;
4685 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4686 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4687 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4688 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4690 if (obj->hdrChunk > 0)
4691 obj->lazyLoaded = 1;
4697 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4698 __u32 level, int chunkOffset)
4701 yaffs_Device *dev = in->myDev;
4703 int tnodeSize = yaffs_CalcTnodeSize(dev);
4708 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4709 if (tn->internal[i]) {
4710 ok = yaffs_CheckpointTnodeWorker(in,
4713 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4716 } else if (level == 0) {
4717 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4718 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4720 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4728 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4730 __u32 endMarker = ~0;
4733 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4734 ok = yaffs_CheckpointTnodeWorker(obj,
4735 obj->variant.fileVariant.top,
4736 obj->variant.fileVariant.topLevel,
4739 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4746 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4750 yaffs_Device *dev = obj->myDev;
4751 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4754 int tnodeSize = yaffs_CalcTnodeSize(dev);
4756 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4758 while (ok && (~baseChunk)) {
4760 /* Read level 0 tnode */
4763 tn = yaffs_GetTnodeRaw(dev);
4765 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4770 ok = yaffs_AddOrFindLevel0Tnode(dev,
4776 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4780 T(YAFFS_TRACE_CHECKPOINT, (
4781 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4782 nread, baseChunk, ok));
4788 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4791 yaffs_CheckpointObject cp;
4794 struct ylist_head *lh;
4797 /* Iterate through the objects in each hash entry,
4798 * dumping them to the checkpointing stream.
4801 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4802 ylist_for_each(lh, &dev->objectBucket[i].list) {
4804 obj = ylist_entry(lh, yaffs_Object, hashLink);
4805 if (!obj->deferedFree) {
4806 yaffs_ObjectToCheckpointObject(&cp, obj);
4807 cp.structType = sizeof(cp);
4809 T(YAFFS_TRACE_CHECKPOINT, (
4810 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4811 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4813 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4815 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4816 ok = yaffs_WriteCheckpointTnodes(obj);
4822 /* Dump end of list */
4823 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4824 cp.structType = sizeof(cp);
4827 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4832 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4835 yaffs_CheckpointObject cp;
4838 yaffs_Object *hardList = NULL;
4840 while (ok && !done) {
4841 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4842 if (cp.structType != sizeof(cp)) {
4843 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4844 cp.structType, (int)sizeof(cp), ok));
4848 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4849 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4851 if (ok && cp.objectId == ~0)
4854 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4856 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4859 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4860 ok = yaffs_ReadCheckpointTnodes(obj);
4861 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4862 obj->hardLinks.next =
4863 (struct ylist_head *) hardList;
4872 yaffs_HardlinkFixup(dev, hardList);
4877 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4879 __u32 checkpointSum;
4882 yaffs_GetCheckpointSum(dev, &checkpointSum);
4884 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4892 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4894 __u32 checkpointSum0;
4895 __u32 checkpointSum1;
4898 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4900 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4905 if (checkpointSum0 != checkpointSum1)
4912 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4916 if (!yaffs_CheckpointRequired(dev)) {
4917 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4922 ok = yaffs_CheckpointOpen(dev, 1);
4925 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4926 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4929 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4930 ok = yaffs_WriteCheckpointDevice(dev);
4933 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4934 ok = yaffs_WriteCheckpointObjects(dev);
4937 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4938 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4942 ok = yaffs_WriteCheckpointSum(dev);
4944 if (!yaffs_CheckpointClose(dev))
4948 dev->isCheckpointed = 1;
4950 dev->isCheckpointed = 0;
4952 return dev->isCheckpointed;
4955 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4959 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4960 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4965 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4968 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4969 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4972 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4973 ok = yaffs_ReadCheckpointDevice(dev);
4976 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4977 ok = yaffs_ReadCheckpointObjects(dev);
4980 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4981 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4985 ok = yaffs_ReadCheckpointSum(dev);
4986 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4989 if (!yaffs_CheckpointClose(dev))
4993 dev->isCheckpointed = 1;
4995 dev->isCheckpointed = 0;
5001 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
5003 if (dev->isCheckpointed ||
5004 dev->blocksInCheckpoint > 0) {
5005 dev->isCheckpointed = 0;
5006 yaffs_CheckpointInvalidateStream(dev);
5008 if (dev->param.markSuperBlockDirty)
5009 dev->param.markSuperBlockDirty(dev);
5013 int yaffs_CheckpointSave(yaffs_Device *dev)
5016 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5018 yaffs_VerifyObjects(dev);
5019 yaffs_VerifyBlocks(dev);
5020 yaffs_VerifyFreeChunks(dev);
5022 if (!dev->isCheckpointed) {
5023 yaffs_InvalidateCheckpoint(dev);
5024 yaffs_WriteCheckpointData(dev);
5027 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5029 return dev->isCheckpointed;
5032 int yaffs_CheckpointRestore(yaffs_Device *dev)
5035 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5037 retval = yaffs_ReadCheckpointData(dev);
5039 if (dev->isCheckpointed) {
5040 yaffs_VerifyObjects(dev);
5041 yaffs_VerifyBlocks(dev);
5042 yaffs_VerifyFreeChunks(dev);
5045 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5050 /*--------------------- File read/write ------------------------
5051 * Read and write have very similar structures.
5052 * In general the read/write has three parts to it
5053 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
5054 * Some complete chunks
5055 * An incomplete chunk to end off with
5057 * Curve-balls: the first chunk might also be the last chunk.
5060 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
5069 yaffs_ChunkCache *cache;
5076 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5077 /* start = offset % dev->nDataBytesPerChunk; */
5078 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5081 /* OK now check for the curveball where the start and end are in
5084 if ((start + n) < dev->nDataBytesPerChunk)
5087 nToCopy = dev->nDataBytesPerChunk - start;
5089 cache = yaffs_FindChunkCache(in, chunk);
5091 /* If the chunk is already in the cache or it is less than a whole chunk
5092 * or we're using inband tags then use the cache (if there is caching)
5093 * else bypass the cache.
5095 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5096 if (dev->param.nShortOpCaches > 0) {
5098 /* If we can't find the data in the cache, then load it up. */
5101 cache = yaffs_GrabChunkCache(in->myDev);
5103 cache->chunkId = chunk;
5106 yaffs_ReadChunkDataFromObject(in, chunk,
5112 yaffs_UseChunkCache(dev, cache, 0);
5117 memcpy(buffer, &cache->data[start], nToCopy);
5121 /* Read into the local buffer then copy..*/
5124 yaffs_GetTempBuffer(dev, __LINE__);
5125 yaffs_ReadChunkDataFromObject(in, chunk,
5128 memcpy(buffer, &localBuffer[start], nToCopy);
5131 yaffs_ReleaseTempBuffer(dev, localBuffer,
5137 /* A full chunk. Read directly into the supplied buffer. */
5138 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
5152 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5153 int nBytes, int writeThrough)
5162 int startOfWrite = offset;
5163 int chunkWritten = 0;
5171 while (n > 0 && chunkWritten >= 0) {
5172 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5174 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5175 start >= dev->nDataBytesPerChunk) {
5176 T(YAFFS_TRACE_ERROR, (
5177 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5179 (int)offset, chunk, start));
5181 chunk++; /* File pos to chunk in file offset */
5183 /* OK now check for the curveball where the start and end are in
5187 if ((start + n) < dev->nDataBytesPerChunk) {
5190 /* Now folks, to calculate how many bytes to write back....
5191 * If we're overwriting and not writing to then end of file then
5192 * we need to write back as much as was there before.
5195 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5197 if (chunkStart > in->variant.fileVariant.fileSize)
5198 nBytesRead = 0; /* Past end of file */
5200 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5202 if (nBytesRead > dev->nDataBytesPerChunk)
5203 nBytesRead = dev->nDataBytesPerChunk;
5207 (start + n)) ? nBytesRead : (start + n);
5209 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5213 nToCopy = dev->nDataBytesPerChunk - start;
5214 nToWriteBack = dev->nDataBytesPerChunk;
5217 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5218 /* An incomplete start or end chunk (or maybe both start and end chunk),
5219 * or we're using inband tags, so we want to use the cache buffers.
5221 if (dev->param.nShortOpCaches > 0) {
5222 yaffs_ChunkCache *cache;
5223 /* If we can't find the data in the cache, then load the cache */
5224 cache = yaffs_FindChunkCache(in, chunk);
5227 && yaffs_CheckSpaceForAllocation(dev, 1)) {
5228 cache = yaffs_GrabChunkCache(dev);
5230 cache->chunkId = chunk;
5233 yaffs_ReadChunkDataFromObject(in, chunk,
5237 !yaffs_CheckSpaceForAllocation(dev, 1)) {
5238 /* Drop the cache if it was a read cache item and
5239 * no space check has been made for it.
5245 yaffs_UseChunkCache(dev, cache, 1);
5249 memcpy(&cache->data[start], buffer,
5254 cache->nBytes = nToWriteBack;
5258 yaffs_WriteChunkDataToObject
5261 cache->data, cache->nBytes,
5267 chunkWritten = -1; /* fail the write */
5270 /* An incomplete start or end chunk (or maybe both start and end chunk)
5271 * Read into the local buffer then copy, then copy over and write back.
5275 yaffs_GetTempBuffer(dev, __LINE__);
5277 yaffs_ReadChunkDataFromObject(in, chunk,
5282 memcpy(&localBuffer[start], buffer, nToCopy);
5285 yaffs_WriteChunkDataToObject(in, chunk,
5290 yaffs_ReleaseTempBuffer(dev, localBuffer,
5296 /* A full chunk. Write directly from the supplied buffer. */
5301 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5302 dev->nDataBytesPerChunk,
5305 /* Since we've overwritten the cached data, we better invalidate it. */
5306 yaffs_InvalidateChunkCache(in, chunk);
5309 if (chunkWritten >= 0) {
5318 /* Update file object */
5320 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5321 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5328 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5329 int nBytes, int writeThrough)
5331 yaffs_HandleHole(in,offset);
5332 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
5337 /* ---------------------- File resizing stuff ------------------ */
5339 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5342 yaffs_Device *dev = in->myDev;
5343 int oldFileSize = in->variant.fileVariant.fileSize;
5345 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5347 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5348 dev->nDataBytesPerChunk;
5352 /* Delete backwards so that we don't end up with holes if
5353 * power is lost part-way through the operation.
5355 for (i = lastDel; i >= startDel; i--) {
5356 /* NB this could be optimised somewhat,
5357 * eg. could retrieve the tags and write them without
5358 * using yaffs_DeleteChunk
5361 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5364 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5366 ((dev->internalEndBlock +
5367 1) * dev->param.nChunksPerBlock)) {
5368 T(YAFFS_TRACE_ALWAYS,
5369 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5373 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5381 static void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
5384 __u32 newSizeOfPartialChunk;
5385 yaffs_Device *dev = obj->myDev;
5387 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5389 yaffs_PruneResizedChunks(obj, newSize);
5391 if (newSizeOfPartialChunk != 0) {
5392 int lastChunk = 1 + newFullChunks;
5393 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5395 /* Got to read and rewrite the last chunk with its new size and zero pad */
5396 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
5397 memset(localBuffer + newSizeOfPartialChunk, 0,
5398 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5400 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
5401 newSizeOfPartialChunk, 1);
5403 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5406 obj->variant.fileVariant.fileSize = newSize;
5408 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
5412 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize)
5414 /* if newsSize > oldFileSize.
5415 * We're going to be writing a hole.
5416 * If the hole is small then write zeros otherwise write a start of hole marker.
5423 int result = YAFFS_OK;
5424 yaffs_Device *dev = NULL;
5426 __u8 *localBuffer = NULL;
5428 int smallIncreaseOk = 0;
5433 if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
5438 /* Bail out if not yaffs2 mode */
5439 if(!dev->param.isYaffs2)
5442 oldFileSize = obj->variant.fileVariant.fileSize;
5444 if (newSize <= oldFileSize)
5447 increase = newSize - oldFileSize;
5449 if(increase < YAFFS_SMALL_HOLE_THRESHOLD * dev->nDataBytesPerChunk &&
5450 yaffs_CheckSpaceForAllocation(dev, YAFFS_SMALL_HOLE_THRESHOLD + 1))
5456 localBuffer= yaffs_GetTempBuffer(dev, __LINE__);
5459 /* fill hole with zero bytes */
5460 int pos = oldFileSize;
5463 memset(localBuffer,0,dev->nDataBytesPerChunk);
5464 smallIncreaseOk = 1;
5466 while(increase > 0 && smallIncreaseOk){
5467 thisWrite = increase;
5468 if(thisWrite > dev->nDataBytesPerChunk)
5469 thisWrite = dev->nDataBytesPerChunk;
5470 written = yaffs_DoWriteDataToFile(obj,localBuffer,pos,thisWrite,0);
5471 if(written == thisWrite){
5473 increase -= thisWrite;
5475 smallIncreaseOk = 0;
5478 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
5480 /* If we were out of space then reverse any chunks we've added */
5481 if(!smallIncreaseOk)
5482 yaffs_ResizeDown(obj, oldFileSize);
5485 if (!smallIncreaseOk &&
5487 obj->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5488 obj->parent->objectId != YAFFS_OBJECTID_DELETED){
5489 /* Write a hole start header with the old file size */
5490 yaffs_UpdateObjectHeader(obj, NULL, 0, 1, 0, NULL);
5497 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5499 yaffs_Device *dev = in->myDev;
5500 int oldFileSize = in->variant.fileVariant.fileSize;
5502 yaffs_FlushFilesChunkCache(in);
5503 yaffs_InvalidateWholeChunkCache(in);
5505 yaffs_CheckGarbageCollection(dev,0);
5507 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5510 if (newSize == oldFileSize)
5513 if(newSize > oldFileSize){
5514 yaffs_HandleHole(in,newSize);
5515 in->variant.fileVariant.fileSize = newSize;
5517 /* newSize < oldFileSize */
5518 yaffs_ResizeDown(in, newSize);
5521 /* Write a new object header to reflect the resize.
5522 * show we've shrunk the file, if need be
5523 * Do this only if the file is not in the deleted directories
5524 * and is not shadowed.
5528 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5529 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5530 yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL);
5536 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5538 YCHAR *alias = NULL;
5539 obj = yaffs_GetEquivalentObject(obj);
5541 switch (obj->variantType) {
5542 case YAFFS_OBJECT_TYPE_FILE:
5543 return obj->variant.fileVariant.fileSize;
5544 case YAFFS_OBJECT_TYPE_SYMLINK:
5545 alias = obj->variant.symLinkVariant.alias;
5548 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5556 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5560 yaffs_FlushFilesChunkCache(in);
5561 if(dataSync) /* Only sync data */
5565 #ifdef CONFIG_YAFFS_WINCE
5566 yfsd_WinFileTimeNow(in->win_mtime);
5569 in->yst_mtime = Y_CURRENT_TIME;
5574 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL) >=
5575 0) ? YAFFS_OK : YAFFS_FAIL;
5585 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5588 /* First off, invalidate the file's data in the cache, without flushing. */
5589 yaffs_InvalidateWholeChunkCache(in);
5591 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5592 /* Move to the unlinked directory so we have a record that it was deleted. */
5593 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5597 yaffs_RemoveObjectFromDirectory(in);
5598 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5601 yaffs_FreeObject(in);
5606 /* yaffs_DeleteFile deletes the whole file data
5607 * and the inode associated with the file.
5608 * It does not delete the links associated with the file.
5610 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5614 int immediateDeletion = 0;
5615 yaffs_Device *dev = in->myDev;
5618 immediateDeletion = 1;
5620 if (immediateDeletion) {
5622 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5623 _Y("deleted"), 0, 0);
5624 T(YAFFS_TRACE_TRACING,
5625 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5628 in->myDev->nDeletedFiles++;
5629 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5630 yaffs_ResizeFile(in, 0);
5631 yaffs_SoftDeleteFile(in);
5634 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5635 _Y("unlinked"), 0, 0);
5642 int yaffs_DeleteFile(yaffs_Object *in)
5644 int retVal = YAFFS_OK;
5645 int deleted; /* Need to cache value on stack if in is freed */
5646 yaffs_Device *dev = in->myDev;
5648 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5649 yaffs_ResizeFile(in, 0);
5651 if (in->nDataChunks > 0) {
5652 /* Use soft deletion if there is data in the file.
5653 * That won't be the case if it has been resized to zero.
5656 retVal = yaffs_UnlinkFileIfNeeded(in);
5658 deleted = in->deleted;
5660 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5663 in->myDev->nDeletedFiles++;
5664 yaffs_SoftDeleteFile(in);
5666 return deleted ? YAFFS_OK : YAFFS_FAIL;
5668 /* The file has no data chunks so we toss it immediately */
5669 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5670 in->variant.fileVariant.top = NULL;
5671 yaffs_DoGenericObjectDeletion(in);
5677 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5679 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5680 !(ylist_empty(&obj->variant.directoryVariant.children));
5683 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5685 /* First check that the directory is empty. */
5686 if (yaffs_IsNonEmptyDirectory(obj))
5689 return yaffs_DoGenericObjectDeletion(obj);
5692 static int yaffs_DeleteSymLink(yaffs_Object *in)
5694 if(in->variant.symLinkVariant.alias)
5695 YFREE(in->variant.symLinkVariant.alias);
5696 in->variant.symLinkVariant.alias=NULL;
5698 return yaffs_DoGenericObjectDeletion(in);
5701 static int yaffs_DeleteHardLink(yaffs_Object *in)
5703 /* remove this hardlink from the list assocaited with the equivalent
5706 ylist_del_init(&in->hardLinks);
5707 return yaffs_DoGenericObjectDeletion(in);
5710 int yaffs_DeleteObject(yaffs_Object *obj)
5713 switch (obj->variantType) {
5714 case YAFFS_OBJECT_TYPE_FILE:
5715 retVal = yaffs_DeleteFile(obj);
5717 case YAFFS_OBJECT_TYPE_DIRECTORY:
5718 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5719 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5720 ylist_del_init(&obj->variant.directoryVariant.dirty);
5722 return yaffs_DeleteDirectory(obj);
5724 case YAFFS_OBJECT_TYPE_SYMLINK:
5725 retVal = yaffs_DeleteSymLink(obj);
5727 case YAFFS_OBJECT_TYPE_HARDLINK:
5728 retVal = yaffs_DeleteHardLink(obj);
5730 case YAFFS_OBJECT_TYPE_SPECIAL:
5731 retVal = yaffs_DoGenericObjectDeletion(obj);
5733 case YAFFS_OBJECT_TYPE_UNKNOWN:
5735 break; /* should not happen. */
5741 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5744 int immediateDeletion = 0;
5747 immediateDeletion = 1;
5750 yaffs_UpdateParent(obj->parent);
5752 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5753 return yaffs_DeleteHardLink(obj);
5754 } else if (!ylist_empty(&obj->hardLinks)) {
5755 /* Curve ball: We're unlinking an object that has a hardlink.
5757 * This problem arises because we are not strictly following
5758 * The Linux link/inode model.
5760 * We can't really delete the object.
5761 * Instead, we do the following:
5762 * - Select a hardlink.
5763 * - Unhook it from the hard links
5764 * - Move it from its parent directory (so that the rename can work)
5765 * - Rename the object to the hardlink's name.
5766 * - Delete the hardlink
5770 yaffs_Object *parent;
5772 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5774 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5776 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5777 parent = hl->parent;
5779 ylist_del_init(&hl->hardLinks);
5781 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5783 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5785 if (retVal == YAFFS_OK)
5786 retVal = yaffs_DoGenericObjectDeletion(hl);
5790 } else if (immediateDeletion) {
5791 switch (obj->variantType) {
5792 case YAFFS_OBJECT_TYPE_FILE:
5793 return yaffs_DeleteFile(obj);
5795 case YAFFS_OBJECT_TYPE_DIRECTORY:
5796 ylist_del_init(&obj->variant.directoryVariant.dirty);
5797 return yaffs_DeleteDirectory(obj);
5799 case YAFFS_OBJECT_TYPE_SYMLINK:
5800 return yaffs_DeleteSymLink(obj);
5802 case YAFFS_OBJECT_TYPE_SPECIAL:
5803 return yaffs_DoGenericObjectDeletion(obj);
5805 case YAFFS_OBJECT_TYPE_HARDLINK:
5806 case YAFFS_OBJECT_TYPE_UNKNOWN:
5810 } else if(yaffs_IsNonEmptyDirectory(obj))
5813 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5814 _Y("unlinked"), 0, 0);
5818 static int yaffs_UnlinkObject(yaffs_Object *obj)
5821 if (obj && obj->unlinkAllowed)
5822 return yaffs_UnlinkWorker(obj);
5827 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5831 obj = yaffs_FindObjectByName(dir, name);
5832 return yaffs_UnlinkObject(obj);
5835 /*----------------------- Initialisation Scanning ---------------------- */
5837 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5838 int backwardScanning)
5842 if (!backwardScanning) {
5843 /* Handle YAFFS1 forward scanning case
5844 * For YAFFS1 we always do the deletion
5848 /* Handle YAFFS2 case (backward scanning)
5849 * If the shadowed object exists then ignore.
5851 obj = yaffs_FindObjectByNumber(dev, objId);
5856 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5857 * We put it in unlinked dir to be cleaned up after the scanning
5860 yaffs_FindOrCreateObjectByNumber(dev, objId,
5861 YAFFS_OBJECT_TYPE_FILE);
5864 obj->isShadowed = 1;
5865 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5866 obj->variant.fileVariant.shrinkSize = 0;
5867 obj->valid = 1; /* So that we don't read any other info for this file */
5877 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5884 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5886 in = yaffs_FindObjectByNumber(dev,
5887 hl->variant.hardLinkVariant.
5888 equivalentObjectId);
5891 /* Add the hardlink pointers */
5892 hl->variant.hardLinkVariant.equivalentObject = in;
5893 ylist_add(&hl->hardLinks, &in->hardLinks);
5895 /* Todo Need to report/handle this better.
5896 * Got a problem... hardlink to a non-existant object
5898 hl->variant.hardLinkVariant.equivalentObject = NULL;
5899 YINIT_LIST_HEAD(&hl->hardLinks);
5909 static int ybicmp(const void *a, const void *b)
5911 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5912 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5913 register int ablock = ((yaffs_BlockIndex *)a)->block;
5914 register int bblock = ((yaffs_BlockIndex *)b)->block;
5916 return ablock - bblock;
5922 struct yaffs_ShadowFixerStruct {
5925 struct yaffs_ShadowFixerStruct *next;
5929 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5932 * Sort out state of unlinked and deleted objects after scanning.
5934 struct ylist_head *i;
5935 struct ylist_head *n;
5938 /* Soft delete all the unlinked files */
5939 ylist_for_each_safe(i, n,
5940 &dev->unlinkedDir->variant.directoryVariant.children) {
5942 l = ylist_entry(i, yaffs_Object, siblings);
5943 yaffs_DeleteObject(l);
5947 ylist_for_each_safe(i, n,
5948 &dev->deletedDir->variant.directoryVariant.children) {
5950 l = ylist_entry(i, yaffs_Object, siblings);
5951 yaffs_DeleteObject(l);
5958 * This code iterates through all the objects making sure that they are rooted.
5959 * Any unrooted objects are re-rooted in lost+found.
5960 * An object needs to be in one of:
5961 * - Directly under deleted, unlinked
5962 * - Directly or indirectly under root.
5965 * This code assumes that we don't ever change the current relationships between
5967 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5968 * lostNfound->parent == rootDir
5970 * This fixes the problem where directories might have inadvertently been deleted
5971 * leaving the object "hanging" without being rooted in the directory tree.
5974 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5976 return (obj == dev->deletedDir ||
5977 obj == dev->unlinkedDir||
5978 obj == dev->rootDir);
5981 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5984 yaffs_Object *parent;
5986 struct ylist_head *lh;
5987 struct ylist_head *n;
5992 /* Iterate through the objects in each hash entry,
5993 * looking at each object.
5994 * Make sure it is rooted.
5997 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5998 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
6000 obj = ylist_entry(lh, yaffs_Object, hashLink);
6001 parent= obj->parent;
6003 if(yaffs_HasNULLParent(dev,obj)){
6004 /* These directories are not hanging */
6007 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6009 else if(yaffs_HasNULLParent(dev,parent))
6013 * Need to follow the parent chain to see if it is hanging.
6018 while(parent != dev->rootDir &&
6020 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
6022 parent = parent->parent;
6025 if(parent != dev->rootDir)
6030 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
6032 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
6041 * Delete directory contents for cleaning up lost and found.
6043 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
6046 struct ylist_head *lh;
6047 struct ylist_head *n;
6049 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6052 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
6054 obj = ylist_entry(lh, yaffs_Object, siblings);
6055 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
6056 yaffs_DeleteDirectoryContents(obj);
6059 (TSTR("Deleting lost_found object %d" TENDSTR),
6062 /* Need to use UnlinkObject since Delete would not handle
6063 * hardlinked objects correctly.
6065 yaffs_UnlinkObject(obj);
6071 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
6073 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
6076 static int yaffs_Scan(yaffs_Device *dev)
6078 yaffs_ExtendedTags tags;
6088 yaffs_BlockState state;
6089 yaffs_Object *hardList = NULL;
6090 yaffs_BlockInfo *bi;
6091 __u32 sequenceNumber;
6092 yaffs_ObjectHeader *oh;
6094 yaffs_Object *parent;
6096 int alloc_failed = 0;
6098 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
6106 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
6107 dev->internalStartBlock, dev->internalEndBlock));
6109 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6111 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6113 /* Scan all the blocks to determine their state */
6114 bi = dev->blockInfo;
6115 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6116 yaffs_ClearChunkBits(dev, blk);
6118 bi->softDeletions = 0;
6120 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6122 bi->blockState = state;
6123 bi->sequenceNumber = sequenceNumber;
6125 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6126 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6128 T(YAFFS_TRACE_SCAN_DEBUG,
6129 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6130 state, sequenceNumber));
6132 if (state == YAFFS_BLOCK_STATE_DEAD) {
6133 T(YAFFS_TRACE_BAD_BLOCKS,
6134 (TSTR("block %d is bad" TENDSTR), blk));
6135 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6136 T(YAFFS_TRACE_SCAN_DEBUG,
6137 (TSTR("Block empty " TENDSTR)));
6138 dev->nErasedBlocks++;
6139 dev->nFreeChunks += dev->param.nChunksPerBlock;
6144 startIterator = dev->internalStartBlock;
6145 endIterator = dev->internalEndBlock;
6147 /* For each block.... */
6148 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
6155 blk = blockIterator;
6157 bi = yaffs_GetBlockInfo(dev, blk);
6158 state = bi->blockState;
6162 /* For each chunk in each block that needs scanning....*/
6163 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
6164 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
6165 /* Read the tags and decide what to do */
6166 chunk = blk * dev->param.nChunksPerBlock + c;
6168 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6171 /* Let's have a good look at this chunk... */
6173 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
6179 /*T((" %d %d deleted\n",blk,c)); */
6180 } else if (!tags.chunkUsed) {
6181 /* An unassigned chunk in the block
6182 * This means that either the block is empty or
6183 * this is the one being allocated from
6187 /* We're looking at the first chunk in the block so the block is unused */
6188 state = YAFFS_BLOCK_STATE_EMPTY;
6189 dev->nErasedBlocks++;
6191 /* this is the block being allocated from */
6194 (" Allocating from %d %d" TENDSTR),
6196 state = YAFFS_BLOCK_STATE_ALLOCATING;
6197 dev->allocationBlock = blk;
6198 dev->allocationPage = c;
6199 dev->allocationBlockFinder = blk;
6200 /* Set block finder here to encourage the allocator to go forth from here. */
6204 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
6205 } else if (tags.chunkId > 0) {
6206 /* chunkId > 0 so it is a data chunk... */
6207 unsigned int endpos;
6209 yaffs_SetChunkBit(dev, blk, c);
6212 in = yaffs_FindOrCreateObjectByNumber(dev,
6215 YAFFS_OBJECT_TYPE_FILE);
6216 /* PutChunkIntoFile checks for a clash (two data chunks with
6217 * the same chunkId).
6224 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
6229 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
6232 in->variantType == YAFFS_OBJECT_TYPE_FILE
6233 && in->variant.fileVariant.scannedFileSize <
6235 in->variant.fileVariant.
6236 scannedFileSize = endpos;
6237 if (!dev->param.useHeaderFileSize) {
6238 in->variant.fileVariant.
6240 in->variant.fileVariant.
6245 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
6247 /* chunkId == 0, so it is an ObjectHeader.
6248 * Thus, we read in the object header and make the object
6250 yaffs_SetChunkBit(dev, blk, c);
6253 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6257 oh = (yaffs_ObjectHeader *) chunkData;
6259 in = yaffs_FindObjectByNumber(dev,
6261 if (in && in->variantType != oh->type) {
6262 /* This should not happen, but somehow
6263 * Wev'e ended up with an objectId that has been reused but not yet
6264 * deleted, and worse still it has changed type. Delete the old object.
6267 yaffs_DeleteObject(in);
6272 in = yaffs_FindOrCreateObjectByNumber(dev,
6280 if (in && oh->shadowsObject > 0) {
6282 struct yaffs_ShadowFixerStruct *fixer;
6283 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6285 fixer->next = shadowFixerList;
6286 shadowFixerList = fixer;
6287 fixer->objectId = tags.objectId;
6288 fixer->shadowedId = oh->shadowsObject;
6293 if (in && in->valid) {
6294 /* We have already filled this one. We have a duplicate and need to resolve it. */
6296 unsigned existingSerial = in->serial;
6297 unsigned newSerial = tags.serialNumber;
6299 if (((existingSerial + 1) & 3) == newSerial) {
6300 /* Use new one - destroy the exisiting one */
6301 yaffs_DeleteChunk(dev,
6306 /* Use existing - destroy this one. */
6307 yaffs_DeleteChunk(dev, chunk, 1,
6312 if (in && !in->valid &&
6313 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6314 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6315 /* We only load some info, don't fiddle with directory structure */
6317 in->variantType = oh->type;
6319 in->yst_mode = oh->yst_mode;
6320 #ifdef CONFIG_YAFFS_WINCE
6321 in->win_atime[0] = oh->win_atime[0];
6322 in->win_ctime[0] = oh->win_ctime[0];
6323 in->win_mtime[0] = oh->win_mtime[0];
6324 in->win_atime[1] = oh->win_atime[1];
6325 in->win_ctime[1] = oh->win_ctime[1];
6326 in->win_mtime[1] = oh->win_mtime[1];
6328 in->yst_uid = oh->yst_uid;
6329 in->yst_gid = oh->yst_gid;
6330 in->yst_atime = oh->yst_atime;
6331 in->yst_mtime = oh->yst_mtime;
6332 in->yst_ctime = oh->yst_ctime;
6333 in->yst_rdev = oh->yst_rdev;
6335 in->hdrChunk = chunk;
6336 in->serial = tags.serialNumber;
6338 } else if (in && !in->valid) {
6339 /* we need to load this info */
6342 in->variantType = oh->type;
6344 in->yst_mode = oh->yst_mode;
6345 #ifdef CONFIG_YAFFS_WINCE
6346 in->win_atime[0] = oh->win_atime[0];
6347 in->win_ctime[0] = oh->win_ctime[0];
6348 in->win_mtime[0] = oh->win_mtime[0];
6349 in->win_atime[1] = oh->win_atime[1];
6350 in->win_ctime[1] = oh->win_ctime[1];
6351 in->win_mtime[1] = oh->win_mtime[1];
6353 in->yst_uid = oh->yst_uid;
6354 in->yst_gid = oh->yst_gid;
6355 in->yst_atime = oh->yst_atime;
6356 in->yst_mtime = oh->yst_mtime;
6357 in->yst_ctime = oh->yst_ctime;
6358 in->yst_rdev = oh->yst_rdev;
6360 in->hdrChunk = chunk;
6361 in->serial = tags.serialNumber;
6363 yaffs_SetObjectName(in, oh->name);
6366 /* directory stuff...
6371 yaffs_FindOrCreateObjectByNumber
6372 (dev, oh->parentObjectId,
6373 YAFFS_OBJECT_TYPE_DIRECTORY);
6376 if (parent && parent->variantType ==
6377 YAFFS_OBJECT_TYPE_UNKNOWN) {
6378 /* Set up as a directory */
6379 parent->variantType =
6380 YAFFS_OBJECT_TYPE_DIRECTORY;
6381 YINIT_LIST_HEAD(&parent->variant.
6384 } else if (!parent || parent->variantType !=
6385 YAFFS_OBJECT_TYPE_DIRECTORY) {
6386 /* Hoosterman, another problem....
6387 * We're trying to use a non-directory as a directory
6390 T(YAFFS_TRACE_ERROR,
6392 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6394 parent = dev->lostNFoundDir;
6397 yaffs_AddObjectToDirectory(parent, in);
6399 if (0 && (parent == dev->deletedDir ||
6400 parent == dev->unlinkedDir)) {
6401 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6402 dev->nDeletedFiles++;
6404 /* Note re hardlinks.
6405 * Since we might scan a hardlink before its equivalent object is scanned
6406 * we put them all in a list.
6407 * After scanning is complete, we should have all the objects, so we run through this
6408 * list and fix up all the chains.
6411 switch (in->variantType) {
6412 case YAFFS_OBJECT_TYPE_UNKNOWN:
6413 /* Todo got a problem */
6415 case YAFFS_OBJECT_TYPE_FILE:
6416 if (dev->param.useHeaderFileSize)
6418 in->variant.fileVariant.
6423 case YAFFS_OBJECT_TYPE_HARDLINK:
6424 in->variant.hardLinkVariant.
6425 equivalentObjectId =
6426 oh->equivalentObjectId;
6427 in->hardLinks.next =
6428 (struct ylist_head *)
6432 case YAFFS_OBJECT_TYPE_DIRECTORY:
6435 case YAFFS_OBJECT_TYPE_SPECIAL:
6438 case YAFFS_OBJECT_TYPE_SYMLINK:
6439 in->variant.symLinkVariant.alias =
6440 yaffs_CloneString(oh->alias);
6441 if (!in->variant.symLinkVariant.alias)
6450 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6451 /* If we got this far while scanning, then the block is fully allocated.*/
6452 state = YAFFS_BLOCK_STATE_FULL;
6455 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6456 /* If the block was partially allocated then treat it as fully allocated.*/
6457 state = YAFFS_BLOCK_STATE_FULL;
6458 dev->allocationBlock = -1;
6461 bi->blockState = state;
6463 /* Now let's see if it was dirty */
6464 if (bi->pagesInUse == 0 &&
6465 !bi->hasShrinkHeader &&
6466 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6467 yaffs_BlockBecameDirty(dev, blk);
6473 /* Ok, we've done all the scanning.
6474 * Fix up the hard link chains.
6475 * We should now have scanned all the objects, now it's time to add these
6479 yaffs_HardlinkFixup(dev, hardList);
6481 /* Fix up any shadowed objects */
6483 struct yaffs_ShadowFixerStruct *fixer;
6486 while (shadowFixerList) {
6487 fixer = shadowFixerList;
6488 shadowFixerList = fixer->next;
6489 /* Complete the rename transaction by deleting the shadowed object
6490 * then setting the object header to unshadowed.
6492 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6494 yaffs_DeleteObject(obj);
6496 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6499 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0, NULL);
6505 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6510 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6516 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6519 yaffs_ObjectHeader *oh;
6521 yaffs_ExtendedTags tags;
6523 int alloc_failed = 0;
6531 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6533 in->lazyLoaded ? "not yet" : "already"));
6536 if (in->lazyLoaded && in->hdrChunk > 0) {
6538 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6540 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6541 oh = (yaffs_ObjectHeader *) chunkData;
6543 in->yst_mode = oh->yst_mode;
6544 #ifdef CONFIG_YAFFS_WINCE
6545 in->win_atime[0] = oh->win_atime[0];
6546 in->win_ctime[0] = oh->win_ctime[0];
6547 in->win_mtime[0] = oh->win_mtime[0];
6548 in->win_atime[1] = oh->win_atime[1];
6549 in->win_ctime[1] = oh->win_ctime[1];
6550 in->win_mtime[1] = oh->win_mtime[1];
6552 in->yst_uid = oh->yst_uid;
6553 in->yst_gid = oh->yst_gid;
6554 in->yst_atime = oh->yst_atime;
6555 in->yst_mtime = oh->yst_mtime;
6556 in->yst_ctime = oh->yst_ctime;
6557 in->yst_rdev = oh->yst_rdev;
6560 yaffs_SetObjectName(in, oh->name);
6562 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6563 in->variant.symLinkVariant.alias =
6564 yaffs_CloneString(oh->alias);
6565 if (!in->variant.symLinkVariant.alias)
6566 alloc_failed = 1; /* Not returned to caller */
6569 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6573 static int yaffs_ScanBackwards(yaffs_Device *dev)
6575 yaffs_ExtendedTags tags;
6580 int nBlocksToScan = 0;
6586 yaffs_BlockState state;
6587 yaffs_Object *hardList = NULL;
6588 yaffs_BlockInfo *bi;
6589 __u32 sequenceNumber;
6590 yaffs_ObjectHeader *oh;
6592 yaffs_Object *parent;
6593 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6599 int foundChunksInBlock;
6600 int equivalentObjectId;
6601 int alloc_failed = 0;
6604 yaffs_BlockIndex *blockIndex = NULL;
6605 int altBlockIndex = 0;
6607 if (!dev->param.isYaffs2) {
6609 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6615 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6616 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6619 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6621 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6624 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6630 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6634 dev->blocksInCheckpoint = 0;
6636 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6638 /* Scan all the blocks to determine their state */
6639 bi = dev->blockInfo;
6640 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6641 yaffs_ClearChunkBits(dev, blk);
6643 bi->softDeletions = 0;
6645 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6647 bi->blockState = state;
6648 bi->sequenceNumber = sequenceNumber;
6650 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6651 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6652 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6653 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6655 T(YAFFS_TRACE_SCAN_DEBUG,
6656 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6657 state, sequenceNumber));
6660 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6661 dev->blocksInCheckpoint++;
6663 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6664 T(YAFFS_TRACE_BAD_BLOCKS,
6665 (TSTR("block %d is bad" TENDSTR), blk));
6666 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6667 T(YAFFS_TRACE_SCAN_DEBUG,
6668 (TSTR("Block empty " TENDSTR)));
6669 dev->nErasedBlocks++;
6670 dev->nFreeChunks += dev->param.nChunksPerBlock;
6671 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6673 /* Determine the highest sequence number */
6674 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6675 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6677 blockIndex[nBlocksToScan].seq = sequenceNumber;
6678 blockIndex[nBlocksToScan].block = blk;
6682 if (sequenceNumber >= dev->sequenceNumber)
6683 dev->sequenceNumber = sequenceNumber;
6685 /* TODO: Nasty sequence number! */
6688 ("Block scanning block %d has bad sequence number %d"
6689 TENDSTR), blk, sequenceNumber));
6697 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6703 /* Sort the blocks */
6704 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6706 /* Use qsort now. */
6707 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6711 /* Dungy old bubble sort... */
6713 yaffs_BlockIndex temp;
6717 for (i = 0; i < nBlocksToScan; i++)
6718 for (j = i + 1; j < nBlocksToScan; j++)
6719 if (blockIndex[i].seq > blockIndex[j].seq) {
6720 temp = blockIndex[j];
6721 blockIndex[j] = blockIndex[i];
6722 blockIndex[i] = temp;
6729 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6731 /* Now scan the blocks looking at the data. */
6733 endIterator = nBlocksToScan - 1;
6734 T(YAFFS_TRACE_SCAN_DEBUG,
6735 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6737 /* For each block.... backwards */
6738 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6740 /* Cooperative multitasking! This loop can run for so
6741 long that watchdog timers expire. */
6744 /* get the block to scan in the correct order */
6745 blk = blockIndex[blockIterator].block;
6747 bi = yaffs_GetBlockInfo(dev, blk);
6750 state = bi->blockState;
6754 /* For each chunk in each block that needs scanning.... */
6755 foundChunksInBlock = 0;
6756 for (c = dev->param.nChunksPerBlock - 1;
6757 !alloc_failed && c >= 0 &&
6758 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6759 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6760 /* Scan backwards...
6761 * Read the tags and decide what to do
6764 chunk = blk * dev->param.nChunksPerBlock + c;
6766 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6769 /* Let's have a good look at this chunk... */
6771 if (!tags.chunkUsed) {
6772 /* An unassigned chunk in the block.
6773 * If there are used chunks after this one, then
6774 * it is a chunk that was skipped due to failing the erased
6775 * check. Just skip it so that it can be deleted.
6776 * But, more typically, We get here when this is an unallocated
6777 * chunk and his means that either the block is empty or
6778 * this is the one being allocated from
6781 if (foundChunksInBlock) {
6782 /* This is a chunk that was skipped due to failing the erased check */
6783 } else if (c == 0) {
6784 /* We're looking at the first chunk in the block so the block is unused */
6785 state = YAFFS_BLOCK_STATE_EMPTY;
6786 dev->nErasedBlocks++;
6788 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6789 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6790 if (dev->sequenceNumber == bi->sequenceNumber) {
6791 /* this is the block being allocated from */
6795 (" Allocating from %d %d"
6798 state = YAFFS_BLOCK_STATE_ALLOCATING;
6799 dev->allocationBlock = blk;
6800 dev->allocationPage = c;
6801 dev->allocationBlockFinder = blk;
6803 /* This is a partially written block that is not
6804 * the current allocation block.
6808 (TSTR("Partially written block %d detected" TENDSTR),
6816 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6818 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6823 } else if (tags.chunkId > 0) {
6824 /* chunkId > 0 so it is a data chunk... */
6825 unsigned int endpos;
6827 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6829 foundChunksInBlock = 1;
6832 yaffs_SetChunkBit(dev, blk, c);
6835 in = yaffs_FindOrCreateObjectByNumber(dev,
6838 YAFFS_OBJECT_TYPE_FILE);
6845 in->variantType == YAFFS_OBJECT_TYPE_FILE
6846 && chunkBase < in->variant.fileVariant.shrinkSize) {
6847 /* This has not been invalidated by a resize */
6848 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6852 /* File size is calculated by looking at the data chunks if we have not
6853 * seen an object header yet. Stop this practice once we find an object header.
6855 endpos = chunkBase + tags.byteCount;
6857 if (!in->valid && /* have not got an object header yet */
6858 in->variant.fileVariant.scannedFileSize < endpos) {
6859 in->variant.fileVariant.scannedFileSize = endpos;
6860 in->variant.fileVariant.fileSize = endpos;
6864 /* This chunk has been invalidated by a resize, or a past file deletion
6865 * so delete the chunk*/
6866 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6870 /* chunkId == 0, so it is an ObjectHeader.
6871 * Thus, we read in the object header and make the object
6873 foundChunksInBlock = 1;
6875 yaffs_SetChunkBit(dev, blk, c);
6881 if (tags.extraHeaderInfoAvailable) {
6882 in = yaffs_FindOrCreateObjectByNumber(dev,
6884 tags.extraObjectType);
6890 (!in->valid && dev->param.disableLazyLoad) ||
6891 tags.extraShadows ||
6893 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6894 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6896 /* If we don't have valid info then we need to read the chunk
6897 * TODO In future we can probably defer reading the chunk and
6898 * living with invalid data until needed.
6901 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6906 oh = (yaffs_ObjectHeader *) chunkData;
6908 if (dev->param.inbandTags) {
6909 /* Fix up the header if they got corrupted by inband tags */
6910 oh->shadowsObject = oh->inbandShadowsObject;
6911 oh->isShrink = oh->inbandIsShrink;
6915 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6923 /* TODO Hoosterman we have a problem! */
6924 T(YAFFS_TRACE_ERROR,
6926 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6927 TENDSTR), tags.objectId, chunk));
6932 /* We have already filled this one.
6933 * We have a duplicate that will be discarded, but
6934 * we first have to suck out resize info if it is a file.
6937 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6939 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6940 (tags.extraHeaderInfoAvailable &&
6941 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6943 (oh) ? oh->fileSize : tags.
6945 __u32 parentObjectId =
6947 parentObjectId : tags.
6948 extraParentObjectId;
6952 (oh) ? oh->isShrink : tags.
6953 extraIsShrinkHeader;
6955 /* If it is deleted (unlinked at start also means deleted)
6956 * we treat the file size as being zeroed at this point.
6958 if (parentObjectId ==
6959 YAFFS_OBJECTID_DELETED
6960 || parentObjectId ==
6961 YAFFS_OBJECTID_UNLINKED) {
6966 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6967 in->variant.fileVariant.shrinkSize = thisSize;
6970 bi->hasShrinkHeader = 1;
6973 /* Use existing - destroy this one. */
6974 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6978 if (!in->valid && in->variantType !=
6979 (oh ? oh->type : tags.extraObjectType))
6980 T(YAFFS_TRACE_ERROR, (
6981 TSTR("yaffs tragedy: Bad object type, "
6982 TCONT("%d != %d, for object %d at chunk ")
6983 TCONT("%d during scan")
6985 oh->type : tags.extraObjectType,
6986 in->variantType, tags.objectId,
6990 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6992 YAFFS_OBJECTID_LOSTNFOUND)) {
6993 /* We only load some info, don't fiddle with directory structure */
6997 in->variantType = oh->type;
6999 in->yst_mode = oh->yst_mode;
7000 #ifdef CONFIG_YAFFS_WINCE
7001 in->win_atime[0] = oh->win_atime[0];
7002 in->win_ctime[0] = oh->win_ctime[0];
7003 in->win_mtime[0] = oh->win_mtime[0];
7004 in->win_atime[1] = oh->win_atime[1];
7005 in->win_ctime[1] = oh->win_ctime[1];
7006 in->win_mtime[1] = oh->win_mtime[1];
7008 in->yst_uid = oh->yst_uid;
7009 in->yst_gid = oh->yst_gid;
7010 in->yst_atime = oh->yst_atime;
7011 in->yst_mtime = oh->yst_mtime;
7012 in->yst_ctime = oh->yst_ctime;
7013 in->yst_rdev = oh->yst_rdev;
7017 in->variantType = tags.extraObjectType;
7021 in->hdrChunk = chunk;
7023 } else if (!in->valid) {
7024 /* we need to load this info */
7027 in->hdrChunk = chunk;
7030 in->variantType = oh->type;
7032 in->yst_mode = oh->yst_mode;
7033 #ifdef CONFIG_YAFFS_WINCE
7034 in->win_atime[0] = oh->win_atime[0];
7035 in->win_ctime[0] = oh->win_ctime[0];
7036 in->win_mtime[0] = oh->win_mtime[0];
7037 in->win_atime[1] = oh->win_atime[1];
7038 in->win_ctime[1] = oh->win_ctime[1];
7039 in->win_mtime[1] = oh->win_mtime[1];
7041 in->yst_uid = oh->yst_uid;
7042 in->yst_gid = oh->yst_gid;
7043 in->yst_atime = oh->yst_atime;
7044 in->yst_mtime = oh->yst_mtime;
7045 in->yst_ctime = oh->yst_ctime;
7046 in->yst_rdev = oh->yst_rdev;
7049 if (oh->shadowsObject > 0)
7050 yaffs_HandleShadowedObject(dev,
7057 yaffs_SetObjectName(in, oh->name);
7059 yaffs_FindOrCreateObjectByNumber
7060 (dev, oh->parentObjectId,
7061 YAFFS_OBJECT_TYPE_DIRECTORY);
7063 fileSize = oh->fileSize;
7064 isShrink = oh->isShrink;
7065 equivalentObjectId = oh->equivalentObjectId;
7068 in->variantType = tags.extraObjectType;
7070 yaffs_FindOrCreateObjectByNumber
7071 (dev, tags.extraParentObjectId,
7072 YAFFS_OBJECT_TYPE_DIRECTORY);
7073 fileSize = tags.extraFileLength;
7074 isShrink = tags.extraIsShrinkHeader;
7075 equivalentObjectId = tags.extraEquivalentObjectId;
7084 /* directory stuff...
7088 if (parent && parent->variantType ==
7089 YAFFS_OBJECT_TYPE_UNKNOWN) {
7090 /* Set up as a directory */
7091 parent->variantType =
7092 YAFFS_OBJECT_TYPE_DIRECTORY;
7093 YINIT_LIST_HEAD(&parent->variant.
7096 } else if (!parent || parent->variantType !=
7097 YAFFS_OBJECT_TYPE_DIRECTORY) {
7098 /* Hoosterman, another problem....
7099 * We're trying to use a non-directory as a directory
7102 T(YAFFS_TRACE_ERROR,
7104 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
7106 parent = dev->lostNFoundDir;
7109 yaffs_AddObjectToDirectory(parent, in);
7111 itsUnlinked = (parent == dev->deletedDir) ||
7112 (parent == dev->unlinkedDir);
7115 /* Mark the block as having a shrinkHeader */
7116 bi->hasShrinkHeader = 1;
7119 /* Note re hardlinks.
7120 * Since we might scan a hardlink before its equivalent object is scanned
7121 * we put them all in a list.
7122 * After scanning is complete, we should have all the objects, so we run
7123 * through this list and fix up all the chains.
7126 switch (in->variantType) {
7127 case YAFFS_OBJECT_TYPE_UNKNOWN:
7128 /* Todo got a problem */
7130 case YAFFS_OBJECT_TYPE_FILE:
7132 if (in->variant.fileVariant.
7133 scannedFileSize < fileSize) {
7134 /* This covers the case where the file size is greater
7135 * than where the data is
7136 * This will happen if the file is resized to be larger
7137 * than its current data extents.
7139 in->variant.fileVariant.fileSize = fileSize;
7140 in->variant.fileVariant.scannedFileSize = fileSize;
7143 if (in->variant.fileVariant.shrinkSize > fileSize)
7144 in->variant.fileVariant.shrinkSize = fileSize;
7148 case YAFFS_OBJECT_TYPE_HARDLINK:
7150 in->variant.hardLinkVariant.equivalentObjectId =
7152 in->hardLinks.next =
7153 (struct ylist_head *) hardList;
7157 case YAFFS_OBJECT_TYPE_DIRECTORY:
7160 case YAFFS_OBJECT_TYPE_SPECIAL:
7163 case YAFFS_OBJECT_TYPE_SYMLINK:
7165 in->variant.symLinkVariant.alias =
7166 yaffs_CloneString(oh->alias);
7167 if (!in->variant.symLinkVariant.alias)
7177 } /* End of scanning for each chunk */
7179 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
7180 /* If we got this far while scanning, then the block is fully allocated. */
7181 state = YAFFS_BLOCK_STATE_FULL;
7185 bi->blockState = state;
7187 /* Now let's see if it was dirty */
7188 if (bi->pagesInUse == 0 &&
7189 !bi->hasShrinkHeader &&
7190 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
7191 yaffs_BlockBecameDirty(dev, blk);
7196 yaffs_SkipRestOfBlock(dev);
7199 YFREE_ALT(blockIndex);
7203 /* Ok, we've done all the scanning.
7204 * Fix up the hard link chains.
7205 * We should now have scanned all the objects, now it's time to add these
7208 yaffs_HardlinkFixup(dev, hardList);
7211 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
7216 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
7221 /*------------------------------ Directory Functions ----------------------------- */
7223 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
7225 struct ylist_head *lh;
7226 yaffs_Object *listObj;
7231 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
7236 if (yaffs_SkipVerification(obj->myDev))
7240 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7245 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7246 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7250 /* Iterate through the objects in each hash entry */
7252 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7254 listObj = ylist_entry(lh, yaffs_Object, siblings);
7255 yaffs_VerifyObject(listObj);
7262 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7267 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7269 struct ylist_head *lh;
7270 yaffs_Object *listObj;
7277 if (yaffs_SkipFullVerification(directory->myDev))
7280 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7281 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7285 /* Iterate through the objects in each hash entry */
7287 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7289 listObj = ylist_entry(lh, yaffs_Object, siblings);
7290 if (listObj->parent != directory) {
7291 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7294 yaffs_VerifyObjectInDirectory(listObj);
7300 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7301 * link (ie. name) is created or deleted in the directory.
7304 * create dir/a : update dir's mtime/ctime
7305 * rm dir/a: update dir's mtime/ctime
7306 * modify dir/a: don't update dir's mtimme/ctime
7308 * This can be handled immediately or defered. Defering helps reduce the number
7309 * of updates when many files in a directory are changed within a brief period.
7311 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7312 * called periodically.
7315 static void yaffs_UpdateParent(yaffs_Object *obj)
7323 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7324 if(dev->param.deferDirectoryUpdate){
7325 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
7327 if(ylist_empty(link)){
7328 ylist_add(link,&dev->dirtyDirectories);
7329 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7333 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
7336 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7338 struct ylist_head *link;
7340 yaffs_DirectoryStructure *dS;
7341 yaffs_ObjectVariant *oV;
7343 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7345 while(!ylist_empty(&dev->dirtyDirectories)){
7346 link = dev->dirtyDirectories.next;
7347 ylist_del_init(link);
7349 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7350 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7351 obj = ylist_entry(oV,yaffs_Object,variant);
7353 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7356 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
7360 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7362 yaffs_Device *dev = obj->myDev;
7363 yaffs_Object *parent;
7365 yaffs_VerifyObjectInDirectory(obj);
7366 parent = obj->parent;
7368 yaffs_VerifyDirectory(parent);
7370 if (dev && dev->param.removeObjectCallback)
7371 dev->param.removeObjectCallback(obj);
7374 ylist_del_init(&obj->siblings);
7377 yaffs_VerifyDirectory(parent);
7380 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7384 T(YAFFS_TRACE_ALWAYS,
7386 ("tragedy: Trying to add an object to a null pointer directory"
7391 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7392 T(YAFFS_TRACE_ALWAYS,
7394 ("tragedy: Trying to add an object to a non-directory"
7399 if (obj->siblings.prev == NULL) {
7400 /* Not initialised */
7405 yaffs_VerifyDirectory(directory);
7407 yaffs_RemoveObjectFromDirectory(obj);
7411 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7412 obj->parent = directory;
7414 if (directory == obj->myDev->unlinkedDir
7415 || directory == obj->myDev->deletedDir) {
7417 obj->myDev->nUnlinkedFiles++;
7418 obj->renameAllowed = 0;
7421 yaffs_VerifyDirectory(directory);
7422 yaffs_VerifyObjectInDirectory(obj);
7425 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7430 struct ylist_head *i;
7431 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7439 T(YAFFS_TRACE_ALWAYS,
7441 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7446 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7447 T(YAFFS_TRACE_ALWAYS,
7449 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7453 sum = yaffs_CalcNameSum(name);
7455 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7457 l = ylist_entry(i, yaffs_Object, siblings);
7459 if (l->parent != directory)
7462 yaffs_CheckObjectDetailsLoaded(l);
7464 /* Special case for lost-n-found */
7465 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7466 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7468 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7469 /* LostnFound chunk called Objxxx
7472 yaffs_GetObjectName(l, buffer,
7473 YAFFS_MAX_NAME_LENGTH + 1);
7474 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7485 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7486 int (*fn) (yaffs_Object *))
7488 struct ylist_head *i;
7492 T(YAFFS_TRACE_ALWAYS,
7494 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7499 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7500 T(YAFFS_TRACE_ALWAYS,
7502 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7507 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7509 l = ylist_entry(i, yaffs_Object, siblings);
7520 /* GetEquivalentObject dereferences any hard links to get to the
7524 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7526 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7527 /* We want the object id of the equivalent object, not this one */
7528 obj = obj->variant.hardLinkVariant.equivalentObject;
7529 yaffs_CheckObjectDetailsLoaded(obj);
7534 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7536 memset(name, 0, buffSize * sizeof(YCHAR));
7538 yaffs_CheckObjectDetailsLoaded(obj);
7540 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7541 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7542 } else if (obj->hdrChunk <= 0) {
7544 YCHAR numString[20];
7545 YCHAR *x = &numString[19];
7546 unsigned v = obj->objectId;
7550 *x = '0' + (v % 10);
7553 /* make up a name */
7554 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7555 yaffs_strcat(locName, x);
7556 yaffs_strncpy(name, locName, buffSize - 1);
7559 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7560 else if (obj->shortName[0])
7561 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7565 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7567 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7569 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7571 if (obj->hdrChunk > 0) {
7572 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7573 obj->hdrChunk, buffer,
7576 yaffs_strncpy(name, oh->name, buffSize - 1);
7579 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7582 return yaffs_strnlen(name,buffSize-1);
7585 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7587 /* Dereference any hard linking */
7588 obj = yaffs_GetEquivalentObject(obj);
7590 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7591 return obj->variant.fileVariant.fileSize;
7592 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7593 if(!obj->variant.symLinkVariant.alias)
7595 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7597 /* Only a directory should drop through to here */
7598 return obj->myDev->nDataBytesPerChunk;
7602 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7605 struct ylist_head *i;
7608 count++; /* the object itself */
7610 ylist_for_each(i, &obj->hardLinks)
7611 count++; /* add the hard links; */
7616 int yaffs_GetObjectInode(yaffs_Object *obj)
7618 obj = yaffs_GetEquivalentObject(obj);
7620 return obj->objectId;
7623 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7625 obj = yaffs_GetEquivalentObject(obj);
7627 switch (obj->variantType) {
7628 case YAFFS_OBJECT_TYPE_FILE:
7631 case YAFFS_OBJECT_TYPE_DIRECTORY:
7634 case YAFFS_OBJECT_TYPE_SYMLINK:
7637 case YAFFS_OBJECT_TYPE_HARDLINK:
7640 case YAFFS_OBJECT_TYPE_SPECIAL:
7641 if (S_ISFIFO(obj->yst_mode))
7643 if (S_ISCHR(obj->yst_mode))
7645 if (S_ISBLK(obj->yst_mode))
7647 if (S_ISSOCK(obj->yst_mode))
7655 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7657 obj = yaffs_GetEquivalentObject(obj);
7658 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7659 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7661 return yaffs_CloneString(_Y(""));
7664 #ifndef CONFIG_YAFFS_WINCE
7666 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7668 unsigned int valid = attr->ia_valid;
7670 if (valid & ATTR_MODE)
7671 obj->yst_mode = attr->ia_mode;
7672 if (valid & ATTR_UID)
7673 obj->yst_uid = attr->ia_uid;
7674 if (valid & ATTR_GID)
7675 obj->yst_gid = attr->ia_gid;
7677 if (valid & ATTR_ATIME)
7678 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7679 if (valid & ATTR_CTIME)
7680 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7681 if (valid & ATTR_MTIME)
7682 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7684 if (valid & ATTR_SIZE)
7685 yaffs_ResizeFile(obj, attr->ia_size);
7687 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0, NULL);
7692 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7694 unsigned int valid = 0;
7696 attr->ia_mode = obj->yst_mode;
7698 attr->ia_uid = obj->yst_uid;
7700 attr->ia_gid = obj->yst_gid;
7703 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7704 valid |= ATTR_ATIME;
7705 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7706 valid |= ATTR_CTIME;
7707 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7708 valid |= ATTR_MTIME;
7710 attr->ia_size = yaffs_GetFileSize(obj);
7713 attr->ia_valid = valid;
7721 static int yaffs_DoXMod(yaffs_Object *obj, int set, const char *name, const void *value, int size, int flags)
7723 yaffs_XAttrMod xmod;
7732 xmod.result = -ENOSPC;
7734 result = yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, &xmod);
7742 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod)
7745 int x_offs = sizeof(yaffs_ObjectHeader);
7746 int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
7748 char * x_buffer = buffer + x_offs;
7751 retval = nval_set(x_buffer, x_size, xmod->name, xmod->data, xmod->size, xmod->flags);
7753 retval = nval_del(x_buffer, x_size, xmod->name);
7755 xmod->result = retval;
7760 static int yaffs_DoXFetch(yaffs_Object *obj, const char *name, void *value, int size)
7762 char *buffer = NULL;
7764 yaffs_ExtendedTags tags;
7765 yaffs_Device *dev = obj->myDev;
7766 int x_offs = sizeof(yaffs_ObjectHeader);
7767 int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
7773 if(obj->hdrChunk < 1)
7776 buffer = yaffs_GetTempBuffer(dev, __LINE__);
7780 result = yaffs_ReadChunkWithTagsFromNAND(dev,obj->hdrChunk, buffer, &tags);
7782 if(result != YAFFS_OK)
7785 x_buffer = buffer + x_offs;
7788 retval = nval_get(x_buffer, x_size, name, value, size);
7790 retval = nval_list(x_buffer, x_size, value,size);
7792 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
7796 int yaffs_SetXAttribute(yaffs_Object *obj, const char *name, const void * value, int size, int flags)
7798 return yaffs_DoXMod(obj, 1, name, value, size, flags);
7801 int yaffs_RemoveXAttribute(yaffs_Object *obj, const char *name)
7803 return yaffs_DoXMod(obj, 0, name, NULL, 0, 0);
7806 int yaffs_GetXAttribute(yaffs_Object *obj, const char *name, void *value, int size)
7808 return yaffs_DoXFetch(obj, name, value, size);
7811 int yaffs_ListXAttributes(yaffs_Object *obj, char *buffer, int size)
7813 return yaffs_DoXFetch(obj, NULL, buffer,size);
7819 int yaffs_DumpObject(yaffs_Object *obj)
7823 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7825 T(YAFFS_TRACE_ALWAYS,
7827 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7828 " chunk %d type %d size %d\n"
7829 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7830 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7831 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7837 /*---------------------------- Initialisation code -------------------------------------- */
7839 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7842 /* Common functions, gotta have */
7843 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7846 #ifdef CONFIG_YAFFS_YAFFS2
7848 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7849 if (dev->param.writeChunkWithTagsToNAND &&
7850 dev->param.readChunkWithTagsFromNAND &&
7851 !dev->param.writeChunkToNAND &&
7852 !dev->param.readChunkFromNAND &&
7853 dev->param.markNANDBlockBad &&
7854 dev->param.queryNANDBlock)
7858 /* Can use the "spare" style interface for yaffs1 */
7859 if (!dev->param.isYaffs2 &&
7860 !dev->param.writeChunkWithTagsToNAND &&
7861 !dev->param.readChunkWithTagsFromNAND &&
7862 dev->param.writeChunkToNAND &&
7863 dev->param.readChunkFromNAND &&
7864 !dev->param.markNANDBlockBad &&
7865 !dev->param.queryNANDBlock)
7872 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7874 /* Initialise the unlinked, deleted, root and lost and found directories */
7876 dev->lostNFoundDir = dev->rootDir = NULL;
7877 dev->unlinkedDir = dev->deletedDir = NULL;
7880 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7883 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7886 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7887 YAFFS_ROOT_MODE | S_IFDIR);
7888 dev->lostNFoundDir =
7889 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7890 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7892 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7893 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7900 int yaffs_GutsInitialise(yaffs_Device *dev)
7902 int init_failed = 0;
7906 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7908 /* Check stuff that must be set */
7911 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7915 dev->internalStartBlock = dev->param.startBlock;
7916 dev->internalEndBlock = dev->param.endBlock;
7917 dev->blockOffset = 0;
7918 dev->chunkOffset = 0;
7919 dev->nFreeChunks = 0;
7923 if (dev->param.startBlock == 0) {
7924 dev->internalStartBlock = dev->param.startBlock + 1;
7925 dev->internalEndBlock = dev->param.endBlock + 1;
7926 dev->blockOffset = 1;
7927 dev->chunkOffset = dev->param.nChunksPerBlock;
7930 /* Check geometry parameters. */
7932 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7933 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7934 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7935 dev->param.nChunksPerBlock < 2 ||
7936 dev->param.nReservedBlocks < 2 ||
7937 dev->internalStartBlock <= 0 ||
7938 dev->internalEndBlock <= 0 ||
7939 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7940 T(YAFFS_TRACE_ALWAYS,
7942 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7943 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7947 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7948 T(YAFFS_TRACE_ALWAYS,
7949 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7953 /* Sort out space for inband tags, if required */
7954 if (dev->param.inbandTags)
7955 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7957 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7959 /* Got the right mix of functions? */
7960 if (!yaffs_CheckDevFunctions(dev)) {
7961 /* Function missing */
7962 T(YAFFS_TRACE_ALWAYS,
7964 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7969 /* This is really a compilation check. */
7970 if (!yaffs_CheckStructures()) {
7971 T(YAFFS_TRACE_ALWAYS,
7972 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7976 if (dev->isMounted) {
7977 T(YAFFS_TRACE_ALWAYS,
7978 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7982 /* Finished with most checks. One or two more checks happen later on too. */
7986 /* OK now calculate a few things for the device */
7989 * Calculate all the chunk size manipulation numbers:
7991 x = dev->nDataBytesPerChunk;
7992 /* We always use dev->chunkShift and dev->chunkDiv */
7993 dev->chunkShift = Shifts(x);
7994 x >>= dev->chunkShift;
7996 /* We only use chunk mask if chunkDiv is 1 */
7997 dev->chunkMask = (1<<dev->chunkShift) - 1;
8000 * Calculate chunkGroupBits.
8001 * We need to find the next power of 2 > than internalEndBlock
8004 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
8008 /* Set up tnode width if wide tnodes are enabled. */
8009 if (!dev->param.wideTnodesDisabled) {
8010 /* bits must be even so that we end up with 32-bit words */
8014 dev->tnodeWidth = 16;
8016 dev->tnodeWidth = bits;
8018 dev->tnodeWidth = 16;
8020 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
8022 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
8023 * so if the bitwidth of the
8024 * chunk range we're using is greater than 16 we need
8025 * to figure out chunk shift and chunkGroupSize
8028 if (bits <= dev->tnodeWidth)
8029 dev->chunkGroupBits = 0;
8031 dev->chunkGroupBits = bits - dev->tnodeWidth;
8034 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
8036 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
8037 /* We have a problem because the soft delete won't work if
8038 * the chunk group size > chunks per block.
8039 * This can be remedied by using larger "virtual blocks".
8041 T(YAFFS_TRACE_ALWAYS,
8042 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
8047 /* OK, we've finished verifying the device, lets continue with initialisation */
8049 /* More device initialisation */
8051 dev->passiveGCs = 0;
8052 dev->oldestDirtyGCs = 0;
8053 dev->backgroundGCs = 0;
8054 dev->gcBlockFinder = 0;
8055 dev->bufferedBlock = -1;
8056 dev->doingBufferedBlockRewrite = 0;
8057 dev->nDeletedFiles = 0;
8058 dev->nBackgroundDeletions = 0;
8059 dev->nUnlinkedFiles = 0;
8061 dev->eccUnfixed = 0;
8062 dev->tagsEccFixed = 0;
8063 dev->tagsEccUnfixed = 0;
8064 dev->nErasureFailures = 0;
8065 dev->nErasedBlocks = 0;
8067 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
8068 YINIT_LIST_HEAD(&dev->dirtyDirectories);
8069 dev->oldestDirtySequence = 0;
8070 dev->oldestDirtyBlock = 0;
8072 /* Initialise temporary buffers and caches. */
8073 if (!yaffs_InitialiseTempBuffers(dev))
8076 dev->srCache = NULL;
8077 dev->gcCleanupList = NULL;
8081 dev->param.nShortOpCaches > 0) {
8084 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
8086 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
8087 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
8089 dev->srCache = YMALLOC(srCacheBytes);
8091 buf = (__u8 *) dev->srCache;
8094 memset(dev->srCache, 0, srCacheBytes);
8096 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
8097 dev->srCache[i].object = NULL;
8098 dev->srCache[i].lastUse = 0;
8099 dev->srCache[i].dirty = 0;
8100 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
8111 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
8112 if (!dev->gcCleanupList)
8116 if (dev->param.isYaffs2)
8117 dev->param.useHeaderFileSize = 1;
8119 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8122 yaffs_InitialiseTnodes(dev);
8123 yaffs_InitialiseObjects(dev);
8125 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8130 /* Now scan the flash. */
8131 if (dev->param.isYaffs2) {
8132 if (yaffs_CheckpointRestore(dev)) {
8133 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
8134 T(YAFFS_TRACE_ALWAYS,
8135 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
8138 /* Clean up the mess caused by an aborted checkpoint load
8139 * and scan backwards.
8141 yaffs_DeinitialiseBlocks(dev);
8142 yaffs_DeinitialiseTnodes(dev);
8143 yaffs_DeinitialiseObjects(dev);
8146 dev->nErasedBlocks = 0;
8147 dev->nFreeChunks = 0;
8148 dev->allocationBlock = -1;
8149 dev->allocationPage = -1;
8150 dev->nDeletedFiles = 0;
8151 dev->nUnlinkedFiles = 0;
8152 dev->nBackgroundDeletions = 0;
8154 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8157 yaffs_InitialiseTnodes(dev);
8158 yaffs_InitialiseObjects(dev);
8160 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8163 if (!init_failed && !yaffs_ScanBackwards(dev))
8166 } else if (!yaffs_Scan(dev))
8169 yaffs_StripDeletedObjects(dev);
8170 yaffs_FixHangingObjects(dev);
8171 if(dev->param.emptyLostAndFound)
8172 yaffs_EmptyLostAndFound(dev);
8176 /* Clean up the mess */
8177 T(YAFFS_TRACE_TRACING,
8178 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
8180 yaffs_Deinitialise(dev);
8184 /* Zero out stats */
8185 dev->nPageReads = 0;
8186 dev->nPageWrites = 0;
8187 dev->nBlockErasures = 0;
8189 dev->nRetriedWrites = 0;
8191 dev->nRetiredBlocks = 0;
8193 yaffs_VerifyFreeChunks(dev);
8194 yaffs_VerifyBlocks(dev);
8196 /* Clean up any aborted checkpoint data */
8197 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
8198 yaffs_InvalidateCheckpoint(dev);
8200 T(YAFFS_TRACE_TRACING,
8201 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
8206 void yaffs_Deinitialise(yaffs_Device *dev)
8208 if (dev->isMounted) {
8211 yaffs_DeinitialiseBlocks(dev);
8212 yaffs_DeinitialiseTnodes(dev);
8213 yaffs_DeinitialiseObjects(dev);
8214 if (dev->param.nShortOpCaches > 0 &&
8217 for (i = 0; i < dev->param.nShortOpCaches; i++) {
8218 if (dev->srCache[i].data)
8219 YFREE(dev->srCache[i].data);
8220 dev->srCache[i].data = NULL;
8223 YFREE(dev->srCache);
8224 dev->srCache = NULL;
8227 YFREE(dev->gcCleanupList);
8229 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
8230 YFREE(dev->tempBuffer[i].buffer);
8234 if (dev->param.deinitialiseNAND)
8235 dev->param.deinitialiseNAND(dev);
8239 static int yaffs_CountFreeChunks(yaffs_Device *dev)
8244 yaffs_BlockInfo *blk;
8246 blk = dev->blockInfo;
8247 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
8248 switch (blk->blockState) {
8249 case YAFFS_BLOCK_STATE_EMPTY:
8250 case YAFFS_BLOCK_STATE_ALLOCATING:
8251 case YAFFS_BLOCK_STATE_COLLECTING:
8252 case YAFFS_BLOCK_STATE_FULL:
8254 (dev->param.nChunksPerBlock - blk->pagesInUse +
8255 blk->softDeletions);
8266 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
8268 /* This is what we report to the outside world */
8271 int nDirtyCacheChunks;
8272 int blocksForCheckpoint;
8276 nFree = dev->nFreeChunks;
8278 nFree = yaffs_CountFreeChunks(dev);
8281 nFree += dev->nDeletedFiles;
8283 /* Now count the number of dirty chunks in the cache and subtract those */
8285 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
8286 if (dev->srCache[i].dirty)
8287 nDirtyCacheChunks++;
8290 nFree -= nDirtyCacheChunks;
8292 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
8294 /* Now we figure out how much to reserve for the checkpoint and report that... */
8295 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
8296 if (blocksForCheckpoint < 0)
8297 blocksForCheckpoint = 0;
8299 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
8308 static int yaffs_freeVerificationFailures;
8310 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
8315 if (yaffs_SkipVerification(dev))
8318 counted = yaffs_CountFreeChunks(dev);
8320 difference = dev->nFreeChunks - counted;
8323 T(YAFFS_TRACE_ALWAYS,
8324 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
8325 dev->nFreeChunks, counted, difference));
8326 yaffs_freeVerificationFailures++;
8330 /*---------------------------------------- YAFFS test code ----------------------*/
8332 #define yaffs_CheckStruct(structure, syze, name) \
8334 if (sizeof(structure) != syze) { \
8335 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
8336 name, syze, (int) sizeof(structure))); \
8337 return YAFFS_FAIL; \
8341 static int yaffs_CheckStructures(void)
8343 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8344 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8345 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8346 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8347 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8349 #ifndef CONFIG_YAFFS_WINCE
8350 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");