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"
33 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
34 #define YAFFS_GC_GOOD_ENOUGH 2
35 #define YAFFS_GC_PASSIVE_THRESHOLD 4
37 #define YAFFS_SMALL_HOLE_THRESHOLD 3
40 * Checkpoints are really no benefit on very small partitions.
42 * To save space on small partitions don't bother with checkpoints unless
43 * the partition is at least this big.
45 #define YAFFS_CHECKPOINT_MIN_BLOCKS 60
47 #include "yaffs_ecc.h"
50 /* Robustification (if it ever comes about...) */
51 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
52 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
54 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
56 const yaffs_ExtendedTags *tags);
57 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
58 const yaffs_ExtendedTags *tags);
60 /* Other local prototypes */
61 static void yaffs_UpdateParent(yaffs_Object *obj);
62 static int yaffs_UnlinkObject(yaffs_Object *obj);
63 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
65 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
67 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
69 yaffs_ExtendedTags *tags,
71 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
72 int chunkInNAND, int inScan);
74 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
75 yaffs_ObjectType type);
76 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
78 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
79 int force, int isShrink, int shadows);
80 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
81 static int yaffs_CheckStructures(void);
82 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
84 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
87 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
90 static int yaffs_UnlinkWorker(yaffs_Object *obj);
92 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
95 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
96 yaffs_BlockInfo **blockUsedPtr);
98 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
100 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
102 static void yaffs_VerifyDirectory(yaffs_Object *directory);
103 #ifdef YAFFS_PARANOID
104 static int yaffs_CheckFileSanity(yaffs_Object *in);
106 #define yaffs_CheckFileSanity(in)
109 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
110 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
112 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
114 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
115 yaffs_ExtendedTags *tags);
117 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
119 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
120 yaffs_FileStructure *fStruct,
123 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize);
124 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
125 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
128 yaffs_ExtendedTags *tags);
130 /* Function to calculate chunk and offset */
132 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
138 chunk = (__u32)(addr >> dev->chunkShift);
140 if (dev->chunkDiv == 1) {
141 /* easy power of 2 case */
142 offset = (__u32)(addr & dev->chunkMask);
144 /* Non power-of-2 case */
148 chunk /= dev->chunkDiv;
150 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
151 offset = (__u32)(addr - chunkBase);
158 /* Function to return the number of shifts for a power of 2 greater than or
159 * equal to the given number
160 * Note we don't try to cater for all possible numbers and this does not have to
161 * be hellishly efficient.
164 static __u32 ShiftsGE(__u32 x)
169 nShifts = extraBits = 0;
184 /* Function to return the number of shifts to get a 1 in bit 0
187 static __u32 Shifts(__u32 x)
207 * Temporary buffer manipulations.
210 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
213 __u8 *buf = (__u8 *)1;
215 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
217 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
218 dev->tempBuffer[i].line = 0; /* not in use */
219 dev->tempBuffer[i].buffer = buf =
220 YMALLOC_DMA(dev->param.totalBytesPerChunk);
223 return buf ? YAFFS_OK : YAFFS_FAIL;
226 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
231 if (dev->tempInUse > dev->maxTemp)
232 dev->maxTemp = dev->tempInUse;
234 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
235 if (dev->tempBuffer[i].line == 0) {
236 dev->tempBuffer[i].line = lineNo;
237 if ((i + 1) > dev->maxTemp) {
238 dev->maxTemp = i + 1;
239 for (j = 0; j <= i; j++)
240 dev->tempBuffer[j].maxLine =
241 dev->tempBuffer[j].line;
244 return dev->tempBuffer[i].buffer;
248 T(YAFFS_TRACE_BUFFERS,
249 (TSTR("Out of temp buffers at line %d, other held by lines:"),
251 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
252 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
254 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
257 * If we got here then we have to allocate an unmanaged one
261 dev->unmanagedTempAllocations++;
262 return YMALLOC(dev->nDataBytesPerChunk);
266 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
273 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
274 if (dev->tempBuffer[i].buffer == buffer) {
275 dev->tempBuffer[i].line = 0;
281 /* assume it is an unmanaged one. */
282 T(YAFFS_TRACE_BUFFERS,
283 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
286 dev->unmanagedTempDeallocations++;
292 * Determine if we have a managed buffer.
294 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
298 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
299 if (dev->tempBuffer[i].buffer == buffer)
303 for (i = 0; i < dev->param.nShortOpCaches; i++) {
304 if (dev->srCache[i].data == buffer)
308 if (buffer == dev->checkpointBuffer)
311 T(YAFFS_TRACE_ALWAYS,
312 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
319 * Chunk bitmap manipulations
322 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
324 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
326 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
330 return dev->chunkBits +
331 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
334 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
336 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
337 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
339 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
345 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
347 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 memset(blkBits, 0, dev->chunkBitmapStride);
352 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
354 __u8 *blkBits = yaffs_BlockBits(dev, blk);
356 yaffs_VerifyChunkBitId(dev, blk, chunk);
358 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
361 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
363 __u8 *blkBits = yaffs_BlockBits(dev, blk);
365 yaffs_VerifyChunkBitId(dev, blk, chunk);
367 blkBits[chunk / 8] |= (1 << (chunk & 7));
370 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
372 __u8 *blkBits = yaffs_BlockBits(dev, blk);
373 yaffs_VerifyChunkBitId(dev, blk, chunk);
375 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
378 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
380 __u8 *blkBits = yaffs_BlockBits(dev, blk);
382 for (i = 0; i < dev->chunkBitmapStride; i++) {
390 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
392 __u8 *blkBits = yaffs_BlockBits(dev, blk);
395 for (i = 0; i < dev->chunkBitmapStride; i++) {
412 static int yaffs_SkipVerification(yaffs_Device *dev)
415 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
418 static int yaffs_SkipFullVerification(yaffs_Device *dev)
421 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
424 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
427 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
430 static const char *blockStateName[] = {
443 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
448 if (yaffs_SkipVerification(dev))
451 /* Report illegal runtime states */
452 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
453 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
455 switch (bi->blockState) {
456 case YAFFS_BLOCK_STATE_UNKNOWN:
457 case YAFFS_BLOCK_STATE_SCANNING:
458 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
459 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
460 n, blockStateName[bi->blockState]));
463 /* Check pages in use and soft deletions are legal */
465 actuallyUsed = bi->pagesInUse - bi->softDeletions;
467 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
468 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
469 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
470 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
471 n, bi->pagesInUse, bi->softDeletions));
474 /* Check chunk bitmap legal */
475 inUse = yaffs_CountChunkBits(dev, n);
476 if (inUse != bi->pagesInUse)
477 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
478 n, bi->pagesInUse, inUse));
480 /* Check that the sequence number is valid.
481 * Ten million is legal, but is very unlikely
483 if (dev->param.isYaffs2 &&
484 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
485 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
486 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
487 n, bi->sequenceNumber));
490 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
493 yaffs_VerifyBlock(dev, bi, n);
495 /* After collection the block should be in the erased state */
496 /* This will need to change if we do partial gc */
498 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
499 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
500 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
505 static void yaffs_VerifyBlocks(yaffs_Device *dev)
508 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
509 int nIllegalBlockStates = 0;
511 if (yaffs_SkipVerification(dev))
514 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
516 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
517 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
518 yaffs_VerifyBlock(dev, bi, i);
520 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
521 nBlocksPerState[bi->blockState]++;
523 nIllegalBlockStates++;
526 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
527 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
529 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
530 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
531 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
533 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
534 T(YAFFS_TRACE_VERIFY,
535 (TSTR("%s %d blocks"TENDSTR),
536 blockStateName[i], nBlocksPerState[i]));
538 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
539 T(YAFFS_TRACE_VERIFY,
540 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
541 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
543 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
544 T(YAFFS_TRACE_VERIFY,
545 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
546 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
548 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
549 T(YAFFS_TRACE_VERIFY,
550 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
551 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
553 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
558 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
559 * case those tests will not be performed.
561 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
563 if (obj && yaffs_SkipVerification(obj->myDev))
566 if (!(tags && obj && oh)) {
567 T(YAFFS_TRACE_VERIFY,
568 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
573 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
574 oh->type > YAFFS_OBJECT_TYPE_MAX)
575 T(YAFFS_TRACE_VERIFY,
576 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
577 tags->objectId, oh->type));
579 if (tags->objectId != obj->objectId)
580 T(YAFFS_TRACE_VERIFY,
581 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
582 tags->objectId, obj->objectId));
586 * Check that the object's parent ids match if parentCheck requested.
588 * Tests do not apply to the root object.
591 if (parentCheck && tags->objectId > 1 && !obj->parent)
592 T(YAFFS_TRACE_VERIFY,
593 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
594 tags->objectId, oh->parentObjectId));
596 if (parentCheck && obj->parent &&
597 oh->parentObjectId != obj->parent->objectId &&
598 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
599 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
602 tags->objectId, oh->parentObjectId, obj->parent->objectId));
604 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
605 T(YAFFS_TRACE_VERIFY,
606 (TSTR("Obj %d header name is NULL"TENDSTR),
609 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
610 T(YAFFS_TRACE_VERIFY,
611 (TSTR("Obj %d header name is 0xFF"TENDSTR),
617 /* Not being used, but don't want to throw away yet */
618 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
619 __u32 level, int chunkOffset)
622 yaffs_Device *dev = obj->myDev;
628 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
629 if (tn->internal[i]) {
630 ok = yaffs_VerifyTnodeWorker(obj,
633 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
636 } else if (level == 0) {
637 yaffs_ExtendedTags tags;
638 __u32 objectId = obj->objectId;
640 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
642 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
643 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
646 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
647 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
648 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
649 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
650 objectId, chunkOffset, theChunk,
651 tags.objectId, tags.chunkId));
665 static void yaffs_VerifyFile(yaffs_Object *obj)
667 int requiredTallness;
673 yaffs_ExtendedTags tags;
680 if (yaffs_SkipVerification(obj->myDev))
684 objectId = obj->objectId;
686 /* Check file size is consistent with tnode depth */
687 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
688 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
689 requiredTallness = 0;
691 x >>= YAFFS_TNODES_INTERNAL_BITS;
695 actualTallness = obj->variant.fileVariant.topLevel;
697 /* Check that the chunks in the tnode tree are all correct.
698 * We do this by scanning through the tnode tree and
699 * checking the tags for every chunk match.
702 if (yaffs_SkipNANDVerification(dev))
705 for (i = 1; i <= lastChunk; i++) {
706 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
709 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
711 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
712 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
713 if (tags.objectId != objectId || tags.chunkId != i) {
714 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
715 objectId, i, theChunk,
716 tags.objectId, tags.chunkId));
724 static void yaffs_VerifyHardLink(yaffs_Object *obj)
726 if (obj && yaffs_SkipVerification(obj->myDev))
729 /* Verify sane equivalent object */
732 static void yaffs_VerifySymlink(yaffs_Object *obj)
734 if (obj && yaffs_SkipVerification(obj->myDev))
737 /* Verify symlink string */
740 static void yaffs_VerifySpecial(yaffs_Object *obj)
742 if (obj && yaffs_SkipVerification(obj->myDev))
746 static void yaffs_VerifyObject(yaffs_Object *obj)
755 __u32 chunkShouldNotBeDeleted;
761 if (obj->beingCreated)
766 if (yaffs_SkipVerification(dev))
769 /* Check sane object header chunk */
771 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
772 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
774 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
775 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
776 chunkValid = chunkInRange &&
777 yaffs_CheckChunkBit(dev,
778 obj->hdrChunk / dev->param.nChunksPerBlock,
779 obj->hdrChunk % dev->param.nChunksPerBlock);
780 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
783 (!chunkIdOk || chunkShouldNotBeDeleted)) {
784 T(YAFFS_TRACE_VERIFY,
785 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
786 obj->objectId, obj->hdrChunk,
787 chunkIdOk ? "" : ",out of range",
788 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
791 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
792 yaffs_ExtendedTags tags;
793 yaffs_ObjectHeader *oh;
794 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
796 oh = (yaffs_ObjectHeader *)buffer;
798 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
801 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
803 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
806 /* Verify it has a parent */
807 if (obj && !obj->fake &&
808 (!obj->parent || obj->parent->myDev != dev)) {
809 T(YAFFS_TRACE_VERIFY,
810 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
811 obj->objectId, obj->parent));
814 /* Verify parent is a directory */
815 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
816 T(YAFFS_TRACE_VERIFY,
817 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
818 obj->objectId, obj->parent->variantType));
821 switch (obj->variantType) {
822 case YAFFS_OBJECT_TYPE_FILE:
823 yaffs_VerifyFile(obj);
825 case YAFFS_OBJECT_TYPE_SYMLINK:
826 yaffs_VerifySymlink(obj);
828 case YAFFS_OBJECT_TYPE_DIRECTORY:
829 yaffs_VerifyDirectory(obj);
831 case YAFFS_OBJECT_TYPE_HARDLINK:
832 yaffs_VerifyHardLink(obj);
834 case YAFFS_OBJECT_TYPE_SPECIAL:
835 yaffs_VerifySpecial(obj);
837 case YAFFS_OBJECT_TYPE_UNKNOWN:
839 T(YAFFS_TRACE_VERIFY,
840 (TSTR("Obj %d has illegaltype %d"TENDSTR),
841 obj->objectId, obj->variantType));
846 static void yaffs_VerifyObjects(yaffs_Device *dev)
850 struct ylist_head *lh;
852 if (yaffs_SkipVerification(dev))
855 /* Iterate through the objects in each hash entry */
857 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
858 ylist_for_each(lh, &dev->objectBucket[i].list) {
860 obj = ylist_entry(lh, yaffs_Object, hashLink);
861 yaffs_VerifyObject(obj);
869 * Simple hash function. Needs to have a reasonable spread
872 static Y_INLINE int yaffs_HashFunction(int n)
875 return n % YAFFS_NOBJECT_BUCKETS;
879 * Access functions to useful fake objects.
880 * Note that root might have a presence in NAND if permissions are set.
883 yaffs_Object *yaffs_Root(yaffs_Device *dev)
888 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
890 return dev->lostNFoundDir;
895 * Erased NAND checking functions
898 int yaffs_CheckFF(__u8 *buffer, int nBytes)
900 /* Horrible, slow implementation */
909 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
912 int retval = YAFFS_OK;
913 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
914 yaffs_ExtendedTags tags;
917 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
919 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
922 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
923 T(YAFFS_TRACE_NANDACCESS,
924 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
928 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
935 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
938 yaffs_ExtendedTags *tags)
940 int retval = YAFFS_OK;
941 yaffs_ExtendedTags tempTags;
942 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
945 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
946 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
947 tempTags.objectId != tags->objectId ||
948 tempTags.chunkId != tags->chunkId ||
949 tempTags.byteCount != tags->byteCount)
952 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
957 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
959 yaffs_ExtendedTags *tags,
966 yaffs_InvalidateCheckpoint(dev);
969 yaffs_BlockInfo *bi = 0;
972 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
978 /* First check this chunk is erased, if it needs
979 * checking. The checking policy (unless forced
980 * always on) is as follows:
982 * Check the first page we try to write in a block.
983 * If the check passes then we don't need to check any
984 * more. If the check fails, we check again...
985 * If the block has been erased, we don't need to check.
987 * However, if the block has been prioritised for gc,
988 * then we think there might be something odd about
989 * this block and stop using it.
991 * Rationale: We should only ever see chunks that have
992 * not been erased if there was a partially written
993 * chunk due to power loss. This checking policy should
994 * catch that case with very few checks and thus save a
995 * lot of checks that are most likely not needed.
998 * If an erase check fails or the write fails we skip the
1002 /* let's give it a try */
1005 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
1006 bi->skipErasedCheck = 0;
1008 if (!bi->skipErasedCheck) {
1009 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1010 if (erasedOk != YAFFS_OK) {
1011 T(YAFFS_TRACE_ERROR,
1012 (TSTR("**>> yaffs chunk %d was not erased"
1015 /* If not erased, delete this one,
1016 * skip rest of block and
1017 * try another chunk */
1018 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1019 yaffs_SkipRestOfBlock(dev);
1024 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1027 if(!bi->skipErasedCheck)
1028 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1030 if (writeOk != YAFFS_OK) {
1031 /* Clean up aborted write, skip to next block and
1032 * try another chunk */
1033 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1037 bi->skipErasedCheck = 1;
1039 /* Copy the data into the robustification buffer */
1040 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1042 } while (writeOk != YAFFS_OK &&
1043 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1049 T(YAFFS_TRACE_ERROR,
1050 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1053 dev->nRetriedWrites += (attempts - 1);
1061 * Oldest Dirty Sequence Number handling.
1064 /* yaffs_CalcOldestDirtySequence()
1065 * yaffs_FindOldestDirtySequence()
1066 * Calculate the oldest dirty sequence number if we don't know it.
1068 static void yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1072 unsigned blockNo = 0;
1075 if(!dev->param.isYaffs2)
1078 /* Find the oldest dirty sequence number. */
1079 seq = dev->sequenceNumber + 1;
1081 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1082 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1083 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1084 b->sequenceNumber < seq) {
1085 seq = b->sequenceNumber;
1092 dev->oldestDirtySequence = seq;
1093 dev->oldestDirtyBlock = blockNo;
1099 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1101 if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1102 yaffs_CalcOldestDirtySequence(dev);
1106 * yaffs_ClearOldestDirtySequence()
1107 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1108 * becomes invalid). If the value matches the oldest then we clear
1109 * dev->oldestDirtySequence to force its recomputation.
1111 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1114 if(!dev->param.isYaffs2)
1117 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence){
1118 dev->oldestDirtySequence = 0;
1119 dev->oldestDirtyBlock = 0;
1124 * yaffs_UpdateOldestDirtySequence()
1125 * Update the oldest dirty sequence number whenever we dirty a block.
1126 * Only do this if the oldestDirtySequence is actually being tracked.
1128 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, unsigned blockNo, yaffs_BlockInfo *bi)
1130 if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1131 if(dev->oldestDirtySequence > bi->sequenceNumber){
1132 dev->oldestDirtySequence = bi->sequenceNumber;
1133 dev->oldestDirtyBlock = blockNo;
1139 * Block retiring for handling a broken block.
1142 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1144 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1146 yaffs_InvalidateCheckpoint(dev);
1148 yaffs_ClearOldestDirtySequence(dev,bi);
1150 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1151 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1152 T(YAFFS_TRACE_ALWAYS, (TSTR(
1153 "yaffs: Failed to mark bad and erase block %d"
1154 TENDSTR), blockInNAND));
1156 yaffs_ExtendedTags tags;
1157 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1159 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1161 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1162 yaffs_InitialiseTags(&tags);
1163 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1164 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1165 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1166 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1167 TCONT("write bad block marker to block %d")
1168 TENDSTR), blockInNAND));
1170 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1174 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1175 bi->gcPrioritise = 0;
1176 bi->needsRetiring = 0;
1178 dev->nRetiredBlocks++;
1182 * Functions for robustisizing TODO
1186 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1188 const yaffs_ExtendedTags *tags)
1191 chunkInNAND=chunkInNAND;
1196 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1197 const yaffs_ExtendedTags *tags)
1200 chunkInNAND=chunkInNAND;
1204 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1206 if (!bi->gcPrioritise) {
1207 bi->gcPrioritise = 1;
1208 dev->hasPendingPrioritisedGCs = 1;
1209 bi->chunkErrorStrikes++;
1211 if (bi->chunkErrorStrikes > 3) {
1212 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1213 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1219 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1222 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1223 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1225 yaffs_HandleChunkError(dev, bi);
1228 /* Was an actual write failure, so mark the block for retirement */
1229 bi->needsRetiring = 1;
1230 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1231 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1234 /* Delete the chunk */
1235 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1236 yaffs_SkipRestOfBlock(dev);
1240 /*---------------- Name handling functions ------------*/
1242 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1247 const YUCHAR *bname = (const YUCHAR *) name;
1249 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1251 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1252 sum += yaffs_toupper(*bname) * i;
1254 sum += (*bname) * i;
1263 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1265 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1266 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1267 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1268 yaffs_strcpy(obj->shortName, name);
1270 obj->shortName[0] = _Y('\0');
1272 obj->sum = yaffs_CalcNameSum(name);
1275 /*-------------------- TNODES -------------------
1277 * List of spare tnodes
1278 * The list is hooked together using the first pointer
1282 /* yaffs_CreateTnodes creates a bunch more tnodes and
1283 * adds them to the tnode free list.
1284 * Don't use this function directly
1286 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1289 /* Calculate the tnode size in bytes for variable width tnode support.
1290 * Must be a multiple of 32-bits */
1291 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1293 if (tnodeSize < sizeof(yaffs_Tnode))
1294 tnodeSize = sizeof(yaffs_Tnode);
1298 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1301 int tnodeSize = yaffs_CalcTnodeSize(dev);
1302 yaffs_Tnode *newTnodes;
1306 yaffs_TnodeList *tnl;
1312 /* make these things */
1314 newTnodes = YMALLOC(nTnodes * tnodeSize);
1315 mem = (__u8 *)newTnodes;
1318 T(YAFFS_TRACE_ERROR,
1319 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1323 /* Hook them into the free list */
1325 for (i = 0; i < nTnodes - 1; i++) {
1326 newTnodes[i].internal[0] = &newTnodes[i + 1];
1327 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1328 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1332 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1333 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1334 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1336 dev->freeTnodes = newTnodes;
1338 /* New hookup for wide tnodes */
1339 for (i = 0; i < nTnodes - 1; i++) {
1340 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1341 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1342 curr->internal[0] = next;
1345 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1346 curr->internal[0] = dev->freeTnodes;
1347 dev->freeTnodes = (yaffs_Tnode *)mem;
1352 dev->nFreeTnodes += nTnodes;
1353 dev->nTnodesCreated += nTnodes;
1355 /* Now add this bunch of tnodes to a list for freeing up.
1356 * NB If we can't add this to the management list it isn't fatal
1357 * but it just means we can't free this bunch of tnodes later.
1360 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1362 T(YAFFS_TRACE_ERROR,
1364 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1367 tnl->tnodes = newTnodes;
1368 tnl->next = dev->allocatedTnodeList;
1369 dev->allocatedTnodeList = tnl;
1372 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1377 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1379 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1381 yaffs_Tnode *tn = NULL;
1383 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1384 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1386 dev->nTnodesCreated++;
1388 /* If there are none left make more */
1389 if (!dev->freeTnodes)
1390 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1392 if (dev->freeTnodes) {
1393 tn = dev->freeTnodes;
1394 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1395 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1396 /* Hoosterman, this thing looks like it isn't in the list */
1397 T(YAFFS_TRACE_ALWAYS,
1398 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1401 dev->freeTnodes = dev->freeTnodes->internal[0];
1405 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1410 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1412 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1413 int tnodeSize = yaffs_CalcTnodeSize(dev);
1416 memset(tn, 0, tnodeSize);
1421 /* FreeTnode frees up a tnode and puts it back on the free list */
1422 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1425 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1427 dev->nTnodesCreated--;
1429 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1430 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1431 /* Hoosterman, this thing looks like it is already in the list */
1432 T(YAFFS_TRACE_ALWAYS,
1433 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1435 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1437 tn->internal[0] = dev->freeTnodes;
1438 dev->freeTnodes = tn;
1442 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1445 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1447 /* Free the list of allocated tnodes */
1448 yaffs_TnodeList *tmp;
1450 while (dev->allocatedTnodeList) {
1451 tmp = dev->allocatedTnodeList->next;
1453 YFREE(dev->allocatedTnodeList->tnodes);
1454 YFREE(dev->allocatedTnodeList);
1455 dev->allocatedTnodeList = tmp;
1459 dev->freeTnodes = NULL;
1460 dev->nFreeTnodes = 0;
1461 dev->nTnodesCreated = 0;
1464 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1466 dev->allocatedTnodeList = NULL;
1467 dev->freeTnodes = NULL;
1468 dev->nFreeTnodes = 0;
1469 dev->nTnodesCreated = 0;
1473 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1476 __u32 *map = (__u32 *)tn;
1482 pos &= YAFFS_TNODES_LEVEL0_MASK;
1483 val >>= dev->chunkGroupBits;
1485 bitInMap = pos * dev->tnodeWidth;
1486 wordInMap = bitInMap / 32;
1487 bitInWord = bitInMap & (32 - 1);
1489 mask = dev->tnodeMask << bitInWord;
1491 map[wordInMap] &= ~mask;
1492 map[wordInMap] |= (mask & (val << bitInWord));
1494 if (dev->tnodeWidth > (32 - bitInWord)) {
1495 bitInWord = (32 - bitInWord);
1497 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1498 map[wordInMap] &= ~mask;
1499 map[wordInMap] |= (mask & (val >> bitInWord));
1503 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1506 __u32 *map = (__u32 *)tn;
1512 pos &= YAFFS_TNODES_LEVEL0_MASK;
1514 bitInMap = pos * dev->tnodeWidth;
1515 wordInMap = bitInMap / 32;
1516 bitInWord = bitInMap & (32 - 1);
1518 val = map[wordInMap] >> bitInWord;
1520 if (dev->tnodeWidth > (32 - bitInWord)) {
1521 bitInWord = (32 - bitInWord);
1523 val |= (map[wordInMap] << bitInWord);
1526 val &= dev->tnodeMask;
1527 val <<= dev->chunkGroupBits;
1532 /* ------------------- End of individual tnode manipulation -----------------*/
1534 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1535 * The look up tree is represented by the top tnode and the number of topLevel
1536 * in the tree. 0 means only the level 0 tnode is in the tree.
1539 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1540 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1541 yaffs_FileStructure *fStruct,
1544 yaffs_Tnode *tn = fStruct->top;
1546 int requiredTallness;
1547 int level = fStruct->topLevel;
1551 /* Check sane level and chunk Id */
1552 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1555 if (chunkId > YAFFS_MAX_CHUNK_ID)
1558 /* First check we're tall enough (ie enough topLevel) */
1560 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1561 requiredTallness = 0;
1563 i >>= YAFFS_TNODES_INTERNAL_BITS;
1567 if (requiredTallness > fStruct->topLevel)
1568 return NULL; /* Not tall enough, so we can't find it */
1570 /* Traverse down to level 0 */
1571 while (level > 0 && tn) {
1572 tn = tn->internal[(chunkId >>
1573 (YAFFS_TNODES_LEVEL0_BITS +
1575 YAFFS_TNODES_INTERNAL_BITS)) &
1576 YAFFS_TNODES_INTERNAL_MASK];
1583 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1584 * This happens in two steps:
1585 * 1. If the tree isn't tall enough, then make it taller.
1586 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1588 * Used when modifying the tree.
1590 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1591 * be plugged into the ttree.
1594 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1595 yaffs_FileStructure *fStruct,
1597 yaffs_Tnode *passedTn)
1599 int requiredTallness;
1607 /* Check sane level and page Id */
1608 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1611 if (chunkId > YAFFS_MAX_CHUNK_ID)
1614 /* First check we're tall enough (ie enough topLevel) */
1616 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1617 requiredTallness = 0;
1619 x >>= YAFFS_TNODES_INTERNAL_BITS;
1624 if (requiredTallness > fStruct->topLevel) {
1625 /* Not tall enough, gotta make the tree taller */
1626 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1628 tn = yaffs_GetTnode(dev);
1631 tn->internal[0] = fStruct->top;
1633 fStruct->topLevel++;
1635 T(YAFFS_TRACE_ERROR,
1636 (TSTR("yaffs: no more tnodes" TENDSTR)));
1642 /* Traverse down to level 0, adding anything we need */
1644 l = fStruct->topLevel;
1648 while (l > 0 && tn) {
1650 (YAFFS_TNODES_LEVEL0_BITS +
1651 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1652 YAFFS_TNODES_INTERNAL_MASK;
1655 if ((l > 1) && !tn->internal[x]) {
1656 /* Add missing non-level-zero tnode */
1657 tn->internal[x] = yaffs_GetTnode(dev);
1658 if(!tn->internal[x])
1660 } else if (l == 1) {
1661 /* Looking from level 1 at level 0 */
1663 /* If we already have one, then release it.*/
1664 if (tn->internal[x])
1665 yaffs_FreeTnode(dev, tn->internal[x]);
1666 tn->internal[x] = passedTn;
1668 } else if (!tn->internal[x]) {
1669 /* Don't have one, none passed in */
1670 tn->internal[x] = yaffs_GetTnode(dev);
1671 if(!tn->internal[x])
1676 tn = tn->internal[x];
1680 /* top is level 0 */
1682 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1683 yaffs_FreeTnode(dev, passedTn);
1690 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1691 yaffs_ExtendedTags *tags, int objectId,
1696 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1697 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1698 theChunk % dev->param.nChunksPerBlock)) {
1700 if(dev->chunkGroupSize == 1)
1703 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1705 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1717 /* Experimental code not being used yet. Might speed up file deletion */
1718 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1719 * chunks and tnodes in the file.
1720 * Returns 1 if the tree was deleted.
1721 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1724 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1725 int chunkOffset, int *limit)
1730 yaffs_ExtendedTags tags;
1732 yaffs_Device *dev = in->myDev;
1738 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1740 if (tn->internal[i]) {
1741 if (limit && (*limit) < 0) {
1745 yaffs_DeleteWorker(in,
1753 YAFFS_TNODES_INTERNAL_BITS)
1758 yaffs_FreeTnode(dev,
1761 tn->internal[i] = NULL;
1765 return (allDone) ? 1 : 0;
1766 } else if (level == 0) {
1769 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1771 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1774 chunkInInode = (chunkOffset <<
1775 YAFFS_TNODES_LEVEL0_BITS) + i;
1778 yaffs_FindChunkInGroup(dev,
1784 if (foundChunk > 0) {
1785 yaffs_DeleteChunk(dev,
1790 *limit = *limit - 1;
1797 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1801 return (i < 0) ? 1 : 0;
1813 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1815 yaffs_BlockInfo *theBlock;
1818 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1820 blockNo = chunk / dev->param.nChunksPerBlock;
1821 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1823 theBlock->softDeletions++;
1825 yaffs_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1829 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1830 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1832 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1835 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1836 __u32 level, int chunkOffset)
1841 yaffs_Device *dev = in->myDev;
1846 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1848 if (tn->internal[i]) {
1850 yaffs_SoftDeleteWorker(in,
1856 YAFFS_TNODES_INTERNAL_BITS)
1859 yaffs_FreeTnode(dev,
1862 tn->internal[i] = NULL;
1864 /* Hoosterman... how could this happen? */
1868 return (allDone) ? 1 : 0;
1869 } else if (level == 0) {
1871 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1872 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1874 /* Note this does not find the real chunk, only the chunk group.
1875 * We make an assumption that a chunk group is not larger than
1878 yaffs_SoftDeleteChunk(dev, theChunk);
1879 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1893 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1896 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1897 if (obj->nDataChunks <= 0) {
1898 /* Empty file with no duplicate object headers, just delete it immediately */
1899 yaffs_FreeTnode(obj->myDev,
1900 obj->variant.fileVariant.top);
1901 obj->variant.fileVariant.top = NULL;
1902 T(YAFFS_TRACE_TRACING,
1903 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1905 yaffs_DoGenericObjectDeletion(obj);
1907 yaffs_SoftDeleteWorker(obj,
1908 obj->variant.fileVariant.top,
1909 obj->variant.fileVariant.
1911 obj->softDeleted = 1;
1916 /* Pruning removes any part of the file structure tree that is beyond the
1917 * bounds of the file (ie that does not point to chunks).
1919 * A file should only get pruned when its size is reduced.
1921 * Before pruning, the chunks must be pulled from the tree and the
1922 * level 0 tnode entries must be zeroed out.
1923 * Could also use this for file deletion, but that's probably better handled
1924 * by a special case.
1926 * This function is recursive. For levels > 0 the function is called again on
1927 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1928 * If there is no data in a subtree then it is pruned.
1931 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1932 __u32 level, int del0)
1941 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1942 if (tn->internal[i]) {
1944 yaffs_PruneWorker(dev, tn->internal[i],
1946 (i == 0) ? del0 : 1);
1949 if (tn->internal[i])
1953 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1954 __u32 *map = (__u32 *)tn;
1956 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1962 if (hasData == 0 && del0) {
1963 /* Free and return NULL */
1965 yaffs_FreeTnode(dev, tn);
1975 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1976 yaffs_FileStructure *fStruct)
1983 if (fStruct->topLevel > 0) {
1985 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1987 /* Now we have a tree with all the non-zero branches NULL but the height
1988 * is the same as it was.
1989 * Let's see if we can trim internal tnodes to shorten the tree.
1990 * We can do this if only the 0th element in the tnode is in use
1991 * (ie all the non-zero are NULL)
1994 while (fStruct->topLevel && !done) {
1998 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1999 if (tn->internal[i])
2004 fStruct->top = tn->internal[0];
2005 fStruct->topLevel--;
2006 yaffs_FreeTnode(dev, tn);
2016 /*-------------------- End of File Structure functions.-------------------*/
2018 /* yaffs_CreateFreeObjects creates a bunch more objects and
2019 * adds them to the object free list.
2021 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2024 yaffs_Object *newObjects;
2025 yaffs_ObjectList *list;
2030 /* make these things */
2031 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2032 list = YMALLOC(sizeof(yaffs_ObjectList));
2034 if (!newObjects || !list) {
2043 T(YAFFS_TRACE_ALLOCATE,
2044 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2048 /* Hook them into the free list */
2049 for (i = 0; i < nObjects - 1; i++) {
2050 newObjects[i].siblings.next =
2051 (struct ylist_head *)(&newObjects[i + 1]);
2054 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2055 dev->freeObjects = newObjects;
2056 dev->nFreeObjects += nObjects;
2057 dev->nObjectsCreated += nObjects;
2059 /* Now add this bunch of Objects to a list for freeing up. */
2061 list->objects = newObjects;
2062 list->next = dev->allocatedObjectList;
2063 dev->allocatedObjectList = list;
2069 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2070 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2072 yaffs_Object *tn = NULL;
2074 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2075 tn = YMALLOC(sizeof(yaffs_Object));
2077 dev->nObjectsCreated++;
2079 /* If there are none left make more */
2080 if (!dev->freeObjects)
2081 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2083 if (dev->freeObjects) {
2084 tn = dev->freeObjects;
2086 (yaffs_Object *) (dev->freeObjects->siblings.next);
2087 dev->nFreeObjects--;
2091 /* Now sweeten it up... */
2093 memset(tn, 0, sizeof(yaffs_Object));
2094 tn->beingCreated = 1;
2098 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2099 YINIT_LIST_HEAD(&(tn->hardLinks));
2100 YINIT_LIST_HEAD(&(tn->hashLink));
2101 YINIT_LIST_HEAD(&tn->siblings);
2104 /* Now make the directory sane */
2106 tn->parent = dev->rootDir;
2107 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2110 /* Add it to the lost and found directory.
2111 * NB Can't put root or lostNFound in lostNFound so
2112 * check if lostNFound exists first
2114 if (dev->lostNFoundDir)
2115 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2117 tn->beingCreated = 0;
2120 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2125 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2130 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2132 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2133 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2134 obj->unlinkAllowed = 0; /* ... or unlink it */
2137 obj->yst_mode = mode;
2139 obj->hdrChunk = 0; /* Not a valid chunk. */
2146 static void yaffs_UnhashObject(yaffs_Object *tn)
2149 yaffs_Device *dev = tn->myDev;
2151 /* If it is still linked into the bucket list, free from the list */
2152 if (!ylist_empty(&tn->hashLink)) {
2153 ylist_del_init(&tn->hashLink);
2154 bucket = yaffs_HashFunction(tn->objectId);
2155 dev->objectBucket[bucket].count--;
2159 /* FreeObject frees up a Object and puts it back on the free list */
2160 static void yaffs_FreeObject(yaffs_Object *tn)
2162 yaffs_Device *dev = tn->myDev;
2164 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2170 if (!ylist_empty(&tn->siblings))
2175 /* We're still hooked up to a cached inode.
2176 * Don't delete now, but mark for later deletion
2178 tn->deferedFree = 1;
2182 yaffs_UnhashObject(tn);
2184 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2186 dev->nObjectsCreated--;
2189 /* Link into the free list. */
2190 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2191 dev->freeObjects = tn;
2192 dev->nFreeObjects++;
2194 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2198 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2200 if (obj->deferedFree)
2201 yaffs_FreeObject(obj);
2205 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2207 /* Free the list of allocated Objects */
2209 yaffs_ObjectList *tmp;
2211 while (dev->allocatedObjectList) {
2212 tmp = dev->allocatedObjectList->next;
2213 YFREE(dev->allocatedObjectList->objects);
2214 YFREE(dev->allocatedObjectList);
2216 dev->allocatedObjectList = tmp;
2219 dev->freeObjects = NULL;
2220 dev->nFreeObjects = 0;
2221 dev->nObjectsCreated = 0;
2224 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2228 dev->allocatedObjectList = NULL;
2229 dev->freeObjects = NULL;
2230 dev->nFreeObjects = 0;
2232 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2233 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2234 dev->objectBucket[i].count = 0;
2238 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2242 int lowest = 999999;
2245 /* Search for the shortest list or one that
2249 for (i = 0; i < 10 && lowest > 4; i++) {
2250 dev->bucketFinder++;
2251 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2252 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2253 lowest = dev->objectBucket[dev->bucketFinder].count;
2254 l = dev->bucketFinder;
2262 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2264 int bucket = yaffs_FindNiceObjectBucket(dev);
2266 /* Now find an object value that has not already been taken
2267 * by scanning the list.
2271 struct ylist_head *i;
2273 __u32 n = (__u32) bucket;
2275 /* yaffs_CheckObjectHashSanity(); */
2279 n += YAFFS_NOBJECT_BUCKETS;
2280 if (1 || dev->objectBucket[bucket].count > 0) {
2281 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2282 /* If there is already one in the list */
2283 if (i && ylist_entry(i, yaffs_Object,
2284 hashLink)->objectId == n) {
2294 static void yaffs_HashObject(yaffs_Object *in)
2296 int bucket = yaffs_HashFunction(in->objectId);
2297 yaffs_Device *dev = in->myDev;
2299 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2300 dev->objectBucket[bucket].count++;
2303 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2305 int bucket = yaffs_HashFunction(number);
2306 struct ylist_head *i;
2309 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2310 /* Look if it is in the list */
2312 in = ylist_entry(i, yaffs_Object, hashLink);
2313 if (in->objectId == number) {
2315 /* Don't tell the VFS about this one if it is defered free */
2316 if (in->deferedFree)
2327 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2328 yaffs_ObjectType type)
2330 yaffs_Object *theObject=NULL;
2331 yaffs_Tnode *tn = NULL;
2334 number = yaffs_CreateNewObjectNumber(dev);
2336 if (type == YAFFS_OBJECT_TYPE_FILE) {
2337 tn = yaffs_GetTnode(dev);
2342 theObject = yaffs_AllocateEmptyObject(dev);
2345 yaffs_FreeTnode(dev,tn);
2351 theObject->fake = 0;
2352 theObject->renameAllowed = 1;
2353 theObject->unlinkAllowed = 1;
2354 theObject->objectId = number;
2355 yaffs_HashObject(theObject);
2356 theObject->variantType = type;
2357 #ifdef CONFIG_YAFFS_WINCE
2358 yfsd_WinFileTimeNow(theObject->win_atime);
2359 theObject->win_ctime[0] = theObject->win_mtime[0] =
2360 theObject->win_atime[0];
2361 theObject->win_ctime[1] = theObject->win_mtime[1] =
2362 theObject->win_atime[1];
2366 theObject->yst_atime = theObject->yst_mtime =
2367 theObject->yst_ctime = Y_CURRENT_TIME;
2370 case YAFFS_OBJECT_TYPE_FILE:
2371 theObject->variant.fileVariant.fileSize = 0;
2372 theObject->variant.fileVariant.scannedFileSize = 0;
2373 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2374 theObject->variant.fileVariant.topLevel = 0;
2375 theObject->variant.fileVariant.top = tn;
2377 case YAFFS_OBJECT_TYPE_DIRECTORY:
2378 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2380 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2383 case YAFFS_OBJECT_TYPE_SYMLINK:
2384 case YAFFS_OBJECT_TYPE_HARDLINK:
2385 case YAFFS_OBJECT_TYPE_SPECIAL:
2386 /* No action required */
2388 case YAFFS_OBJECT_TYPE_UNKNOWN:
2389 /* todo this should not happen */
2397 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2399 yaffs_ObjectType type)
2401 yaffs_Object *theObject = NULL;
2404 theObject = yaffs_FindObjectByNumber(dev, number);
2407 theObject = yaffs_CreateNewObject(dev, number, type);
2414 static YCHAR *yaffs_CloneString(const YCHAR *str)
2416 YCHAR *newStr = NULL;
2422 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2423 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2425 yaffs_strncpy(newStr, str,len);
2433 * Mknod (create) a new object.
2434 * equivalentObject only has meaning for a hard link;
2435 * aliasString only has meaning for a symlink.
2436 * rdev only has meaning for devices (a subset of special objects)
2439 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2440 yaffs_Object *parent,
2445 yaffs_Object *equivalentObject,
2446 const YCHAR *aliasString, __u32 rdev)
2451 yaffs_Device *dev = parent->myDev;
2453 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2454 if (yaffs_FindObjectByName(parent, name))
2457 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2458 str = yaffs_CloneString(aliasString);
2463 in = yaffs_CreateNewObject(dev, -1, type);
2478 in->variantType = type;
2480 in->yst_mode = mode;
2482 #ifdef CONFIG_YAFFS_WINCE
2483 yfsd_WinFileTimeNow(in->win_atime);
2484 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2485 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2488 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2490 in->yst_rdev = rdev;
2494 in->nDataChunks = 0;
2496 yaffs_SetObjectName(in, name);
2499 yaffs_AddObjectToDirectory(parent, in);
2501 in->myDev = parent->myDev;
2504 case YAFFS_OBJECT_TYPE_SYMLINK:
2505 in->variant.symLinkVariant.alias = str;
2507 case YAFFS_OBJECT_TYPE_HARDLINK:
2508 in->variant.hardLinkVariant.equivalentObject =
2510 in->variant.hardLinkVariant.equivalentObjectId =
2511 equivalentObject->objectId;
2512 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2514 case YAFFS_OBJECT_TYPE_FILE:
2515 case YAFFS_OBJECT_TYPE_DIRECTORY:
2516 case YAFFS_OBJECT_TYPE_SPECIAL:
2517 case YAFFS_OBJECT_TYPE_UNKNOWN:
2522 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2523 /* Could not create the object header, fail the creation */
2524 yaffs_DeleteObject(in);
2528 yaffs_UpdateParent(parent);
2534 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2535 __u32 mode, __u32 uid, __u32 gid)
2537 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2538 uid, gid, NULL, NULL, 0);
2541 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2542 __u32 mode, __u32 uid, __u32 gid)
2544 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2545 mode, uid, gid, NULL, NULL, 0);
2548 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2549 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2551 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2552 uid, gid, NULL, NULL, rdev);
2555 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2556 __u32 mode, __u32 uid, __u32 gid,
2559 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2560 uid, gid, NULL, alias, 0);
2563 /* yaffs_Link returns the object id of the equivalent object.*/
2564 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2565 yaffs_Object *equivalentObject)
2567 /* Get the real object in case we were fed a hard link as an equivalent object */
2568 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2570 if (yaffs_MknodObject
2571 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2572 equivalentObject, NULL, 0)) {
2573 return equivalentObject;
2580 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2581 const YCHAR *newName, int force, int shadows)
2586 yaffs_Object *existingTarget;
2589 newDir = obj->parent; /* use the old directory */
2591 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2592 T(YAFFS_TRACE_ALWAYS,
2594 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2599 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2600 if (obj->myDev->param.isYaffs2)
2601 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2603 unlinkOp = (newDir == obj->myDev->unlinkedDir
2604 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2606 deleteOp = (newDir == obj->myDev->deletedDir);
2608 existingTarget = yaffs_FindObjectByName(newDir, newName);
2610 /* If the object is a file going into the unlinked directory,
2611 * then it is OK to just stuff it in since duplicate names are allowed.
2612 * else only proceed if the new name does not exist and if we're putting
2613 * it into a directory.
2620 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2621 yaffs_SetObjectName(obj, newName);
2624 yaffs_AddObjectToDirectory(newDir, obj);
2629 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2630 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2637 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2638 yaffs_Object *newDir, const YCHAR *newName)
2640 yaffs_Object *obj = NULL;
2641 yaffs_Object *existingTarget = NULL;
2647 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2649 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2652 dev = oldDir->myDev;
2654 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2655 /* Special case for case insemsitive systems (eg. WinCE).
2656 * While look-up is case insensitive, the name isn't.
2657 * Therefore we might want to change x.txt to X.txt
2659 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2663 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2667 obj = yaffs_FindObjectByName(oldDir, oldName);
2669 if (obj && obj->renameAllowed) {
2671 /* Now do the handling for an existing target, if there is one */
2673 existingTarget = yaffs_FindObjectByName(newDir, newName);
2674 if (existingTarget &&
2675 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2676 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2677 /* There is a target that is a non-empty directory, so we fail */
2678 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2679 } else if (existingTarget && existingTarget != obj) {
2680 /* Nuke the target first, using shadowing,
2681 * but only if it isn't the same object.
2683 * Note we must disable gc otherwise it can mess up the shadowing.
2687 yaffs_ChangeObjectName(obj, newDir, newName, force,
2688 existingTarget->objectId);
2689 existingTarget->isShadowed = 1;
2690 yaffs_UnlinkObject(existingTarget);
2694 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2696 yaffs_UpdateParent(oldDir);
2697 if(newDir != oldDir)
2698 yaffs_UpdateParent(newDir);
2705 /*------------------------- Block Management and Page Allocation ----------------*/
2707 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2709 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2711 dev->blockInfo = NULL;
2712 dev->chunkBits = NULL;
2714 dev->allocationBlock = -1; /* force it to get a new one */
2716 /* If the first allocation strategy fails, thry the alternate one */
2717 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2718 if (!dev->blockInfo) {
2719 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2720 dev->blockInfoAlt = 1;
2722 dev->blockInfoAlt = 0;
2724 if (dev->blockInfo) {
2725 /* Set up dynamic blockinfo stuff. */
2726 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2727 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2728 if (!dev->chunkBits) {
2729 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2730 dev->chunkBitsAlt = 1;
2732 dev->chunkBitsAlt = 0;
2735 if (dev->blockInfo && dev->chunkBits) {
2736 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2737 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2744 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2746 if (dev->blockInfoAlt && dev->blockInfo)
2747 YFREE_ALT(dev->blockInfo);
2748 else if (dev->blockInfo)
2749 YFREE(dev->blockInfo);
2751 dev->blockInfoAlt = 0;
2753 dev->blockInfo = NULL;
2755 if (dev->chunkBitsAlt && dev->chunkBits)
2756 YFREE_ALT(dev->chunkBits);
2757 else if (dev->chunkBits)
2758 YFREE(dev->chunkBits);
2759 dev->chunkBitsAlt = 0;
2760 dev->chunkBits = NULL;
2763 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2764 yaffs_BlockInfo *bi)
2767 if (!dev->param.isYaffs2)
2768 return 1; /* disqualification only applies to yaffs2. */
2770 if (!bi->hasShrinkHeader)
2771 return 1; /* can gc */
2773 yaffs_FindOldestDirtySequence(dev);
2775 /* Can't do gc of this block if there are any blocks older than this one that have
2778 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2782 * yaffs_FindRefreshBlock()
2783 * periodically finds the oldest full block by sequence number for refreshing.
2786 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2791 __u32 oldestSequence = 0;
2793 yaffs_BlockInfo *bi;
2796 * If refresh period < 10 then refreshing is disabled.
2798 if(dev->param.refreshPeriod < 10 ||
2799 !dev->param.isYaffs2)
2803 * Fix broken values.
2805 if(dev->refreshSkip > dev->param.refreshPeriod)
2806 dev->refreshSkip = dev->param.refreshPeriod;
2808 if(dev->refreshSkip > 0)
2812 * Refresh skip is now zero.
2813 * We'll do a refresh this time around....
2814 * Update the refresh skip and find the oldest block.
2816 dev->refreshSkip = dev->param.refreshPeriod;
2817 dev->refreshCount++;
2818 bi = dev->blockInfo;
2819 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2821 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2824 bi->sequenceNumber < oldestSequence){
2826 oldestSequence = bi->sequenceNumber;
2834 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2835 dev->refreshCount, oldest, oldestSequence));
2842 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2844 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2848 /* If the block is still healthy erase it and mark as clean.
2849 * If the block has had a data failure, then retire it.
2852 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2853 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2854 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2856 yaffs_ClearOldestDirtySequence(dev,bi);
2858 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2860 /* If this is the block being garbage collected then stop gc'ing this block */
2861 if(blockNo == dev->gcBlock)
2864 /* If this block is currently the best candidate for gc then drop as a candidate */
2865 if(blockNo == dev->gcDirtiest){
2866 dev->gcDirtiest = 0;
2867 dev->gcPagesInUse = 0;
2870 if (!bi->needsRetiring) {
2871 yaffs_InvalidateCheckpoint(dev);
2872 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2874 dev->nErasureFailures++;
2875 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2876 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2881 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2883 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2884 if (!yaffs_CheckChunkErased
2885 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2886 T(YAFFS_TRACE_ERROR,
2888 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2889 TENDSTR), blockNo, i));
2895 /* Clean it up... */
2896 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2897 bi->sequenceNumber = 0;
2898 dev->nErasedBlocks++;
2900 bi->softDeletions = 0;
2901 bi->hasShrinkHeader = 0;
2902 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2903 bi->gcPrioritise = 0;
2904 yaffs_ClearChunkBits(dev, blockNo);
2906 T(YAFFS_TRACE_ERASE,
2907 (TSTR("Erased block %d" TENDSTR), blockNo));
2909 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2911 yaffs_RetireBlock(dev, blockNo);
2912 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2913 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2917 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2921 yaffs_BlockInfo *bi;
2923 if (dev->nErasedBlocks < 1) {
2924 /* Hoosterman we've got a problem.
2925 * Can't get space to gc
2927 T(YAFFS_TRACE_ERROR,
2928 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2933 /* Find an empty block. */
2935 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2936 dev->allocationBlockFinder++;
2937 if (dev->allocationBlockFinder < dev->internalStartBlock
2938 || dev->allocationBlockFinder > dev->internalEndBlock) {
2939 dev->allocationBlockFinder = dev->internalStartBlock;
2942 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2944 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2945 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2946 dev->sequenceNumber++;
2947 bi->sequenceNumber = dev->sequenceNumber;
2948 dev->nErasedBlocks--;
2949 T(YAFFS_TRACE_ALLOCATE,
2950 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2951 dev->allocationBlockFinder, dev->sequenceNumber,
2952 dev->nErasedBlocks));
2953 return dev->allocationBlockFinder;
2957 T(YAFFS_TRACE_ALWAYS,
2959 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2960 TENDSTR), dev->nErasedBlocks));
2967 static int yaffs_CheckpointRequired(yaffs_Device *dev)
2969 int nblocks = dev->internalEndBlock - dev->internalStartBlock + 1 ;
2970 return dev->param.isYaffs2 &&
2971 !dev->param.skipCheckpointWrite &&
2972 (nblocks >= YAFFS_CHECKPOINT_MIN_BLOCKS);
2974 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2976 if (!dev->nCheckpointBlocksRequired &&
2977 yaffs_CheckpointRequired(dev)){
2978 /* Not a valid value so recalculate */
2981 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2982 int tnodeSize = yaffs_CalcTnodeSize(dev);
2984 nBytes += sizeof(yaffs_CheckpointValidity);
2985 nBytes += sizeof(yaffs_CheckpointDevice);
2986 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2987 nBytes += devBlocks * dev->chunkBitmapStride;
2988 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2989 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2990 nBytes += sizeof(yaffs_CheckpointValidity);
2991 nBytes += sizeof(__u32); /* checksum*/
2993 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2995 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
2997 dev->nCheckpointBlocksRequired = nBlocks;
3000 return dev->nCheckpointBlocksRequired;
3004 * Check if there's space to allocate...
3005 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3007 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
3010 int reservedBlocks = dev->param.nReservedBlocks;
3011 int checkpointBlocks;
3013 if (dev->param.isYaffs2) {
3014 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
3015 dev->blocksInCheckpoint;
3016 if (checkpointBlocks < 0)
3017 checkpointBlocks = 0;
3019 checkpointBlocks = 0;
3022 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3024 return (dev->nFreeChunks > (reservedChunks + nChunks));
3027 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3028 yaffs_BlockInfo **blockUsedPtr)
3031 yaffs_BlockInfo *bi;
3033 if (dev->allocationBlock < 0) {
3034 /* Get next block to allocate off */
3035 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3036 dev->allocationPage = 0;
3039 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
3040 /* Not enough space to allocate unless we're allowed to use the reserve. */
3044 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3045 && dev->allocationPage == 0) {
3046 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3049 /* Next page please.... */
3050 if (dev->allocationBlock >= 0) {
3051 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3053 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3054 dev->allocationPage;
3056 yaffs_SetChunkBit(dev, dev->allocationBlock,
3057 dev->allocationPage);
3059 dev->allocationPage++;
3063 /* If the block is full set the state to full */
3064 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3065 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3066 dev->allocationBlock = -1;
3075 T(YAFFS_TRACE_ERROR,
3076 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3081 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3085 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3087 if (dev->allocationBlock > 0)
3088 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3095 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3096 * if we don't want to write to it.
3098 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3100 if(dev->allocationBlock > 0){
3101 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3102 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3103 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3104 dev->allocationBlock = -1;
3110 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3116 int retVal = YAFFS_OK;
3119 int isCheckpointBlock;
3123 int chunksBefore = yaffs_GetErasedChunks(dev);
3126 yaffs_ExtendedTags tags;
3128 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3130 yaffs_Object *object;
3132 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3135 T(YAFFS_TRACE_TRACING,
3136 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3139 bi->hasShrinkHeader,
3142 /*yaffs_VerifyFreeChunks(dev); */
3144 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3145 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3147 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3151 if (isCheckpointBlock ||
3152 !yaffs_StillSomeChunkBits(dev, block)) {
3153 T(YAFFS_TRACE_TRACING,
3155 ("Collecting block %d that has no chunks in use" TENDSTR),
3157 yaffs_BlockBecameDirty(dev, block);
3160 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3162 yaffs_VerifyBlock(dev, bi, block);
3164 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
3165 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3167 for (/* init already done */;
3168 retVal == YAFFS_OK &&
3169 dev->gcChunk < dev->param.nChunksPerBlock &&
3170 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3172 dev->gcChunk++, oldChunk++) {
3173 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3175 /* This page is in use and might need to be copied off */
3181 yaffs_InitialiseTags(&tags);
3183 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3187 yaffs_FindObjectByNumber(dev,
3190 T(YAFFS_TRACE_GC_DETAIL,
3192 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3193 dev->gcChunk, tags.objectId, tags.chunkId,
3196 if (object && !yaffs_SkipVerification(dev)) {
3197 if (tags.chunkId == 0)
3198 matchingChunk = object->hdrChunk;
3199 else if (object->softDeleted)
3200 matchingChunk = oldChunk; /* Defeat the test */
3202 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3204 if (oldChunk != matchingChunk)
3205 T(YAFFS_TRACE_ERROR,
3206 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3207 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3212 T(YAFFS_TRACE_ERROR,
3214 ("page %d in gc has no object: %d %d %d "
3216 tags.objectId, tags.chunkId, tags.byteCount));
3221 object->softDeleted &&
3222 tags.chunkId != 0) {
3223 /* Data chunk in a soft deleted file, throw it away
3224 * It's a soft deleted data chunk,
3225 * No need to copy this, just forget about it and
3226 * fix up the object.
3229 /* Free chunks already includes softdeleted chunks.
3230 * How ever this chunk is going to soon be really deleted
3231 * which will increment free chunks.
3232 * We have to decrement free chunks so this works out properly.
3236 object->nDataChunks--;
3238 if (object->nDataChunks <= 0) {
3239 /* remeber to clean up the object */
3240 dev->gcCleanupList[cleanups] =
3246 /* Todo object && object->deleted && object->nDataChunks == 0 */
3247 /* Deleted object header with no data chunks.
3248 * Can be discarded and the file deleted.
3250 object->hdrChunk = 0;
3251 yaffs_FreeTnode(object->myDev,
3254 object->variant.fileVariant.top = NULL;
3255 yaffs_DoGenericObjectDeletion(object);
3257 } else if (object) {
3258 /* It's either a data chunk in a live file or
3259 * an ObjectHeader, so we're interested in it.
3260 * NB Need to keep the ObjectHeaders of deleted files
3261 * until the whole file has been deleted off
3263 tags.serialNumber++;
3267 if (tags.chunkId == 0) {
3268 /* It is an object Id,
3269 * We need to nuke the shrinkheader flags first
3270 * Also need to clean up shadowing.
3271 * We no longer want the shrinkHeader flag since its work is done
3272 * and if it is left in place it will mess up scanning.
3275 yaffs_ObjectHeader *oh;
3276 oh = (yaffs_ObjectHeader *)buffer;
3279 tags.extraIsShrinkHeader = 0;
3281 oh->shadowsObject = 0;
3282 oh->inbandShadowsObject = 0;
3283 tags.extraShadows = 0;
3285 /* Update file size */
3286 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3287 oh->fileSize = object->variant.fileVariant.fileSize;
3288 tags.extraFileLength = oh->fileSize;
3291 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3293 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3296 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3299 retVal = YAFFS_FAIL;
3302 /* Ok, now fix up the Tnodes etc. */
3304 if (tags.chunkId == 0) {
3306 object->hdrChunk = newChunk;
3307 object->serial = tags.serialNumber;
3309 /* It's a data chunk */
3311 ok = yaffs_PutChunkIntoFile
3319 if (retVal == YAFFS_OK)
3320 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3325 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3328 /* Do any required cleanups */
3329 for (i = 0; i < cleanups; i++) {
3330 /* Time to delete the file too */
3332 yaffs_FindObjectByNumber(dev,
3333 dev->gcCleanupList[i]);
3335 yaffs_FreeTnode(dev,
3336 object->variant.fileVariant.
3338 object->variant.fileVariant.top = NULL;
3341 ("yaffs: About to finally delete object %d"
3342 TENDSTR), object->objectId));
3343 yaffs_DoGenericObjectDeletion(object);
3344 object->myDev->nDeletedFiles--;
3351 yaffs_VerifyCollectedBlock(dev, bi, block);
3355 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3357 * The gc did not complete. Set block state back to FULL
3358 * because checkpointing does not restore gc.
3360 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3362 /* The gc completed. */
3363 chunksAfter = yaffs_GetErasedChunks(dev);
3364 if (chunksBefore >= chunksAfter) {
3367 ("gc did not increase free chunks before %d after %d"
3368 TENDSTR), chunksBefore, chunksAfter));
3380 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
3381 * for garbage collection.
3384 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
3390 unsigned selected = 0;
3391 int prioritised = 0;
3392 int prioritisedExists = 0;
3393 yaffs_BlockInfo *bi;
3396 /* First let's see if we need to grab a prioritised block */
3397 if (dev->hasPendingPrioritisedGCs && !aggressive) {
3398 dev->gcDirtiest = 0;
3399 bi = dev->blockInfo;
3400 for (i = dev->internalStartBlock;
3401 i <= dev->internalEndBlock && !selected;
3404 if (bi->gcPrioritise) {
3405 prioritisedExists = 1;
3406 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3407 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3416 * If there is a prioritised block and none was selected then
3417 * this happened because there is at least one old dirty block gumming
3418 * up the works. Let's gc the oldest dirty block.
3421 if(prioritisedExists &&
3423 dev->oldestDirtyBlock > 0)
3424 selected = dev->oldestDirtyBlock;
3426 if (!prioritisedExists) /* None found, so we can clear this */
3427 dev->hasPendingPrioritisedGCs = 0;
3430 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
3432 * else (we're doing a leasurely gc), then we only bother to do this if the
3433 * block has only a few pages in use.
3438 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3440 threshold = dev->param.nChunksPerBlock;
3441 iterations = nBlocks;
3443 int maxThreshold = dev->param.nChunksPerBlock/2;
3444 threshold = background ?
3445 (dev->gcNotDone + 2) * 2 : 0;
3446 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
3447 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
3448 if(threshold > maxThreshold)
3449 threshold = maxThreshold;
3451 iterations = nBlocks / 16 + 1;
3452 if (iterations > 100)
3458 (dev->gcDirtiest < 1 ||
3459 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
3461 dev->gcBlockFinder++;
3462 if (dev->gcBlockFinder < dev->internalStartBlock ||
3463 dev->gcBlockFinder > dev->internalEndBlock)
3464 dev->gcBlockFinder = dev->internalStartBlock;
3466 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
3468 pagesUsed = bi->pagesInUse - bi->softDeletions;
3470 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3471 pagesUsed < dev->param.nChunksPerBlock &&
3472 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
3473 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3474 dev->gcDirtiest = dev->gcBlockFinder;
3475 dev->gcPagesInUse = pagesUsed;
3479 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
3480 selected = dev->gcDirtiest;
3484 * If nothing has been selected for a while, try selecting the oldest dirty
3485 * because that's gumming up the works.
3488 if(!selected && dev->param.isYaffs2 &&
3489 dev->gcNotDone >= ( background ? 10 : 20)){
3490 yaffs_FindOldestDirtySequence(dev);
3491 if(dev->oldestDirtyBlock > 0) {
3492 selected = dev->oldestDirtyBlock;
3493 dev->gcDirtiest = selected;
3494 dev->oldestDirtyGCs++;
3495 bi = yaffs_GetBlockInfo(dev, selected);
3496 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
3503 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
3505 dev->param.nChunksPerBlock - dev->gcPagesInUse,
3509 dev->backgroundGCs++;
3510 dev->gcDirtiest = 0;
3511 dev->gcPagesInUse = 0;
3513 if(dev->refreshSkip > 0)
3518 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
3519 dev->gcBlockFinder, dev->gcNotDone,
3521 dev->gcDirtiest, dev->gcPagesInUse,
3522 dev->oldestDirtyBlock,
3523 background ? " bg" : ""));
3529 /* New garbage collector
3530 * If we're very low on erased blocks then we do aggressive garbage collection
3531 * otherwise we do "leasurely" garbage collection.
3532 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3533 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3535 * The idea is to help clear out space in a more spread-out manner.
3536 * Dunno if it really does anything useful.
3538 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
3541 int gcOk = YAFFS_OK;
3547 int checkpointBlockAdjust;
3549 if(dev->param.gcControl &&
3550 (dev->param.gcControl(dev) & 1) == 0)
3553 if (dev->gcDisable) {
3554 /* Bail out so we don't get recursive gc */
3558 /* This loop should pass the first time.
3559 * We'll only see looping here if the collection does not increase space.
3565 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3566 if (checkpointBlockAdjust < 0)
3567 checkpointBlockAdjust = 0;
3569 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
3570 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3572 /* If we need a block soon then do aggressive gc.*/
3573 if (dev->nErasedBlocks < minErased)
3576 if(dev->gcSkip > 20)
3578 if(erasedChunks < dev->nFreeChunks/2 ||
3590 /* If we don't already have a block being gc'd then see if we should start another */
3592 if (dev->gcBlock < 1 && !aggressive) {
3593 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3596 if (dev->gcBlock < 1) {
3597 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
3601 if (dev->gcBlock > 0) {
3608 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3609 dev->nErasedBlocks, aggressive));
3611 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
3614 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
3617 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3618 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
3620 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3621 (dev->gcBlock > 0) &&
3624 return aggressive ? gcOk : YAFFS_OK;
3628 * yaffs_BackgroundGarbageCollect()
3629 * Garbage collects. Intended to be called from a background thread.
3630 * Returns non-zero if at least half the free chunks are erased.
3632 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
3634 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3636 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
3638 yaffs_CheckGarbageCollection(dev, 1);
3639 return erasedChunks > dev->nFreeChunks/2;
3642 /*------------------------- TAGS --------------------------------*/
3644 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3647 return (tags->chunkId == chunkInObject &&
3648 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3653 /*-------------------- Data file manipulation -----------------*/
3655 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3656 yaffs_ExtendedTags *tags)
3658 /*Get the Tnode, then get the level 0 offset chunk offset */
3661 yaffs_ExtendedTags localTags;
3664 yaffs_Device *dev = in->myDev;
3667 /* Passed a NULL, so use our own tags space */
3671 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3674 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3677 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3683 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3684 yaffs_ExtendedTags *tags)
3686 /* Get the Tnode, then get the level 0 offset chunk offset */
3689 yaffs_ExtendedTags localTags;
3691 yaffs_Device *dev = in->myDev;
3695 /* Passed a NULL, so use our own tags space */
3699 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3703 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3706 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3709 /* Delete the entry in the filestructure (if found) */
3711 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3717 #ifdef YAFFS_PARANOID
3719 static int yaffs_CheckFileSanity(yaffs_Object *in)
3727 yaffs_Tags localTags;
3728 yaffs_Tags *tags = &localTags;
3732 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3735 objId = in->objectId;
3736 fSize = in->variant.fileVariant.fileSize;
3738 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3740 for (chunk = 1; chunk <= nChunks; chunk++) {
3741 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3746 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3748 if (yaffs_CheckChunkBits
3749 (dev, theChunk / dev->param.nChunksPerBlock,
3750 theChunk % dev->param.nChunksPerBlock)) {
3752 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3756 (tags, in->objectId, chunk, chunkDeleted)) {
3766 /* T(("No level 0 found for %d\n", chunk)); */
3770 return failed ? YAFFS_FAIL : YAFFS_OK;
3775 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3776 int chunkInNAND, int inScan)
3778 /* NB inScan is zero unless scanning.
3779 * For forward scanning, inScan is > 0;
3780 * for backward scanning inScan is < 0
3782 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3786 yaffs_Device *dev = in->myDev;
3788 yaffs_ExtendedTags existingTags;
3789 yaffs_ExtendedTags newTags;
3790 unsigned existingSerial, newSerial;
3792 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3793 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3794 * If it is not during Scanning then something went wrong!
3797 T(YAFFS_TRACE_ERROR,
3799 ("yaffs tragedy:attempt to put data chunk into a non-file"
3804 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3808 tn = yaffs_AddOrFindLevel0Tnode(dev,
3809 &in->variant.fileVariant,
3816 /* Dummy insert, bail now */
3819 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3822 /* If we're scanning then we need to test for duplicates
3823 * NB This does not need to be efficient since it should only ever
3824 * happen when the power fails during a write, then only one
3825 * chunk should ever be affected.
3827 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3828 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3831 if (existingChunk > 0) {
3832 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3833 * thus we have to do a FindChunkInFile to get the real chunk id.
3835 * We have a duplicate now we need to decide which one to use:
3837 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3838 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3839 * YAFFS1: Get both sets of tags and compare serial numbers.
3843 /* Only do this for forward scanning */
3844 yaffs_ReadChunkWithTagsFromNAND(dev,
3848 /* Do a proper find */
3850 yaffs_FindChunkInFile(in, chunkInInode,
3854 if (existingChunk <= 0) {
3855 /*Hoosterman - how did this happen? */
3857 T(YAFFS_TRACE_ERROR,
3859 ("yaffs tragedy: existing chunk < 0 in scan"
3864 /* NB The deleted flags should be false, otherwise the chunks will
3865 * not be loaded during a scan
3869 newSerial = newTags.serialNumber;
3870 existingSerial = existingTags.serialNumber;
3874 (in->myDev->param.isYaffs2 ||
3875 existingChunk <= 0 ||
3876 ((existingSerial + 1) & 3) == newSerial)) {
3877 /* Forward scanning.
3879 * Delete the old one and drop through to update the tnode
3881 yaffs_DeleteChunk(dev, existingChunk, 1,
3884 /* Backward scanning or we want to use the existing one
3886 * Delete the new one and return early so that the tnode isn't changed
3888 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3896 if (existingChunk == 0)
3899 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3904 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3907 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3909 if (chunkInNAND >= 0)
3910 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3913 T(YAFFS_TRACE_NANDACCESS,
3914 (TSTR("Chunk %d not found zero instead" TENDSTR),
3916 /* get sane (zero) data if you read a hole */
3917 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3923 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3927 yaffs_ExtendedTags tags;
3928 yaffs_BlockInfo *bi;
3934 block = chunkId / dev->param.nChunksPerBlock;
3935 page = chunkId % dev->param.nChunksPerBlock;
3938 if (!yaffs_CheckChunkBit(dev, block, page))
3939 T(YAFFS_TRACE_VERIFY,
3940 (TSTR("Deleting invalid chunk %d"TENDSTR),
3943 bi = yaffs_GetBlockInfo(dev, block);
3945 yaffs_UpdateOldestDirtySequence(dev, block, bi);
3947 T(YAFFS_TRACE_DELETION,
3948 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3951 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3953 yaffs_InitialiseTags(&tags);
3955 tags.chunkDeleted = 1;
3957 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3958 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3960 dev->nUnmarkedDeletions++;
3963 /* Pull out of the management area.
3964 * If the whole block became dirty, this will kick off an erasure.
3966 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3967 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3968 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3969 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3972 yaffs_ClearChunkBit(dev, block, page);
3976 if (bi->pagesInUse == 0 &&
3977 !bi->hasShrinkHeader &&
3978 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3979 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3980 yaffs_BlockBecameDirty(dev, block);
3987 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3988 const __u8 *buffer, int nBytes,
3991 /* Find old chunk Need to do this to get serial number
3992 * Write new one and patch into tree.
3993 * Invalidate old tags.
3997 yaffs_ExtendedTags prevTags;
4000 yaffs_ExtendedTags newTags;
4002 yaffs_Device *dev = in->myDev;
4004 yaffs_CheckGarbageCollection(dev,0);
4006 /* Get the previous chunk at this location in the file if it exists.
4007 * If it does not exist then put a zero into the tree. This creates
4008 * the tnode now, rather than later when it is harder to clean up.
4010 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
4011 if(prevChunkId < 1 &&
4012 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
4015 /* Set up new tags */
4016 yaffs_InitialiseTags(&newTags);
4018 newTags.chunkId = chunkInInode;
4019 newTags.objectId = in->objectId;
4020 newTags.serialNumber =
4021 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
4022 newTags.byteCount = nBytes;
4024 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
4025 T(YAFFS_TRACE_ERROR,
4026 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
4032 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4035 if (newChunkId > 0) {
4036 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
4038 if (prevChunkId > 0)
4039 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
4041 yaffs_CheckFileSanity(in);
4047 /* UpdateObjectHeader updates the header on NAND for an object.
4048 * If name is not NULL, then that new name is used.
4050 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
4051 int isShrink, int shadows)
4054 yaffs_BlockInfo *bi;
4056 yaffs_Device *dev = in->myDev;
4063 yaffs_ExtendedTags newTags;
4064 yaffs_ExtendedTags oldTags;
4065 YCHAR *alias = NULL;
4067 __u8 *buffer = NULL;
4068 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
4070 yaffs_ObjectHeader *oh = NULL;
4072 yaffs_strcpy(oldName, _Y("silly old name"));
4076 in == dev->rootDir || /* The rootDir should also be saved */
4079 yaffs_CheckGarbageCollection(dev,0);
4080 yaffs_CheckObjectDetailsLoaded(in);
4082 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
4083 oh = (yaffs_ObjectHeader *) buffer;
4085 prevChunkId = in->hdrChunk;
4087 if (prevChunkId > 0) {
4088 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
4091 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
4093 memcpy(oldName, oh->name, sizeof(oh->name));
4096 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
4098 oh->type = in->variantType;
4099 oh->yst_mode = in->yst_mode;
4100 oh->shadowsObject = oh->inbandShadowsObject = shadows;
4102 #ifdef CONFIG_YAFFS_WINCE
4103 oh->win_atime[0] = in->win_atime[0];
4104 oh->win_ctime[0] = in->win_ctime[0];
4105 oh->win_mtime[0] = in->win_mtime[0];
4106 oh->win_atime[1] = in->win_atime[1];
4107 oh->win_ctime[1] = in->win_ctime[1];
4108 oh->win_mtime[1] = in->win_mtime[1];
4110 oh->yst_uid = in->yst_uid;
4111 oh->yst_gid = in->yst_gid;
4112 oh->yst_atime = in->yst_atime;
4113 oh->yst_mtime = in->yst_mtime;
4114 oh->yst_ctime = in->yst_ctime;
4115 oh->yst_rdev = in->yst_rdev;
4118 oh->parentObjectId = in->parent->objectId;
4120 oh->parentObjectId = 0;
4122 if (name && *name) {
4123 memset(oh->name, 0, sizeof(oh->name));
4124 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
4125 } else if (prevChunkId > 0)
4126 memcpy(oh->name, oldName, sizeof(oh->name));
4128 memset(oh->name, 0, sizeof(oh->name));
4130 oh->isShrink = isShrink;
4132 switch (in->variantType) {
4133 case YAFFS_OBJECT_TYPE_UNKNOWN:
4134 /* Should not happen */
4136 case YAFFS_OBJECT_TYPE_FILE:
4138 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4139 || oh->parentObjectId ==
4140 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4141 fileVariant.fileSize;
4143 case YAFFS_OBJECT_TYPE_HARDLINK:
4144 oh->equivalentObjectId =
4145 in->variant.hardLinkVariant.equivalentObjectId;
4147 case YAFFS_OBJECT_TYPE_SPECIAL:
4150 case YAFFS_OBJECT_TYPE_DIRECTORY:
4153 case YAFFS_OBJECT_TYPE_SYMLINK:
4154 alias = in->variant.symLinkVariant.alias;
4156 alias = _Y("no alias");
4157 yaffs_strncpy(oh->alias,
4159 YAFFS_MAX_ALIAS_LENGTH);
4160 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4165 yaffs_InitialiseTags(&newTags);
4167 newTags.chunkId = 0;
4168 newTags.objectId = in->objectId;
4169 newTags.serialNumber = in->serial;
4171 /* Add extra info for file header */
4173 newTags.extraHeaderInfoAvailable = 1;
4174 newTags.extraParentObjectId = oh->parentObjectId;
4175 newTags.extraFileLength = oh->fileSize;
4176 newTags.extraIsShrinkHeader = oh->isShrink;
4177 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4178 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4179 newTags.extraObjectType = in->variantType;
4181 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4183 /* Create new chunk in NAND */
4185 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4186 (prevChunkId > 0) ? 1 : 0);
4188 if (newChunkId >= 0) {
4190 in->hdrChunk = newChunkId;
4192 if (prevChunkId > 0) {
4193 yaffs_DeleteChunk(dev, prevChunkId, 1,
4197 if (!yaffs_ObjectHasCachedWriteData(in))
4200 /* If this was a shrink, then mark the block that the chunk lives on */
4202 bi = yaffs_GetBlockInfo(in->myDev,
4203 newChunkId / in->myDev->param.nChunksPerBlock);
4204 bi->hasShrinkHeader = 1;
4209 retVal = newChunkId;
4214 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4219 /*------------------------ Short Operations Cache ----------------------------------------
4220 * In many situations where there is no high level buffering (eg WinCE) a lot of
4221 * reads might be short sequential reads, and a lot of writes may be short
4222 * sequential writes. eg. scanning/writing a jpeg file.
4223 * In these cases, a short read/write cache can provide a huge perfomance benefit
4224 * with dumb-as-a-rock code.
4225 * In Linux, the page cache provides read buffering aand the short op cache provides write
4228 * There are a limited number (~10) of cache chunks per device so that we don't
4229 * need a very intelligent search.
4232 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4234 yaffs_Device *dev = obj->myDev;
4236 yaffs_ChunkCache *cache;
4237 int nCaches = obj->myDev->param.nShortOpCaches;
4239 for (i = 0; i < nCaches; i++) {
4240 cache = &dev->srCache[i];
4241 if (cache->object == obj &&
4250 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4252 yaffs_Device *dev = obj->myDev;
4253 int lowest = -99; /* Stop compiler whining. */
4255 yaffs_ChunkCache *cache;
4256 int chunkWritten = 0;
4257 int nCaches = obj->myDev->param.nShortOpCaches;
4263 /* Find the dirty cache for this object with the lowest chunk id. */
4264 for (i = 0; i < nCaches; i++) {
4265 if (dev->srCache[i].object == obj &&
4266 dev->srCache[i].dirty) {
4268 || dev->srCache[i].chunkId <
4270 cache = &dev->srCache[i];
4271 lowest = cache->chunkId;
4276 if (cache && !cache->locked) {
4277 /* Write it out and free it up */
4280 yaffs_WriteChunkDataToObject(cache->object,
4286 cache->object = NULL;
4289 } while (cache && chunkWritten > 0);
4292 /* Hoosterman, disk full while writing cache out. */
4293 T(YAFFS_TRACE_ERROR,
4294 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4301 /*yaffs_FlushEntireDeviceCache(dev)
4306 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4309 int nCaches = dev->param.nShortOpCaches;
4312 /* Find a dirty object in the cache and flush it...
4313 * until there are no further dirty objects.
4317 for (i = 0; i < nCaches && !obj; i++) {
4318 if (dev->srCache[i].object &&
4319 dev->srCache[i].dirty)
4320 obj = dev->srCache[i].object;
4324 yaffs_FlushFilesChunkCache(obj);
4331 /* Grab us a cache chunk for use.
4332 * First look for an empty one.
4333 * Then look for the least recently used non-dirty one.
4334 * Then look for the least recently used dirty one...., flush and look again.
4336 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4340 if (dev->param.nShortOpCaches > 0) {
4341 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4342 if (!dev->srCache[i].object)
4343 return &dev->srCache[i];
4350 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4352 yaffs_ChunkCache *cache;
4353 yaffs_Object *theObj;
4358 if (dev->param.nShortOpCaches > 0) {
4359 /* Try find a non-dirty one... */
4361 cache = yaffs_GrabChunkCacheWorker(dev);
4364 /* They were all dirty, find the last recently used object and flush
4365 * its cache, then find again.
4366 * NB what's here is not very accurate, we actually flush the object
4367 * the last recently used page.
4370 /* With locking we can't assume we can use entry zero */
4377 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4378 if (dev->srCache[i].object &&
4379 !dev->srCache[i].locked &&
4380 (dev->srCache[i].lastUse < usage || !cache)) {
4381 usage = dev->srCache[i].lastUse;
4382 theObj = dev->srCache[i].object;
4383 cache = &dev->srCache[i];
4388 if (!cache || cache->dirty) {
4389 /* Flush and try again */
4390 yaffs_FlushFilesChunkCache(theObj);
4391 cache = yaffs_GrabChunkCacheWorker(dev);
4401 /* Find a cached chunk */
4402 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4405 yaffs_Device *dev = obj->myDev;
4407 if (dev->param.nShortOpCaches > 0) {
4408 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4409 if (dev->srCache[i].object == obj &&
4410 dev->srCache[i].chunkId == chunkId) {
4413 return &dev->srCache[i];
4420 /* Mark the chunk for the least recently used algorithym */
4421 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4425 if (dev->param.nShortOpCaches > 0) {
4426 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4427 /* Reset the cache usages */
4429 for (i = 1; i < dev->param.nShortOpCaches; i++)
4430 dev->srCache[i].lastUse = 0;
4437 cache->lastUse = dev->srLastUse;
4444 /* Invalidate a single cache page.
4445 * Do this when a whole page gets written,
4446 * ie the short cache for this page is no longer valid.
4448 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4450 if (object->myDev->param.nShortOpCaches > 0) {
4451 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4454 cache->object = NULL;
4458 /* Invalidate all the cache pages associated with this object
4459 * Do this whenever ther file is deleted or resized.
4461 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4464 yaffs_Device *dev = in->myDev;
4466 if (dev->param.nShortOpCaches > 0) {
4467 /* Invalidate it. */
4468 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4469 if (dev->srCache[i].object == in)
4470 dev->srCache[i].object = NULL;
4475 /*--------------------- Checkpointing --------------------*/
4478 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4480 yaffs_CheckpointValidity cp;
4482 memset(&cp, 0, sizeof(cp));
4484 cp.structType = sizeof(cp);
4485 cp.magic = YAFFS_MAGIC;
4486 cp.version = YAFFS_CHECKPOINT_VERSION;
4487 cp.head = (head) ? 1 : 0;
4489 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4493 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4495 yaffs_CheckpointValidity cp;
4498 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4501 ok = (cp.structType == sizeof(cp)) &&
4502 (cp.magic == YAFFS_MAGIC) &&
4503 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4504 (cp.head == ((head) ? 1 : 0));
4508 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4511 cp->nErasedBlocks = dev->nErasedBlocks;
4512 cp->allocationBlock = dev->allocationBlock;
4513 cp->allocationPage = dev->allocationPage;
4514 cp->nFreeChunks = dev->nFreeChunks;
4516 cp->nDeletedFiles = dev->nDeletedFiles;
4517 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4518 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4519 cp->sequenceNumber = dev->sequenceNumber;
4523 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4524 yaffs_CheckpointDevice *cp)
4526 dev->nErasedBlocks = cp->nErasedBlocks;
4527 dev->allocationBlock = cp->allocationBlock;
4528 dev->allocationPage = cp->allocationPage;
4529 dev->nFreeChunks = cp->nFreeChunks;
4531 dev->nDeletedFiles = cp->nDeletedFiles;
4532 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4533 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4534 dev->sequenceNumber = cp->sequenceNumber;
4538 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4540 yaffs_CheckpointDevice cp;
4542 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4546 /* Write device runtime values*/
4547 yaffs_DeviceToCheckpointDevice(&cp, dev);
4548 cp.structType = sizeof(cp);
4550 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4552 /* Write block info */
4554 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4555 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4558 /* Write chunk bits */
4560 nBytes = nBlocks * dev->chunkBitmapStride;
4561 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4567 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4569 yaffs_CheckpointDevice cp;
4571 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4575 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4579 if (cp.structType != sizeof(cp))
4583 yaffs_CheckpointDeviceToDevice(dev, &cp);
4585 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4587 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4591 nBytes = nBlocks * dev->chunkBitmapStride;
4593 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4598 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4602 cp->objectId = obj->objectId;
4603 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4604 cp->hdrChunk = obj->hdrChunk;
4605 cp->variantType = obj->variantType;
4606 cp->deleted = obj->deleted;
4607 cp->softDeleted = obj->softDeleted;
4608 cp->unlinked = obj->unlinked;
4609 cp->fake = obj->fake;
4610 cp->renameAllowed = obj->renameAllowed;
4611 cp->unlinkAllowed = obj->unlinkAllowed;
4612 cp->serial = obj->serial;
4613 cp->nDataChunks = obj->nDataChunks;
4615 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4616 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4617 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4618 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4621 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4624 yaffs_Object *parent;
4626 if (obj->variantType != cp->variantType) {
4627 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4628 TCONT("chunk %d does not match existing object type %d")
4629 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4634 obj->objectId = cp->objectId;
4637 parent = yaffs_FindOrCreateObjectByNumber(
4640 YAFFS_OBJECT_TYPE_DIRECTORY);
4645 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4646 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4647 TCONT(" chunk %d Parent type, %d, not directory")
4649 cp->objectId, cp->parentId, cp->variantType,
4650 cp->hdrChunk, parent->variantType));
4653 yaffs_AddObjectToDirectory(parent, obj);
4656 obj->hdrChunk = cp->hdrChunk;
4657 obj->variantType = cp->variantType;
4658 obj->deleted = cp->deleted;
4659 obj->softDeleted = cp->softDeleted;
4660 obj->unlinked = cp->unlinked;
4661 obj->fake = cp->fake;
4662 obj->renameAllowed = cp->renameAllowed;
4663 obj->unlinkAllowed = cp->unlinkAllowed;
4664 obj->serial = cp->serial;
4665 obj->nDataChunks = cp->nDataChunks;
4667 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4668 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4669 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4670 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4672 if (obj->hdrChunk > 0)
4673 obj->lazyLoaded = 1;
4679 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4680 __u32 level, int chunkOffset)
4683 yaffs_Device *dev = in->myDev;
4685 int tnodeSize = yaffs_CalcTnodeSize(dev);
4690 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4691 if (tn->internal[i]) {
4692 ok = yaffs_CheckpointTnodeWorker(in,
4695 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4698 } else if (level == 0) {
4699 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4700 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4702 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4710 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4712 __u32 endMarker = ~0;
4715 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4716 ok = yaffs_CheckpointTnodeWorker(obj,
4717 obj->variant.fileVariant.top,
4718 obj->variant.fileVariant.topLevel,
4721 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4728 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4732 yaffs_Device *dev = obj->myDev;
4733 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4736 int tnodeSize = yaffs_CalcTnodeSize(dev);
4738 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4740 while (ok && (~baseChunk)) {
4742 /* Read level 0 tnode */
4745 tn = yaffs_GetTnodeRaw(dev);
4747 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4752 ok = yaffs_AddOrFindLevel0Tnode(dev,
4758 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4762 T(YAFFS_TRACE_CHECKPOINT, (
4763 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4764 nread, baseChunk, ok));
4770 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4773 yaffs_CheckpointObject cp;
4776 struct ylist_head *lh;
4779 /* Iterate through the objects in each hash entry,
4780 * dumping them to the checkpointing stream.
4783 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4784 ylist_for_each(lh, &dev->objectBucket[i].list) {
4786 obj = ylist_entry(lh, yaffs_Object, hashLink);
4787 if (!obj->deferedFree) {
4788 yaffs_ObjectToCheckpointObject(&cp, obj);
4789 cp.structType = sizeof(cp);
4791 T(YAFFS_TRACE_CHECKPOINT, (
4792 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4793 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4795 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4797 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4798 ok = yaffs_WriteCheckpointTnodes(obj);
4804 /* Dump end of list */
4805 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4806 cp.structType = sizeof(cp);
4809 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4814 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4817 yaffs_CheckpointObject cp;
4820 yaffs_Object *hardList = NULL;
4822 while (ok && !done) {
4823 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4824 if (cp.structType != sizeof(cp)) {
4825 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4826 cp.structType, (int)sizeof(cp), ok));
4830 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4831 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4833 if (ok && cp.objectId == ~0)
4836 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4838 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4841 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4842 ok = yaffs_ReadCheckpointTnodes(obj);
4843 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4844 obj->hardLinks.next =
4845 (struct ylist_head *) hardList;
4854 yaffs_HardlinkFixup(dev, hardList);
4859 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4861 __u32 checkpointSum;
4864 yaffs_GetCheckpointSum(dev, &checkpointSum);
4866 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4874 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4876 __u32 checkpointSum0;
4877 __u32 checkpointSum1;
4880 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4882 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4887 if (checkpointSum0 != checkpointSum1)
4894 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4898 if (!yaffs_CheckpointRequired(dev)) {
4899 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4904 ok = yaffs_CheckpointOpen(dev, 1);
4907 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4908 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4911 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4912 ok = yaffs_WriteCheckpointDevice(dev);
4915 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4916 ok = yaffs_WriteCheckpointObjects(dev);
4919 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4920 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4924 ok = yaffs_WriteCheckpointSum(dev);
4926 if (!yaffs_CheckpointClose(dev))
4930 dev->isCheckpointed = 1;
4932 dev->isCheckpointed = 0;
4934 return dev->isCheckpointed;
4937 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4941 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4942 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4947 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4950 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4951 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4954 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4955 ok = yaffs_ReadCheckpointDevice(dev);
4958 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4959 ok = yaffs_ReadCheckpointObjects(dev);
4962 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4963 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4967 ok = yaffs_ReadCheckpointSum(dev);
4968 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4971 if (!yaffs_CheckpointClose(dev))
4975 dev->isCheckpointed = 1;
4977 dev->isCheckpointed = 0;
4983 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4985 if (dev->isCheckpointed ||
4986 dev->blocksInCheckpoint > 0) {
4987 dev->isCheckpointed = 0;
4988 yaffs_CheckpointInvalidateStream(dev);
4990 if (dev->param.markSuperBlockDirty)
4991 dev->param.markSuperBlockDirty(dev);
4995 int yaffs_CheckpointSave(yaffs_Device *dev)
4998 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5000 yaffs_VerifyObjects(dev);
5001 yaffs_VerifyBlocks(dev);
5002 yaffs_VerifyFreeChunks(dev);
5004 if (!dev->isCheckpointed) {
5005 yaffs_InvalidateCheckpoint(dev);
5006 yaffs_WriteCheckpointData(dev);
5009 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5011 return dev->isCheckpointed;
5014 int yaffs_CheckpointRestore(yaffs_Device *dev)
5017 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5019 retval = yaffs_ReadCheckpointData(dev);
5021 if (dev->isCheckpointed) {
5022 yaffs_VerifyObjects(dev);
5023 yaffs_VerifyBlocks(dev);
5024 yaffs_VerifyFreeChunks(dev);
5027 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5032 /*--------------------- File read/write ------------------------
5033 * Read and write have very similar structures.
5034 * In general the read/write has three parts to it
5035 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
5036 * Some complete chunks
5037 * An incomplete chunk to end off with
5039 * Curve-balls: the first chunk might also be the last chunk.
5042 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
5051 yaffs_ChunkCache *cache;
5058 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5059 /* start = offset % dev->nDataBytesPerChunk; */
5060 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5063 /* OK now check for the curveball where the start and end are in
5066 if ((start + n) < dev->nDataBytesPerChunk)
5069 nToCopy = dev->nDataBytesPerChunk - start;
5071 cache = yaffs_FindChunkCache(in, chunk);
5073 /* If the chunk is already in the cache or it is less than a whole chunk
5074 * or we're using inband tags then use the cache (if there is caching)
5075 * else bypass the cache.
5077 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5078 if (dev->param.nShortOpCaches > 0) {
5080 /* If we can't find the data in the cache, then load it up. */
5083 cache = yaffs_GrabChunkCache(in->myDev);
5085 cache->chunkId = chunk;
5088 yaffs_ReadChunkDataFromObject(in, chunk,
5094 yaffs_UseChunkCache(dev, cache, 0);
5099 memcpy(buffer, &cache->data[start], nToCopy);
5103 /* Read into the local buffer then copy..*/
5106 yaffs_GetTempBuffer(dev, __LINE__);
5107 yaffs_ReadChunkDataFromObject(in, chunk,
5110 memcpy(buffer, &localBuffer[start], nToCopy);
5113 yaffs_ReleaseTempBuffer(dev, localBuffer,
5119 /* A full chunk. Read directly into the supplied buffer. */
5120 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
5134 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5135 int nBytes, int writeThrough)
5144 int startOfWrite = offset;
5145 int chunkWritten = 0;
5153 while (n > 0 && chunkWritten >= 0) {
5154 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5156 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5157 start >= dev->nDataBytesPerChunk) {
5158 T(YAFFS_TRACE_ERROR, (
5159 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5161 (int)offset, chunk, start));
5163 chunk++; /* File pos to chunk in file offset */
5165 /* OK now check for the curveball where the start and end are in
5169 if ((start + n) < dev->nDataBytesPerChunk) {
5172 /* Now folks, to calculate how many bytes to write back....
5173 * If we're overwriting and not writing to then end of file then
5174 * we need to write back as much as was there before.
5177 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5179 if (chunkStart > in->variant.fileVariant.fileSize)
5180 nBytesRead = 0; /* Past end of file */
5182 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5184 if (nBytesRead > dev->nDataBytesPerChunk)
5185 nBytesRead = dev->nDataBytesPerChunk;
5189 (start + n)) ? nBytesRead : (start + n);
5191 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5195 nToCopy = dev->nDataBytesPerChunk - start;
5196 nToWriteBack = dev->nDataBytesPerChunk;
5199 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5200 /* An incomplete start or end chunk (or maybe both start and end chunk),
5201 * or we're using inband tags, so we want to use the cache buffers.
5203 if (dev->param.nShortOpCaches > 0) {
5204 yaffs_ChunkCache *cache;
5205 /* If we can't find the data in the cache, then load the cache */
5206 cache = yaffs_FindChunkCache(in, chunk);
5209 && yaffs_CheckSpaceForAllocation(dev, 1)) {
5210 cache = yaffs_GrabChunkCache(dev);
5212 cache->chunkId = chunk;
5215 yaffs_ReadChunkDataFromObject(in, chunk,
5219 !yaffs_CheckSpaceForAllocation(dev, 1)) {
5220 /* Drop the cache if it was a read cache item and
5221 * no space check has been made for it.
5227 yaffs_UseChunkCache(dev, cache, 1);
5231 memcpy(&cache->data[start], buffer,
5236 cache->nBytes = nToWriteBack;
5240 yaffs_WriteChunkDataToObject
5243 cache->data, cache->nBytes,
5249 chunkWritten = -1; /* fail the write */
5252 /* An incomplete start or end chunk (or maybe both start and end chunk)
5253 * Read into the local buffer then copy, then copy over and write back.
5257 yaffs_GetTempBuffer(dev, __LINE__);
5259 yaffs_ReadChunkDataFromObject(in, chunk,
5264 memcpy(&localBuffer[start], buffer, nToCopy);
5267 yaffs_WriteChunkDataToObject(in, chunk,
5272 yaffs_ReleaseTempBuffer(dev, localBuffer,
5278 /* A full chunk. Write directly from the supplied buffer. */
5283 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5284 dev->nDataBytesPerChunk,
5287 /* Since we've overwritten the cached data, we better invalidate it. */
5288 yaffs_InvalidateChunkCache(in, chunk);
5291 if (chunkWritten >= 0) {
5300 /* Update file object */
5302 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5303 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5310 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5311 int nBytes, int writeThrough)
5313 yaffs_HandleHole(in,offset);
5314 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
5319 /* ---------------------- File resizing stuff ------------------ */
5321 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5324 yaffs_Device *dev = in->myDev;
5325 int oldFileSize = in->variant.fileVariant.fileSize;
5327 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5329 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5330 dev->nDataBytesPerChunk;
5334 /* Delete backwards so that we don't end up with holes if
5335 * power is lost part-way through the operation.
5337 for (i = lastDel; i >= startDel; i--) {
5338 /* NB this could be optimised somewhat,
5339 * eg. could retrieve the tags and write them without
5340 * using yaffs_DeleteChunk
5343 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5346 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5348 ((dev->internalEndBlock +
5349 1) * dev->param.nChunksPerBlock)) {
5350 T(YAFFS_TRACE_ALWAYS,
5351 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5355 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5363 static void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
5366 __u32 newSizeOfPartialChunk;
5367 yaffs_Device *dev = obj->myDev;
5369 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5371 yaffs_PruneResizedChunks(obj, newSize);
5373 if (newSizeOfPartialChunk != 0) {
5374 int lastChunk = 1 + newFullChunks;
5375 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5377 /* Got to read and rewrite the last chunk with its new size and zero pad */
5378 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
5379 memset(localBuffer + newSizeOfPartialChunk, 0,
5380 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5382 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
5383 newSizeOfPartialChunk, 1);
5385 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5388 obj->variant.fileVariant.fileSize = newSize;
5390 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
5394 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize)
5396 /* if newsSize > oldFileSize.
5397 * We're going to be writing a hole.
5398 * If the hole is small then write zeros otherwise write a start of hole marker.
5405 int result = YAFFS_OK;
5406 yaffs_Device *dev = NULL;
5408 __u8 *localBuffer = NULL;
5410 int smallIncreaseOk = 0;
5415 if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
5420 /* Bail out if not yaffs2 mode */
5421 if(!dev->param.isYaffs2)
5424 oldFileSize = obj->variant.fileVariant.fileSize;
5426 if (newSize <= oldFileSize)
5429 increase = newSize - oldFileSize;
5431 if(increase < YAFFS_SMALL_HOLE_THRESHOLD * dev->nDataBytesPerChunk &&
5432 yaffs_CheckSpaceForAllocation(dev, YAFFS_SMALL_HOLE_THRESHOLD + 1))
5438 localBuffer= yaffs_GetTempBuffer(dev, __LINE__);
5441 /* fill hole with zero bytes */
5442 int pos = oldFileSize;
5445 memset(localBuffer,0,dev->nDataBytesPerChunk);
5446 smallIncreaseOk = 1;
5448 while(increase > 0 && smallIncreaseOk){
5449 thisWrite = increase;
5450 if(thisWrite > dev->nDataBytesPerChunk)
5451 thisWrite = dev->nDataBytesPerChunk;
5452 written = yaffs_DoWriteDataToFile(obj,localBuffer,pos,thisWrite,0);
5453 if(written == thisWrite){
5455 increase -= thisWrite;
5457 smallIncreaseOk = 0;
5460 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
5462 /* If we were out of space then reverse any chunks we've added */
5463 if(!smallIncreaseOk)
5464 yaffs_ResizeDown(obj, oldFileSize);
5467 if (!smallIncreaseOk &&
5469 obj->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5470 obj->parent->objectId != YAFFS_OBJECTID_DELETED){
5471 /* Write a hole start header with the old file size */
5472 yaffs_UpdateObjectHeader(obj, NULL, 0,1,0);
5479 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5481 yaffs_Device *dev = in->myDev;
5482 int oldFileSize = in->variant.fileVariant.fileSize;
5484 yaffs_FlushFilesChunkCache(in);
5485 yaffs_InvalidateWholeChunkCache(in);
5487 yaffs_CheckGarbageCollection(dev,0);
5489 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5492 if (newSize == oldFileSize)
5495 if(newSize > oldFileSize){
5496 yaffs_HandleHole(in,newSize);
5497 in->variant.fileVariant.fileSize = newSize;
5499 /* newSize < oldFileSize */
5500 yaffs_ResizeDown(in, newSize);
5503 /* Write a new object header to reflect the resize.
5504 * show we've shrunk the file, if need be
5505 * Do this only if the file is not in the deleted directories
5506 * and is not shadowed.
5510 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5511 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5512 yaffs_UpdateObjectHeader(in, NULL, 0,0,0);
5518 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5520 YCHAR *alias = NULL;
5521 obj = yaffs_GetEquivalentObject(obj);
5523 switch (obj->variantType) {
5524 case YAFFS_OBJECT_TYPE_FILE:
5525 return obj->variant.fileVariant.fileSize;
5526 case YAFFS_OBJECT_TYPE_SYMLINK:
5527 alias = obj->variant.symLinkVariant.alias;
5530 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5538 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5542 yaffs_FlushFilesChunkCache(in);
5543 if(dataSync) /* Only sync data */
5547 #ifdef CONFIG_YAFFS_WINCE
5548 yfsd_WinFileTimeNow(in->win_mtime);
5551 in->yst_mtime = Y_CURRENT_TIME;
5556 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5557 0) ? YAFFS_OK : YAFFS_FAIL;
5567 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5570 /* First off, invalidate the file's data in the cache, without flushing. */
5571 yaffs_InvalidateWholeChunkCache(in);
5573 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5574 /* Move to the unlinked directory so we have a record that it was deleted. */
5575 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5579 yaffs_RemoveObjectFromDirectory(in);
5580 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5583 yaffs_FreeObject(in);
5588 /* yaffs_DeleteFile deletes the whole file data
5589 * and the inode associated with the file.
5590 * It does not delete the links associated with the file.
5592 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5596 int immediateDeletion = 0;
5597 yaffs_Device *dev = in->myDev;
5600 immediateDeletion = 1;
5602 if (immediateDeletion) {
5604 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5605 _Y("deleted"), 0, 0);
5606 T(YAFFS_TRACE_TRACING,
5607 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5610 in->myDev->nDeletedFiles++;
5611 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5612 yaffs_ResizeFile(in, 0);
5613 yaffs_SoftDeleteFile(in);
5616 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5617 _Y("unlinked"), 0, 0);
5624 int yaffs_DeleteFile(yaffs_Object *in)
5626 int retVal = YAFFS_OK;
5627 int deleted; /* Need to cache value on stack if in is freed */
5628 yaffs_Device *dev = in->myDev;
5630 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5631 yaffs_ResizeFile(in, 0);
5633 if (in->nDataChunks > 0) {
5634 /* Use soft deletion if there is data in the file.
5635 * That won't be the case if it has been resized to zero.
5638 retVal = yaffs_UnlinkFileIfNeeded(in);
5640 deleted = in->deleted;
5642 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5645 in->myDev->nDeletedFiles++;
5646 yaffs_SoftDeleteFile(in);
5648 return deleted ? YAFFS_OK : YAFFS_FAIL;
5650 /* The file has no data chunks so we toss it immediately */
5651 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5652 in->variant.fileVariant.top = NULL;
5653 yaffs_DoGenericObjectDeletion(in);
5659 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5661 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5662 !(ylist_empty(&obj->variant.directoryVariant.children));
5665 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5667 /* First check that the directory is empty. */
5668 if (yaffs_IsNonEmptyDirectory(obj))
5671 return yaffs_DoGenericObjectDeletion(obj);
5674 static int yaffs_DeleteSymLink(yaffs_Object *in)
5676 if(in->variant.symLinkVariant.alias)
5677 YFREE(in->variant.symLinkVariant.alias);
5678 in->variant.symLinkVariant.alias=NULL;
5680 return yaffs_DoGenericObjectDeletion(in);
5683 static int yaffs_DeleteHardLink(yaffs_Object *in)
5685 /* remove this hardlink from the list assocaited with the equivalent
5688 ylist_del_init(&in->hardLinks);
5689 return yaffs_DoGenericObjectDeletion(in);
5692 int yaffs_DeleteObject(yaffs_Object *obj)
5695 switch (obj->variantType) {
5696 case YAFFS_OBJECT_TYPE_FILE:
5697 retVal = yaffs_DeleteFile(obj);
5699 case YAFFS_OBJECT_TYPE_DIRECTORY:
5700 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5701 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5702 ylist_del_init(&obj->variant.directoryVariant.dirty);
5704 return yaffs_DeleteDirectory(obj);
5706 case YAFFS_OBJECT_TYPE_SYMLINK:
5707 retVal = yaffs_DeleteSymLink(obj);
5709 case YAFFS_OBJECT_TYPE_HARDLINK:
5710 retVal = yaffs_DeleteHardLink(obj);
5712 case YAFFS_OBJECT_TYPE_SPECIAL:
5713 retVal = yaffs_DoGenericObjectDeletion(obj);
5715 case YAFFS_OBJECT_TYPE_UNKNOWN:
5717 break; /* should not happen. */
5723 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5726 int immediateDeletion = 0;
5729 immediateDeletion = 1;
5732 yaffs_UpdateParent(obj->parent);
5734 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5735 return yaffs_DeleteHardLink(obj);
5736 } else if (!ylist_empty(&obj->hardLinks)) {
5737 /* Curve ball: We're unlinking an object that has a hardlink.
5739 * This problem arises because we are not strictly following
5740 * The Linux link/inode model.
5742 * We can't really delete the object.
5743 * Instead, we do the following:
5744 * - Select a hardlink.
5745 * - Unhook it from the hard links
5746 * - Move it from its parent directory (so that the rename can work)
5747 * - Rename the object to the hardlink's name.
5748 * - Delete the hardlink
5752 yaffs_Object *parent;
5754 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5756 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5758 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5759 parent = hl->parent;
5761 ylist_del_init(&hl->hardLinks);
5763 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5765 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5767 if (retVal == YAFFS_OK)
5768 retVal = yaffs_DoGenericObjectDeletion(hl);
5772 } else if (immediateDeletion) {
5773 switch (obj->variantType) {
5774 case YAFFS_OBJECT_TYPE_FILE:
5775 return yaffs_DeleteFile(obj);
5777 case YAFFS_OBJECT_TYPE_DIRECTORY:
5778 ylist_del_init(&obj->variant.directoryVariant.dirty);
5779 return yaffs_DeleteDirectory(obj);
5781 case YAFFS_OBJECT_TYPE_SYMLINK:
5782 return yaffs_DeleteSymLink(obj);
5784 case YAFFS_OBJECT_TYPE_SPECIAL:
5785 return yaffs_DoGenericObjectDeletion(obj);
5787 case YAFFS_OBJECT_TYPE_HARDLINK:
5788 case YAFFS_OBJECT_TYPE_UNKNOWN:
5792 } else if(yaffs_IsNonEmptyDirectory(obj))
5795 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5796 _Y("unlinked"), 0, 0);
5800 static int yaffs_UnlinkObject(yaffs_Object *obj)
5803 if (obj && obj->unlinkAllowed)
5804 return yaffs_UnlinkWorker(obj);
5809 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5813 obj = yaffs_FindObjectByName(dir, name);
5814 return yaffs_UnlinkObject(obj);
5817 /*----------------------- Initialisation Scanning ---------------------- */
5819 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5820 int backwardScanning)
5824 if (!backwardScanning) {
5825 /* Handle YAFFS1 forward scanning case
5826 * For YAFFS1 we always do the deletion
5830 /* Handle YAFFS2 case (backward scanning)
5831 * If the shadowed object exists then ignore.
5833 obj = yaffs_FindObjectByNumber(dev, objId);
5838 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5839 * We put it in unlinked dir to be cleaned up after the scanning
5842 yaffs_FindOrCreateObjectByNumber(dev, objId,
5843 YAFFS_OBJECT_TYPE_FILE);
5846 obj->isShadowed = 1;
5847 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5848 obj->variant.fileVariant.shrinkSize = 0;
5849 obj->valid = 1; /* So that we don't read any other info for this file */
5859 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5866 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5868 in = yaffs_FindObjectByNumber(dev,
5869 hl->variant.hardLinkVariant.
5870 equivalentObjectId);
5873 /* Add the hardlink pointers */
5874 hl->variant.hardLinkVariant.equivalentObject = in;
5875 ylist_add(&hl->hardLinks, &in->hardLinks);
5877 /* Todo Need to report/handle this better.
5878 * Got a problem... hardlink to a non-existant object
5880 hl->variant.hardLinkVariant.equivalentObject = NULL;
5881 YINIT_LIST_HEAD(&hl->hardLinks);
5891 static int ybicmp(const void *a, const void *b)
5893 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5894 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5895 register int ablock = ((yaffs_BlockIndex *)a)->block;
5896 register int bblock = ((yaffs_BlockIndex *)b)->block;
5898 return ablock - bblock;
5904 struct yaffs_ShadowFixerStruct {
5907 struct yaffs_ShadowFixerStruct *next;
5911 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5914 * Sort out state of unlinked and deleted objects after scanning.
5916 struct ylist_head *i;
5917 struct ylist_head *n;
5920 /* Soft delete all the unlinked files */
5921 ylist_for_each_safe(i, n,
5922 &dev->unlinkedDir->variant.directoryVariant.children) {
5924 l = ylist_entry(i, yaffs_Object, siblings);
5925 yaffs_DeleteObject(l);
5929 ylist_for_each_safe(i, n,
5930 &dev->deletedDir->variant.directoryVariant.children) {
5932 l = ylist_entry(i, yaffs_Object, siblings);
5933 yaffs_DeleteObject(l);
5940 * This code iterates through all the objects making sure that they are rooted.
5941 * Any unrooted objects are re-rooted in lost+found.
5942 * An object needs to be in one of:
5943 * - Directly under deleted, unlinked
5944 * - Directly or indirectly under root.
5947 * This code assumes that we don't ever change the current relationships between
5949 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5950 * lostNfound->parent == rootDir
5952 * This fixes the problem where directories might have inadvertently been deleted
5953 * leaving the object "hanging" without being rooted in the directory tree.
5956 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5958 return (obj == dev->deletedDir ||
5959 obj == dev->unlinkedDir||
5960 obj == dev->rootDir);
5963 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5966 yaffs_Object *parent;
5968 struct ylist_head *lh;
5969 struct ylist_head *n;
5974 /* Iterate through the objects in each hash entry,
5975 * looking at each object.
5976 * Make sure it is rooted.
5979 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5980 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5982 obj = ylist_entry(lh, yaffs_Object, hashLink);
5983 parent= obj->parent;
5985 if(yaffs_HasNULLParent(dev,obj)){
5986 /* These directories are not hanging */
5989 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5991 else if(yaffs_HasNULLParent(dev,parent))
5995 * Need to follow the parent chain to see if it is hanging.
6000 while(parent != dev->rootDir &&
6002 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
6004 parent = parent->parent;
6007 if(parent != dev->rootDir)
6012 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
6014 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
6023 * Delete directory contents for cleaning up lost and found.
6025 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
6028 struct ylist_head *lh;
6029 struct ylist_head *n;
6031 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6034 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
6036 obj = ylist_entry(lh, yaffs_Object, siblings);
6037 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
6038 yaffs_DeleteDirectoryContents(obj);
6041 (TSTR("Deleting lost_found object %d" TENDSTR),
6044 /* Need to use UnlinkObject since Delete would not handle
6045 * hardlinked objects correctly.
6047 yaffs_UnlinkObject(obj);
6053 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
6055 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
6058 static int yaffs_Scan(yaffs_Device *dev)
6060 yaffs_ExtendedTags tags;
6070 yaffs_BlockState state;
6071 yaffs_Object *hardList = NULL;
6072 yaffs_BlockInfo *bi;
6073 __u32 sequenceNumber;
6074 yaffs_ObjectHeader *oh;
6076 yaffs_Object *parent;
6078 int alloc_failed = 0;
6080 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
6088 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
6089 dev->internalStartBlock, dev->internalEndBlock));
6091 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6093 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6095 /* Scan all the blocks to determine their state */
6096 bi = dev->blockInfo;
6097 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6098 yaffs_ClearChunkBits(dev, blk);
6100 bi->softDeletions = 0;
6102 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6104 bi->blockState = state;
6105 bi->sequenceNumber = sequenceNumber;
6107 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6108 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6110 T(YAFFS_TRACE_SCAN_DEBUG,
6111 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6112 state, sequenceNumber));
6114 if (state == YAFFS_BLOCK_STATE_DEAD) {
6115 T(YAFFS_TRACE_BAD_BLOCKS,
6116 (TSTR("block %d is bad" TENDSTR), blk));
6117 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6118 T(YAFFS_TRACE_SCAN_DEBUG,
6119 (TSTR("Block empty " TENDSTR)));
6120 dev->nErasedBlocks++;
6121 dev->nFreeChunks += dev->param.nChunksPerBlock;
6126 startIterator = dev->internalStartBlock;
6127 endIterator = dev->internalEndBlock;
6129 /* For each block.... */
6130 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
6137 blk = blockIterator;
6139 bi = yaffs_GetBlockInfo(dev, blk);
6140 state = bi->blockState;
6144 /* For each chunk in each block that needs scanning....*/
6145 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
6146 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
6147 /* Read the tags and decide what to do */
6148 chunk = blk * dev->param.nChunksPerBlock + c;
6150 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6153 /* Let's have a good look at this chunk... */
6155 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
6161 /*T((" %d %d deleted\n",blk,c)); */
6162 } else if (!tags.chunkUsed) {
6163 /* An unassigned chunk in the block
6164 * This means that either the block is empty or
6165 * this is the one being allocated from
6169 /* We're looking at the first chunk in the block so the block is unused */
6170 state = YAFFS_BLOCK_STATE_EMPTY;
6171 dev->nErasedBlocks++;
6173 /* this is the block being allocated from */
6176 (" Allocating from %d %d" TENDSTR),
6178 state = YAFFS_BLOCK_STATE_ALLOCATING;
6179 dev->allocationBlock = blk;
6180 dev->allocationPage = c;
6181 dev->allocationBlockFinder = blk;
6182 /* Set block finder here to encourage the allocator to go forth from here. */
6186 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
6187 } else if (tags.chunkId > 0) {
6188 /* chunkId > 0 so it is a data chunk... */
6189 unsigned int endpos;
6191 yaffs_SetChunkBit(dev, blk, c);
6194 in = yaffs_FindOrCreateObjectByNumber(dev,
6197 YAFFS_OBJECT_TYPE_FILE);
6198 /* PutChunkIntoFile checks for a clash (two data chunks with
6199 * the same chunkId).
6206 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
6211 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
6214 in->variantType == YAFFS_OBJECT_TYPE_FILE
6215 && in->variant.fileVariant.scannedFileSize <
6217 in->variant.fileVariant.
6218 scannedFileSize = endpos;
6219 if (!dev->param.useHeaderFileSize) {
6220 in->variant.fileVariant.
6222 in->variant.fileVariant.
6227 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
6229 /* chunkId == 0, so it is an ObjectHeader.
6230 * Thus, we read in the object header and make the object
6232 yaffs_SetChunkBit(dev, blk, c);
6235 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6239 oh = (yaffs_ObjectHeader *) chunkData;
6241 in = yaffs_FindObjectByNumber(dev,
6243 if (in && in->variantType != oh->type) {
6244 /* This should not happen, but somehow
6245 * Wev'e ended up with an objectId that has been reused but not yet
6246 * deleted, and worse still it has changed type. Delete the old object.
6249 yaffs_DeleteObject(in);
6254 in = yaffs_FindOrCreateObjectByNumber(dev,
6262 if (in && oh->shadowsObject > 0) {
6264 struct yaffs_ShadowFixerStruct *fixer;
6265 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6267 fixer->next = shadowFixerList;
6268 shadowFixerList = fixer;
6269 fixer->objectId = tags.objectId;
6270 fixer->shadowedId = oh->shadowsObject;
6275 if (in && in->valid) {
6276 /* We have already filled this one. We have a duplicate and need to resolve it. */
6278 unsigned existingSerial = in->serial;
6279 unsigned newSerial = tags.serialNumber;
6281 if (((existingSerial + 1) & 3) == newSerial) {
6282 /* Use new one - destroy the exisiting one */
6283 yaffs_DeleteChunk(dev,
6288 /* Use existing - destroy this one. */
6289 yaffs_DeleteChunk(dev, chunk, 1,
6294 if (in && !in->valid &&
6295 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6296 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6297 /* We only load some info, don't fiddle with directory structure */
6299 in->variantType = oh->type;
6301 in->yst_mode = oh->yst_mode;
6302 #ifdef CONFIG_YAFFS_WINCE
6303 in->win_atime[0] = oh->win_atime[0];
6304 in->win_ctime[0] = oh->win_ctime[0];
6305 in->win_mtime[0] = oh->win_mtime[0];
6306 in->win_atime[1] = oh->win_atime[1];
6307 in->win_ctime[1] = oh->win_ctime[1];
6308 in->win_mtime[1] = oh->win_mtime[1];
6310 in->yst_uid = oh->yst_uid;
6311 in->yst_gid = oh->yst_gid;
6312 in->yst_atime = oh->yst_atime;
6313 in->yst_mtime = oh->yst_mtime;
6314 in->yst_ctime = oh->yst_ctime;
6315 in->yst_rdev = oh->yst_rdev;
6317 in->hdrChunk = chunk;
6318 in->serial = tags.serialNumber;
6320 } else if (in && !in->valid) {
6321 /* we need to load this info */
6324 in->variantType = oh->type;
6326 in->yst_mode = oh->yst_mode;
6327 #ifdef CONFIG_YAFFS_WINCE
6328 in->win_atime[0] = oh->win_atime[0];
6329 in->win_ctime[0] = oh->win_ctime[0];
6330 in->win_mtime[0] = oh->win_mtime[0];
6331 in->win_atime[1] = oh->win_atime[1];
6332 in->win_ctime[1] = oh->win_ctime[1];
6333 in->win_mtime[1] = oh->win_mtime[1];
6335 in->yst_uid = oh->yst_uid;
6336 in->yst_gid = oh->yst_gid;
6337 in->yst_atime = oh->yst_atime;
6338 in->yst_mtime = oh->yst_mtime;
6339 in->yst_ctime = oh->yst_ctime;
6340 in->yst_rdev = oh->yst_rdev;
6342 in->hdrChunk = chunk;
6343 in->serial = tags.serialNumber;
6345 yaffs_SetObjectName(in, oh->name);
6348 /* directory stuff...
6353 yaffs_FindOrCreateObjectByNumber
6354 (dev, oh->parentObjectId,
6355 YAFFS_OBJECT_TYPE_DIRECTORY);
6358 if (parent && parent->variantType ==
6359 YAFFS_OBJECT_TYPE_UNKNOWN) {
6360 /* Set up as a directory */
6361 parent->variantType =
6362 YAFFS_OBJECT_TYPE_DIRECTORY;
6363 YINIT_LIST_HEAD(&parent->variant.
6366 } else if (!parent || parent->variantType !=
6367 YAFFS_OBJECT_TYPE_DIRECTORY) {
6368 /* Hoosterman, another problem....
6369 * We're trying to use a non-directory as a directory
6372 T(YAFFS_TRACE_ERROR,
6374 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6376 parent = dev->lostNFoundDir;
6379 yaffs_AddObjectToDirectory(parent, in);
6381 if (0 && (parent == dev->deletedDir ||
6382 parent == dev->unlinkedDir)) {
6383 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6384 dev->nDeletedFiles++;
6386 /* Note re hardlinks.
6387 * Since we might scan a hardlink before its equivalent object is scanned
6388 * we put them all in a list.
6389 * After scanning is complete, we should have all the objects, so we run through this
6390 * list and fix up all the chains.
6393 switch (in->variantType) {
6394 case YAFFS_OBJECT_TYPE_UNKNOWN:
6395 /* Todo got a problem */
6397 case YAFFS_OBJECT_TYPE_FILE:
6398 if (dev->param.useHeaderFileSize)
6400 in->variant.fileVariant.
6405 case YAFFS_OBJECT_TYPE_HARDLINK:
6406 in->variant.hardLinkVariant.
6407 equivalentObjectId =
6408 oh->equivalentObjectId;
6409 in->hardLinks.next =
6410 (struct ylist_head *)
6414 case YAFFS_OBJECT_TYPE_DIRECTORY:
6417 case YAFFS_OBJECT_TYPE_SPECIAL:
6420 case YAFFS_OBJECT_TYPE_SYMLINK:
6421 in->variant.symLinkVariant.alias =
6422 yaffs_CloneString(oh->alias);
6423 if (!in->variant.symLinkVariant.alias)
6432 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6433 /* If we got this far while scanning, then the block is fully allocated.*/
6434 state = YAFFS_BLOCK_STATE_FULL;
6437 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6438 /* If the block was partially allocated then treat it as fully allocated.*/
6439 state = YAFFS_BLOCK_STATE_FULL;
6440 dev->allocationBlock = -1;
6443 bi->blockState = state;
6445 /* Now let's see if it was dirty */
6446 if (bi->pagesInUse == 0 &&
6447 !bi->hasShrinkHeader &&
6448 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6449 yaffs_BlockBecameDirty(dev, blk);
6455 /* Ok, we've done all the scanning.
6456 * Fix up the hard link chains.
6457 * We should now have scanned all the objects, now it's time to add these
6461 yaffs_HardlinkFixup(dev, hardList);
6463 /* Fix up any shadowed objects */
6465 struct yaffs_ShadowFixerStruct *fixer;
6468 while (shadowFixerList) {
6469 fixer = shadowFixerList;
6470 shadowFixerList = fixer->next;
6471 /* Complete the rename transaction by deleting the shadowed object
6472 * then setting the object header to unshadowed.
6474 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6476 yaffs_DeleteObject(obj);
6478 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6481 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6487 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6492 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6498 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6501 yaffs_ObjectHeader *oh;
6503 yaffs_ExtendedTags tags;
6505 int alloc_failed = 0;
6513 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6515 in->lazyLoaded ? "not yet" : "already"));
6518 if (in->lazyLoaded && in->hdrChunk > 0) {
6520 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6522 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6523 oh = (yaffs_ObjectHeader *) chunkData;
6525 in->yst_mode = oh->yst_mode;
6526 #ifdef CONFIG_YAFFS_WINCE
6527 in->win_atime[0] = oh->win_atime[0];
6528 in->win_ctime[0] = oh->win_ctime[0];
6529 in->win_mtime[0] = oh->win_mtime[0];
6530 in->win_atime[1] = oh->win_atime[1];
6531 in->win_ctime[1] = oh->win_ctime[1];
6532 in->win_mtime[1] = oh->win_mtime[1];
6534 in->yst_uid = oh->yst_uid;
6535 in->yst_gid = oh->yst_gid;
6536 in->yst_atime = oh->yst_atime;
6537 in->yst_mtime = oh->yst_mtime;
6538 in->yst_ctime = oh->yst_ctime;
6539 in->yst_rdev = oh->yst_rdev;
6542 yaffs_SetObjectName(in, oh->name);
6544 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6545 in->variant.symLinkVariant.alias =
6546 yaffs_CloneString(oh->alias);
6547 if (!in->variant.symLinkVariant.alias)
6548 alloc_failed = 1; /* Not returned to caller */
6551 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6555 static int yaffs_ScanBackwards(yaffs_Device *dev)
6557 yaffs_ExtendedTags tags;
6562 int nBlocksToScan = 0;
6568 yaffs_BlockState state;
6569 yaffs_Object *hardList = NULL;
6570 yaffs_BlockInfo *bi;
6571 __u32 sequenceNumber;
6572 yaffs_ObjectHeader *oh;
6574 yaffs_Object *parent;
6575 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6581 int foundChunksInBlock;
6582 int equivalentObjectId;
6583 int alloc_failed = 0;
6586 yaffs_BlockIndex *blockIndex = NULL;
6587 int altBlockIndex = 0;
6589 if (!dev->param.isYaffs2) {
6591 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6597 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6598 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6601 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6603 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6606 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6612 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6616 dev->blocksInCheckpoint = 0;
6618 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6620 /* Scan all the blocks to determine their state */
6621 bi = dev->blockInfo;
6622 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6623 yaffs_ClearChunkBits(dev, blk);
6625 bi->softDeletions = 0;
6627 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6629 bi->blockState = state;
6630 bi->sequenceNumber = sequenceNumber;
6632 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6633 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6634 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6635 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6637 T(YAFFS_TRACE_SCAN_DEBUG,
6638 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6639 state, sequenceNumber));
6642 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6643 dev->blocksInCheckpoint++;
6645 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6646 T(YAFFS_TRACE_BAD_BLOCKS,
6647 (TSTR("block %d is bad" TENDSTR), blk));
6648 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6649 T(YAFFS_TRACE_SCAN_DEBUG,
6650 (TSTR("Block empty " TENDSTR)));
6651 dev->nErasedBlocks++;
6652 dev->nFreeChunks += dev->param.nChunksPerBlock;
6653 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6655 /* Determine the highest sequence number */
6656 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6657 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6659 blockIndex[nBlocksToScan].seq = sequenceNumber;
6660 blockIndex[nBlocksToScan].block = blk;
6664 if (sequenceNumber >= dev->sequenceNumber)
6665 dev->sequenceNumber = sequenceNumber;
6667 /* TODO: Nasty sequence number! */
6670 ("Block scanning block %d has bad sequence number %d"
6671 TENDSTR), blk, sequenceNumber));
6679 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6685 /* Sort the blocks */
6686 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6688 /* Use qsort now. */
6689 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6693 /* Dungy old bubble sort... */
6695 yaffs_BlockIndex temp;
6699 for (i = 0; i < nBlocksToScan; i++)
6700 for (j = i + 1; j < nBlocksToScan; j++)
6701 if (blockIndex[i].seq > blockIndex[j].seq) {
6702 temp = blockIndex[j];
6703 blockIndex[j] = blockIndex[i];
6704 blockIndex[i] = temp;
6711 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6713 /* Now scan the blocks looking at the data. */
6715 endIterator = nBlocksToScan - 1;
6716 T(YAFFS_TRACE_SCAN_DEBUG,
6717 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6719 /* For each block.... backwards */
6720 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6722 /* Cooperative multitasking! This loop can run for so
6723 long that watchdog timers expire. */
6726 /* get the block to scan in the correct order */
6727 blk = blockIndex[blockIterator].block;
6729 bi = yaffs_GetBlockInfo(dev, blk);
6732 state = bi->blockState;
6736 /* For each chunk in each block that needs scanning.... */
6737 foundChunksInBlock = 0;
6738 for (c = dev->param.nChunksPerBlock - 1;
6739 !alloc_failed && c >= 0 &&
6740 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6741 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6742 /* Scan backwards...
6743 * Read the tags and decide what to do
6746 chunk = blk * dev->param.nChunksPerBlock + c;
6748 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6751 /* Let's have a good look at this chunk... */
6753 if (!tags.chunkUsed) {
6754 /* An unassigned chunk in the block.
6755 * If there are used chunks after this one, then
6756 * it is a chunk that was skipped due to failing the erased
6757 * check. Just skip it so that it can be deleted.
6758 * But, more typically, We get here when this is an unallocated
6759 * chunk and his means that either the block is empty or
6760 * this is the one being allocated from
6763 if (foundChunksInBlock) {
6764 /* This is a chunk that was skipped due to failing the erased check */
6765 } else if (c == 0) {
6766 /* We're looking at the first chunk in the block so the block is unused */
6767 state = YAFFS_BLOCK_STATE_EMPTY;
6768 dev->nErasedBlocks++;
6770 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6771 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6772 if (dev->sequenceNumber == bi->sequenceNumber) {
6773 /* this is the block being allocated from */
6777 (" Allocating from %d %d"
6780 state = YAFFS_BLOCK_STATE_ALLOCATING;
6781 dev->allocationBlock = blk;
6782 dev->allocationPage = c;
6783 dev->allocationBlockFinder = blk;
6785 /* This is a partially written block that is not
6786 * the current allocation block.
6790 (TSTR("Partially written block %d detected" TENDSTR),
6798 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6800 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6805 } else if (tags.chunkId > 0) {
6806 /* chunkId > 0 so it is a data chunk... */
6807 unsigned int endpos;
6809 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6811 foundChunksInBlock = 1;
6814 yaffs_SetChunkBit(dev, blk, c);
6817 in = yaffs_FindOrCreateObjectByNumber(dev,
6820 YAFFS_OBJECT_TYPE_FILE);
6827 in->variantType == YAFFS_OBJECT_TYPE_FILE
6828 && chunkBase < in->variant.fileVariant.shrinkSize) {
6829 /* This has not been invalidated by a resize */
6830 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6834 /* File size is calculated by looking at the data chunks if we have not
6835 * seen an object header yet. Stop this practice once we find an object header.
6837 endpos = chunkBase + tags.byteCount;
6839 if (!in->valid && /* have not got an object header yet */
6840 in->variant.fileVariant.scannedFileSize < endpos) {
6841 in->variant.fileVariant.scannedFileSize = endpos;
6842 in->variant.fileVariant.fileSize = endpos;
6846 /* This chunk has been invalidated by a resize, or a past file deletion
6847 * so delete the chunk*/
6848 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6852 /* chunkId == 0, so it is an ObjectHeader.
6853 * Thus, we read in the object header and make the object
6855 foundChunksInBlock = 1;
6857 yaffs_SetChunkBit(dev, blk, c);
6863 if (tags.extraHeaderInfoAvailable) {
6864 in = yaffs_FindOrCreateObjectByNumber(dev,
6866 tags.extraObjectType);
6872 (!in->valid && dev->param.disableLazyLoad) ||
6873 tags.extraShadows ||
6875 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6876 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6878 /* If we don't have valid info then we need to read the chunk
6879 * TODO In future we can probably defer reading the chunk and
6880 * living with invalid data until needed.
6883 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6888 oh = (yaffs_ObjectHeader *) chunkData;
6890 if (dev->param.inbandTags) {
6891 /* Fix up the header if they got corrupted by inband tags */
6892 oh->shadowsObject = oh->inbandShadowsObject;
6893 oh->isShrink = oh->inbandIsShrink;
6897 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6905 /* TODO Hoosterman we have a problem! */
6906 T(YAFFS_TRACE_ERROR,
6908 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6909 TENDSTR), tags.objectId, chunk));
6914 /* We have already filled this one.
6915 * We have a duplicate that will be discarded, but
6916 * we first have to suck out resize info if it is a file.
6919 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6921 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6922 (tags.extraHeaderInfoAvailable &&
6923 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6925 (oh) ? oh->fileSize : tags.
6927 __u32 parentObjectId =
6929 parentObjectId : tags.
6930 extraParentObjectId;
6934 (oh) ? oh->isShrink : tags.
6935 extraIsShrinkHeader;
6937 /* If it is deleted (unlinked at start also means deleted)
6938 * we treat the file size as being zeroed at this point.
6940 if (parentObjectId ==
6941 YAFFS_OBJECTID_DELETED
6942 || parentObjectId ==
6943 YAFFS_OBJECTID_UNLINKED) {
6948 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6949 in->variant.fileVariant.shrinkSize = thisSize;
6952 bi->hasShrinkHeader = 1;
6955 /* Use existing - destroy this one. */
6956 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6960 if (!in->valid && in->variantType !=
6961 (oh ? oh->type : tags.extraObjectType))
6962 T(YAFFS_TRACE_ERROR, (
6963 TSTR("yaffs tragedy: Bad object type, "
6964 TCONT("%d != %d, for object %d at chunk ")
6965 TCONT("%d during scan")
6967 oh->type : tags.extraObjectType,
6968 in->variantType, tags.objectId,
6972 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6974 YAFFS_OBJECTID_LOSTNFOUND)) {
6975 /* We only load some info, don't fiddle with directory structure */
6979 in->variantType = oh->type;
6981 in->yst_mode = oh->yst_mode;
6982 #ifdef CONFIG_YAFFS_WINCE
6983 in->win_atime[0] = oh->win_atime[0];
6984 in->win_ctime[0] = oh->win_ctime[0];
6985 in->win_mtime[0] = oh->win_mtime[0];
6986 in->win_atime[1] = oh->win_atime[1];
6987 in->win_ctime[1] = oh->win_ctime[1];
6988 in->win_mtime[1] = oh->win_mtime[1];
6990 in->yst_uid = oh->yst_uid;
6991 in->yst_gid = oh->yst_gid;
6992 in->yst_atime = oh->yst_atime;
6993 in->yst_mtime = oh->yst_mtime;
6994 in->yst_ctime = oh->yst_ctime;
6995 in->yst_rdev = oh->yst_rdev;
6999 in->variantType = tags.extraObjectType;
7003 in->hdrChunk = chunk;
7005 } else if (!in->valid) {
7006 /* we need to load this info */
7009 in->hdrChunk = chunk;
7012 in->variantType = oh->type;
7014 in->yst_mode = oh->yst_mode;
7015 #ifdef CONFIG_YAFFS_WINCE
7016 in->win_atime[0] = oh->win_atime[0];
7017 in->win_ctime[0] = oh->win_ctime[0];
7018 in->win_mtime[0] = oh->win_mtime[0];
7019 in->win_atime[1] = oh->win_atime[1];
7020 in->win_ctime[1] = oh->win_ctime[1];
7021 in->win_mtime[1] = oh->win_mtime[1];
7023 in->yst_uid = oh->yst_uid;
7024 in->yst_gid = oh->yst_gid;
7025 in->yst_atime = oh->yst_atime;
7026 in->yst_mtime = oh->yst_mtime;
7027 in->yst_ctime = oh->yst_ctime;
7028 in->yst_rdev = oh->yst_rdev;
7031 if (oh->shadowsObject > 0)
7032 yaffs_HandleShadowedObject(dev,
7039 yaffs_SetObjectName(in, oh->name);
7041 yaffs_FindOrCreateObjectByNumber
7042 (dev, oh->parentObjectId,
7043 YAFFS_OBJECT_TYPE_DIRECTORY);
7045 fileSize = oh->fileSize;
7046 isShrink = oh->isShrink;
7047 equivalentObjectId = oh->equivalentObjectId;
7050 in->variantType = tags.extraObjectType;
7052 yaffs_FindOrCreateObjectByNumber
7053 (dev, tags.extraParentObjectId,
7054 YAFFS_OBJECT_TYPE_DIRECTORY);
7055 fileSize = tags.extraFileLength;
7056 isShrink = tags.extraIsShrinkHeader;
7057 equivalentObjectId = tags.extraEquivalentObjectId;
7066 /* directory stuff...
7070 if (parent && parent->variantType ==
7071 YAFFS_OBJECT_TYPE_UNKNOWN) {
7072 /* Set up as a directory */
7073 parent->variantType =
7074 YAFFS_OBJECT_TYPE_DIRECTORY;
7075 YINIT_LIST_HEAD(&parent->variant.
7078 } else if (!parent || parent->variantType !=
7079 YAFFS_OBJECT_TYPE_DIRECTORY) {
7080 /* Hoosterman, another problem....
7081 * We're trying to use a non-directory as a directory
7084 T(YAFFS_TRACE_ERROR,
7086 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
7088 parent = dev->lostNFoundDir;
7091 yaffs_AddObjectToDirectory(parent, in);
7093 itsUnlinked = (parent == dev->deletedDir) ||
7094 (parent == dev->unlinkedDir);
7097 /* Mark the block as having a shrinkHeader */
7098 bi->hasShrinkHeader = 1;
7101 /* Note re hardlinks.
7102 * Since we might scan a hardlink before its equivalent object is scanned
7103 * we put them all in a list.
7104 * After scanning is complete, we should have all the objects, so we run
7105 * through this list and fix up all the chains.
7108 switch (in->variantType) {
7109 case YAFFS_OBJECT_TYPE_UNKNOWN:
7110 /* Todo got a problem */
7112 case YAFFS_OBJECT_TYPE_FILE:
7114 if (in->variant.fileVariant.
7115 scannedFileSize < fileSize) {
7116 /* This covers the case where the file size is greater
7117 * than where the data is
7118 * This will happen if the file is resized to be larger
7119 * than its current data extents.
7121 in->variant.fileVariant.fileSize = fileSize;
7122 in->variant.fileVariant.scannedFileSize = fileSize;
7125 if (in->variant.fileVariant.shrinkSize > fileSize)
7126 in->variant.fileVariant.shrinkSize = fileSize;
7130 case YAFFS_OBJECT_TYPE_HARDLINK:
7132 in->variant.hardLinkVariant.equivalentObjectId =
7134 in->hardLinks.next =
7135 (struct ylist_head *) hardList;
7139 case YAFFS_OBJECT_TYPE_DIRECTORY:
7142 case YAFFS_OBJECT_TYPE_SPECIAL:
7145 case YAFFS_OBJECT_TYPE_SYMLINK:
7147 in->variant.symLinkVariant.alias =
7148 yaffs_CloneString(oh->alias);
7149 if (!in->variant.symLinkVariant.alias)
7159 } /* End of scanning for each chunk */
7161 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
7162 /* If we got this far while scanning, then the block is fully allocated. */
7163 state = YAFFS_BLOCK_STATE_FULL;
7167 bi->blockState = state;
7169 /* Now let's see if it was dirty */
7170 if (bi->pagesInUse == 0 &&
7171 !bi->hasShrinkHeader &&
7172 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
7173 yaffs_BlockBecameDirty(dev, blk);
7178 yaffs_SkipRestOfBlock(dev);
7181 YFREE_ALT(blockIndex);
7185 /* Ok, we've done all the scanning.
7186 * Fix up the hard link chains.
7187 * We should now have scanned all the objects, now it's time to add these
7190 yaffs_HardlinkFixup(dev, hardList);
7193 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
7198 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
7203 /*------------------------------ Directory Functions ----------------------------- */
7205 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
7207 struct ylist_head *lh;
7208 yaffs_Object *listObj;
7213 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
7218 if (yaffs_SkipVerification(obj->myDev))
7222 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7227 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7228 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7232 /* Iterate through the objects in each hash entry */
7234 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7236 listObj = ylist_entry(lh, yaffs_Object, siblings);
7237 yaffs_VerifyObject(listObj);
7244 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7249 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7251 struct ylist_head *lh;
7252 yaffs_Object *listObj;
7259 if (yaffs_SkipFullVerification(directory->myDev))
7262 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7263 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7267 /* Iterate through the objects in each hash entry */
7269 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7271 listObj = ylist_entry(lh, yaffs_Object, siblings);
7272 if (listObj->parent != directory) {
7273 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7276 yaffs_VerifyObjectInDirectory(listObj);
7282 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7283 * link (ie. name) is created or deleted in the directory.
7286 * create dir/a : update dir's mtime/ctime
7287 * rm dir/a: update dir's mtime/ctime
7288 * modify dir/a: don't update dir's mtimme/ctime
7290 * This can be handled immediately or defered. Defering helps reduce the number
7291 * of updates when many files in a directory are changed within a brief period.
7293 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7294 * called periodically.
7297 static void yaffs_UpdateParent(yaffs_Object *obj)
7305 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7306 if(dev->param.deferDirectoryUpdate){
7307 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
7309 if(ylist_empty(link)){
7310 ylist_add(link,&dev->dirtyDirectories);
7311 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7315 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7318 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7320 struct ylist_head *link;
7322 yaffs_DirectoryStructure *dS;
7323 yaffs_ObjectVariant *oV;
7325 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7327 while(!ylist_empty(&dev->dirtyDirectories)){
7328 link = dev->dirtyDirectories.next;
7329 ylist_del_init(link);
7331 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7332 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7333 obj = ylist_entry(oV,yaffs_Object,variant);
7335 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7338 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7342 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7344 yaffs_Device *dev = obj->myDev;
7345 yaffs_Object *parent;
7347 yaffs_VerifyObjectInDirectory(obj);
7348 parent = obj->parent;
7350 yaffs_VerifyDirectory(parent);
7352 if (dev && dev->param.removeObjectCallback)
7353 dev->param.removeObjectCallback(obj);
7356 ylist_del_init(&obj->siblings);
7359 yaffs_VerifyDirectory(parent);
7362 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7366 T(YAFFS_TRACE_ALWAYS,
7368 ("tragedy: Trying to add an object to a null pointer directory"
7373 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7374 T(YAFFS_TRACE_ALWAYS,
7376 ("tragedy: Trying to add an object to a non-directory"
7381 if (obj->siblings.prev == NULL) {
7382 /* Not initialised */
7387 yaffs_VerifyDirectory(directory);
7389 yaffs_RemoveObjectFromDirectory(obj);
7393 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7394 obj->parent = directory;
7396 if (directory == obj->myDev->unlinkedDir
7397 || directory == obj->myDev->deletedDir) {
7399 obj->myDev->nUnlinkedFiles++;
7400 obj->renameAllowed = 0;
7403 yaffs_VerifyDirectory(directory);
7404 yaffs_VerifyObjectInDirectory(obj);
7407 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7412 struct ylist_head *i;
7413 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7421 T(YAFFS_TRACE_ALWAYS,
7423 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7428 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7429 T(YAFFS_TRACE_ALWAYS,
7431 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7435 sum = yaffs_CalcNameSum(name);
7437 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7439 l = ylist_entry(i, yaffs_Object, siblings);
7441 if (l->parent != directory)
7444 yaffs_CheckObjectDetailsLoaded(l);
7446 /* Special case for lost-n-found */
7447 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7448 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7450 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7451 /* LostnFound chunk called Objxxx
7454 yaffs_GetObjectName(l, buffer,
7455 YAFFS_MAX_NAME_LENGTH + 1);
7456 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7467 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7468 int (*fn) (yaffs_Object *))
7470 struct ylist_head *i;
7474 T(YAFFS_TRACE_ALWAYS,
7476 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7481 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7482 T(YAFFS_TRACE_ALWAYS,
7484 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7489 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7491 l = ylist_entry(i, yaffs_Object, siblings);
7502 /* GetEquivalentObject dereferences any hard links to get to the
7506 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7508 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7509 /* We want the object id of the equivalent object, not this one */
7510 obj = obj->variant.hardLinkVariant.equivalentObject;
7511 yaffs_CheckObjectDetailsLoaded(obj);
7516 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7518 memset(name, 0, buffSize * sizeof(YCHAR));
7520 yaffs_CheckObjectDetailsLoaded(obj);
7522 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7523 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7524 } else if (obj->hdrChunk <= 0) {
7526 YCHAR numString[20];
7527 YCHAR *x = &numString[19];
7528 unsigned v = obj->objectId;
7532 *x = '0' + (v % 10);
7535 /* make up a name */
7536 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7537 yaffs_strcat(locName, x);
7538 yaffs_strncpy(name, locName, buffSize - 1);
7541 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7542 else if (obj->shortName[0])
7543 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7547 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7549 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7551 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7553 if (obj->hdrChunk > 0) {
7554 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7555 obj->hdrChunk, buffer,
7558 yaffs_strncpy(name, oh->name, buffSize - 1);
7561 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7564 return yaffs_strnlen(name,buffSize-1);
7567 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7569 /* Dereference any hard linking */
7570 obj = yaffs_GetEquivalentObject(obj);
7572 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7573 return obj->variant.fileVariant.fileSize;
7574 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7575 if(!obj->variant.symLinkVariant.alias)
7577 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7579 /* Only a directory should drop through to here */
7580 return obj->myDev->nDataBytesPerChunk;
7584 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7587 struct ylist_head *i;
7590 count++; /* the object itself */
7592 ylist_for_each(i, &obj->hardLinks)
7593 count++; /* add the hard links; */
7598 int yaffs_GetObjectInode(yaffs_Object *obj)
7600 obj = yaffs_GetEquivalentObject(obj);
7602 return obj->objectId;
7605 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7607 obj = yaffs_GetEquivalentObject(obj);
7609 switch (obj->variantType) {
7610 case YAFFS_OBJECT_TYPE_FILE:
7613 case YAFFS_OBJECT_TYPE_DIRECTORY:
7616 case YAFFS_OBJECT_TYPE_SYMLINK:
7619 case YAFFS_OBJECT_TYPE_HARDLINK:
7622 case YAFFS_OBJECT_TYPE_SPECIAL:
7623 if (S_ISFIFO(obj->yst_mode))
7625 if (S_ISCHR(obj->yst_mode))
7627 if (S_ISBLK(obj->yst_mode))
7629 if (S_ISSOCK(obj->yst_mode))
7637 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7639 obj = yaffs_GetEquivalentObject(obj);
7640 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7641 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7643 return yaffs_CloneString(_Y(""));
7646 #ifndef CONFIG_YAFFS_WINCE
7648 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7650 unsigned int valid = attr->ia_valid;
7652 if (valid & ATTR_MODE)
7653 obj->yst_mode = attr->ia_mode;
7654 if (valid & ATTR_UID)
7655 obj->yst_uid = attr->ia_uid;
7656 if (valid & ATTR_GID)
7657 obj->yst_gid = attr->ia_gid;
7659 if (valid & ATTR_ATIME)
7660 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7661 if (valid & ATTR_CTIME)
7662 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7663 if (valid & ATTR_MTIME)
7664 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7666 if (valid & ATTR_SIZE)
7667 yaffs_ResizeFile(obj, attr->ia_size);
7669 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7674 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7676 unsigned int valid = 0;
7678 attr->ia_mode = obj->yst_mode;
7680 attr->ia_uid = obj->yst_uid;
7682 attr->ia_gid = obj->yst_gid;
7685 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7686 valid |= ATTR_ATIME;
7687 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7688 valid |= ATTR_CTIME;
7689 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7690 valid |= ATTR_MTIME;
7692 attr->ia_size = yaffs_GetFileSize(obj);
7695 attr->ia_valid = valid;
7703 int yaffs_DumpObject(yaffs_Object *obj)
7707 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7709 T(YAFFS_TRACE_ALWAYS,
7711 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7712 " chunk %d type %d size %d\n"
7713 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7714 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7715 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7721 /*---------------------------- Initialisation code -------------------------------------- */
7723 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7726 /* Common functions, gotta have */
7727 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7730 #ifdef CONFIG_YAFFS_YAFFS2
7732 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7733 if (dev->param.writeChunkWithTagsToNAND &&
7734 dev->param.readChunkWithTagsFromNAND &&
7735 !dev->param.writeChunkToNAND &&
7736 !dev->param.readChunkFromNAND &&
7737 dev->param.markNANDBlockBad &&
7738 dev->param.queryNANDBlock)
7742 /* Can use the "spare" style interface for yaffs1 */
7743 if (!dev->param.isYaffs2 &&
7744 !dev->param.writeChunkWithTagsToNAND &&
7745 !dev->param.readChunkWithTagsFromNAND &&
7746 dev->param.writeChunkToNAND &&
7747 dev->param.readChunkFromNAND &&
7748 !dev->param.markNANDBlockBad &&
7749 !dev->param.queryNANDBlock)
7756 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7758 /* Initialise the unlinked, deleted, root and lost and found directories */
7760 dev->lostNFoundDir = dev->rootDir = NULL;
7761 dev->unlinkedDir = dev->deletedDir = NULL;
7764 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7767 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7770 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7771 YAFFS_ROOT_MODE | S_IFDIR);
7772 dev->lostNFoundDir =
7773 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7774 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7776 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7777 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7784 int yaffs_GutsInitialise(yaffs_Device *dev)
7786 int init_failed = 0;
7790 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7792 /* Check stuff that must be set */
7795 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7799 dev->internalStartBlock = dev->param.startBlock;
7800 dev->internalEndBlock = dev->param.endBlock;
7801 dev->blockOffset = 0;
7802 dev->chunkOffset = 0;
7803 dev->nFreeChunks = 0;
7807 if (dev->param.startBlock == 0) {
7808 dev->internalStartBlock = dev->param.startBlock + 1;
7809 dev->internalEndBlock = dev->param.endBlock + 1;
7810 dev->blockOffset = 1;
7811 dev->chunkOffset = dev->param.nChunksPerBlock;
7814 /* Check geometry parameters. */
7816 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7817 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7818 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7819 dev->param.nChunksPerBlock < 2 ||
7820 dev->param.nReservedBlocks < 2 ||
7821 dev->internalStartBlock <= 0 ||
7822 dev->internalEndBlock <= 0 ||
7823 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7824 T(YAFFS_TRACE_ALWAYS,
7826 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7827 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7831 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7832 T(YAFFS_TRACE_ALWAYS,
7833 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7837 /* Sort out space for inband tags, if required */
7838 if (dev->param.inbandTags)
7839 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7841 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7843 /* Got the right mix of functions? */
7844 if (!yaffs_CheckDevFunctions(dev)) {
7845 /* Function missing */
7846 T(YAFFS_TRACE_ALWAYS,
7848 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7853 /* This is really a compilation check. */
7854 if (!yaffs_CheckStructures()) {
7855 T(YAFFS_TRACE_ALWAYS,
7856 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7860 if (dev->isMounted) {
7861 T(YAFFS_TRACE_ALWAYS,
7862 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7866 /* Finished with most checks. One or two more checks happen later on too. */
7870 /* OK now calculate a few things for the device */
7873 * Calculate all the chunk size manipulation numbers:
7875 x = dev->nDataBytesPerChunk;
7876 /* We always use dev->chunkShift and dev->chunkDiv */
7877 dev->chunkShift = Shifts(x);
7878 x >>= dev->chunkShift;
7880 /* We only use chunk mask if chunkDiv is 1 */
7881 dev->chunkMask = (1<<dev->chunkShift) - 1;
7884 * Calculate chunkGroupBits.
7885 * We need to find the next power of 2 > than internalEndBlock
7888 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7892 /* Set up tnode width if wide tnodes are enabled. */
7893 if (!dev->param.wideTnodesDisabled) {
7894 /* bits must be even so that we end up with 32-bit words */
7898 dev->tnodeWidth = 16;
7900 dev->tnodeWidth = bits;
7902 dev->tnodeWidth = 16;
7904 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7906 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7907 * so if the bitwidth of the
7908 * chunk range we're using is greater than 16 we need
7909 * to figure out chunk shift and chunkGroupSize
7912 if (bits <= dev->tnodeWidth)
7913 dev->chunkGroupBits = 0;
7915 dev->chunkGroupBits = bits - dev->tnodeWidth;
7918 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7920 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7921 /* We have a problem because the soft delete won't work if
7922 * the chunk group size > chunks per block.
7923 * This can be remedied by using larger "virtual blocks".
7925 T(YAFFS_TRACE_ALWAYS,
7926 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7931 /* OK, we've finished verifying the device, lets continue with initialisation */
7933 /* More device initialisation */
7935 dev->passiveGCs = 0;
7936 dev->oldestDirtyGCs = 0;
7937 dev->backgroundGCs = 0;
7938 dev->gcBlockFinder = 0;
7939 dev->bufferedBlock = -1;
7940 dev->doingBufferedBlockRewrite = 0;
7941 dev->nDeletedFiles = 0;
7942 dev->nBackgroundDeletions = 0;
7943 dev->nUnlinkedFiles = 0;
7945 dev->eccUnfixed = 0;
7946 dev->tagsEccFixed = 0;
7947 dev->tagsEccUnfixed = 0;
7948 dev->nErasureFailures = 0;
7949 dev->nErasedBlocks = 0;
7951 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7952 YINIT_LIST_HEAD(&dev->dirtyDirectories);
7953 dev->oldestDirtySequence = 0;
7954 dev->oldestDirtyBlock = 0;
7956 /* Initialise temporary buffers and caches. */
7957 if (!yaffs_InitialiseTempBuffers(dev))
7960 dev->srCache = NULL;
7961 dev->gcCleanupList = NULL;
7965 dev->param.nShortOpCaches > 0) {
7968 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7970 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7971 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7973 dev->srCache = YMALLOC(srCacheBytes);
7975 buf = (__u8 *) dev->srCache;
7978 memset(dev->srCache, 0, srCacheBytes);
7980 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7981 dev->srCache[i].object = NULL;
7982 dev->srCache[i].lastUse = 0;
7983 dev->srCache[i].dirty = 0;
7984 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7995 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7996 if (!dev->gcCleanupList)
8000 if (dev->param.isYaffs2)
8001 dev->param.useHeaderFileSize = 1;
8003 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8006 yaffs_InitialiseTnodes(dev);
8007 yaffs_InitialiseObjects(dev);
8009 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8014 /* Now scan the flash. */
8015 if (dev->param.isYaffs2) {
8016 if (yaffs_CheckpointRestore(dev)) {
8017 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
8018 T(YAFFS_TRACE_ALWAYS,
8019 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
8022 /* Clean up the mess caused by an aborted checkpoint load
8023 * and scan backwards.
8025 yaffs_DeinitialiseBlocks(dev);
8026 yaffs_DeinitialiseTnodes(dev);
8027 yaffs_DeinitialiseObjects(dev);
8030 dev->nErasedBlocks = 0;
8031 dev->nFreeChunks = 0;
8032 dev->allocationBlock = -1;
8033 dev->allocationPage = -1;
8034 dev->nDeletedFiles = 0;
8035 dev->nUnlinkedFiles = 0;
8036 dev->nBackgroundDeletions = 0;
8038 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8041 yaffs_InitialiseTnodes(dev);
8042 yaffs_InitialiseObjects(dev);
8044 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8047 if (!init_failed && !yaffs_ScanBackwards(dev))
8050 } else if (!yaffs_Scan(dev))
8053 yaffs_StripDeletedObjects(dev);
8054 yaffs_FixHangingObjects(dev);
8055 if(dev->param.emptyLostAndFound)
8056 yaffs_EmptyLostAndFound(dev);
8060 /* Clean up the mess */
8061 T(YAFFS_TRACE_TRACING,
8062 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
8064 yaffs_Deinitialise(dev);
8068 /* Zero out stats */
8069 dev->nPageReads = 0;
8070 dev->nPageWrites = 0;
8071 dev->nBlockErasures = 0;
8073 dev->nRetriedWrites = 0;
8075 dev->nRetiredBlocks = 0;
8077 yaffs_VerifyFreeChunks(dev);
8078 yaffs_VerifyBlocks(dev);
8080 /* Clean up any aborted checkpoint data */
8081 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
8082 yaffs_InvalidateCheckpoint(dev);
8084 T(YAFFS_TRACE_TRACING,
8085 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
8090 void yaffs_Deinitialise(yaffs_Device *dev)
8092 if (dev->isMounted) {
8095 yaffs_DeinitialiseBlocks(dev);
8096 yaffs_DeinitialiseTnodes(dev);
8097 yaffs_DeinitialiseObjects(dev);
8098 if (dev->param.nShortOpCaches > 0 &&
8101 for (i = 0; i < dev->param.nShortOpCaches; i++) {
8102 if (dev->srCache[i].data)
8103 YFREE(dev->srCache[i].data);
8104 dev->srCache[i].data = NULL;
8107 YFREE(dev->srCache);
8108 dev->srCache = NULL;
8111 YFREE(dev->gcCleanupList);
8113 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
8114 YFREE(dev->tempBuffer[i].buffer);
8118 if (dev->param.deinitialiseNAND)
8119 dev->param.deinitialiseNAND(dev);
8123 static int yaffs_CountFreeChunks(yaffs_Device *dev)
8128 yaffs_BlockInfo *blk;
8130 blk = dev->blockInfo;
8131 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
8132 switch (blk->blockState) {
8133 case YAFFS_BLOCK_STATE_EMPTY:
8134 case YAFFS_BLOCK_STATE_ALLOCATING:
8135 case YAFFS_BLOCK_STATE_COLLECTING:
8136 case YAFFS_BLOCK_STATE_FULL:
8138 (dev->param.nChunksPerBlock - blk->pagesInUse +
8139 blk->softDeletions);
8150 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
8152 /* This is what we report to the outside world */
8155 int nDirtyCacheChunks;
8156 int blocksForCheckpoint;
8160 nFree = dev->nFreeChunks;
8162 nFree = yaffs_CountFreeChunks(dev);
8165 nFree += dev->nDeletedFiles;
8167 /* Now count the number of dirty chunks in the cache and subtract those */
8169 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
8170 if (dev->srCache[i].dirty)
8171 nDirtyCacheChunks++;
8174 nFree -= nDirtyCacheChunks;
8176 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
8178 /* Now we figure out how much to reserve for the checkpoint and report that... */
8179 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
8180 if (blocksForCheckpoint < 0)
8181 blocksForCheckpoint = 0;
8183 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
8192 static int yaffs_freeVerificationFailures;
8194 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
8199 if (yaffs_SkipVerification(dev))
8202 counted = yaffs_CountFreeChunks(dev);
8204 difference = dev->nFreeChunks - counted;
8207 T(YAFFS_TRACE_ALWAYS,
8208 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
8209 dev->nFreeChunks, counted, difference));
8210 yaffs_freeVerificationFailures++;
8214 /*---------------------------------------- YAFFS test code ----------------------*/
8216 #define yaffs_CheckStruct(structure, syze, name) \
8218 if (sizeof(structure) != syze) { \
8219 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
8220 name, syze, (int) sizeof(structure))); \
8221 return YAFFS_FAIL; \
8225 static int yaffs_CheckStructures(void)
8227 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8228 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8229 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8230 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8231 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8233 #ifndef CONFIG_YAFFS_WINCE
8234 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");