2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2007 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 const char *yaffs_guts_c_version =
15 "$Id: yaffs_guts.c,v 1.82 2009-03-09 04:24:17 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
38 #include "yaffs_ecc.h"
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
45 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
47 const yaffs_ExtendedTags *tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
49 const yaffs_ExtendedTags *tags);
51 /* Other local prototypes */
52 static int yaffs_UnlinkObject(yaffs_Object *obj);
53 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
55 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
57 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
59 yaffs_ExtendedTags *tags,
61 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
62 int chunkInNAND, int inScan);
64 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
65 yaffs_ObjectType type);
66 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
68 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
69 int force, int isShrink, int shadows);
70 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
71 static int yaffs_CheckStructures(void);
72 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
73 int chunkOffset, int *limit);
74 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
76 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
79 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
82 static int yaffs_UnlinkWorker(yaffs_Object *obj);
84 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
87 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
88 yaffs_BlockInfo **blockUsedPtr);
90 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
92 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
94 static void yaffs_VerifyDirectory(yaffs_Object *directory);
96 static int yaffs_CheckFileSanity(yaffs_Object *in);
98 #define yaffs_CheckFileSanity(in)
101 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
102 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
104 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
106 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
107 yaffs_ExtendedTags *tags);
109 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
111 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
112 yaffs_FileStructure *fStruct,
116 /* Function to calculate chunk and offset */
118 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
124 chunk = (__u32)(addr >> dev->chunkShift);
126 if (dev->chunkDiv == 1) {
127 /* easy power of 2 case */
128 offset = (__u32)(addr & dev->chunkMask);
130 /* Non power-of-2 case */
134 chunk /= dev->chunkDiv;
136 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
137 offset = (__u32)(addr - chunkBase);
144 /* Function to return the number of shifts for a power of 2 greater than or
145 * equal to the given number
146 * Note we don't try to cater for all possible numbers and this does not have to
147 * be hellishly efficient.
150 static __u32 ShiftsGE(__u32 x)
155 nShifts = extraBits = 0;
170 /* Function to return the number of shifts to get a 1 in bit 0
173 static __u32 Shifts(__u32 x)
193 * Temporary buffer manipulations.
196 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
199 __u8 *buf = (__u8 *)1;
201 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
203 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
204 dev->tempBuffer[i].line = 0; /* not in use */
205 dev->tempBuffer[i].buffer = buf =
206 YMALLOC_DMA(dev->totalBytesPerChunk);
209 return buf ? YAFFS_OK : YAFFS_FAIL;
212 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
217 if (dev->tempInUse > dev->maxTemp)
218 dev->maxTemp = dev->tempInUse;
220 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
221 if (dev->tempBuffer[i].line == 0) {
222 dev->tempBuffer[i].line = lineNo;
223 if ((i + 1) > dev->maxTemp) {
224 dev->maxTemp = i + 1;
225 for (j = 0; j <= i; j++)
226 dev->tempBuffer[j].maxLine =
227 dev->tempBuffer[j].line;
230 return dev->tempBuffer[i].buffer;
234 T(YAFFS_TRACE_BUFFERS,
235 (TSTR("Out of temp buffers at line %d, other held by lines:"),
237 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
238 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
240 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
243 * If we got here then we have to allocate an unmanaged one
247 dev->unmanagedTempAllocations++;
248 return YMALLOC(dev->nDataBytesPerChunk);
252 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
259 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
260 if (dev->tempBuffer[i].buffer == buffer) {
261 dev->tempBuffer[i].line = 0;
267 /* assume it is an unmanaged one. */
268 T(YAFFS_TRACE_BUFFERS,
269 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
272 dev->unmanagedTempDeallocations++;
278 * Determine if we have a managed buffer.
280 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
284 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
285 if (dev->tempBuffer[i].buffer == buffer)
289 for (i = 0; i < dev->nShortOpCaches; i++) {
290 if (dev->srCache[i].data == buffer)
294 if (buffer == dev->checkpointBuffer)
297 T(YAFFS_TRACE_ALWAYS,
298 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
305 * Chunk bitmap manipulations
308 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
310 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
312 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
316 return dev->chunkBits +
317 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
320 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
322 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
323 chunk < 0 || chunk >= dev->nChunksPerBlock) {
325 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
331 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
333 __u8 *blkBits = yaffs_BlockBits(dev, blk);
335 memset(blkBits, 0, dev->chunkBitmapStride);
338 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
340 __u8 *blkBits = yaffs_BlockBits(dev, blk);
342 yaffs_VerifyChunkBitId(dev, blk, chunk);
344 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
347 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
349 __u8 *blkBits = yaffs_BlockBits(dev, blk);
351 yaffs_VerifyChunkBitId(dev, blk, chunk);
353 blkBits[chunk / 8] |= (1 << (chunk & 7));
356 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
358 __u8 *blkBits = yaffs_BlockBits(dev, blk);
359 yaffs_VerifyChunkBitId(dev, blk, chunk);
361 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
364 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
366 __u8 *blkBits = yaffs_BlockBits(dev, blk);
368 for (i = 0; i < dev->chunkBitmapStride; i++) {
376 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
378 __u8 *blkBits = yaffs_BlockBits(dev, blk);
381 for (i = 0; i < dev->chunkBitmapStride; i++) {
398 static int yaffs_SkipVerification(yaffs_Device *dev)
400 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
403 static int yaffs_SkipFullVerification(yaffs_Device *dev)
405 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
408 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
410 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
413 static const char *blockStateName[] = {
426 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
431 if (yaffs_SkipVerification(dev))
434 /* Report illegal runtime states */
435 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
436 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
438 switch (bi->blockState) {
439 case YAFFS_BLOCK_STATE_UNKNOWN:
440 case YAFFS_BLOCK_STATE_SCANNING:
441 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
442 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
443 n, blockStateName[bi->blockState]));
446 /* Check pages in use and soft deletions are legal */
448 actuallyUsed = bi->pagesInUse - bi->softDeletions;
450 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
451 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
452 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
453 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
454 n, bi->pagesInUse, bi->softDeletions));
457 /* Check chunk bitmap legal */
458 inUse = yaffs_CountChunkBits(dev, n);
459 if (inUse != bi->pagesInUse)
460 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
461 n, bi->pagesInUse, inUse));
463 /* Check that the sequence number is valid.
464 * Ten million is legal, but is very unlikely
467 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
468 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
469 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
470 n, bi->sequenceNumber));
473 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
476 yaffs_VerifyBlock(dev, bi, n);
478 /* After collection the block should be in the erased state */
479 /* This will need to change if we do partial gc */
481 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
482 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
483 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
488 static void yaffs_VerifyBlocks(yaffs_Device *dev)
491 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
492 int nIllegalBlockStates = 0;
494 if (yaffs_SkipVerification(dev))
497 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
499 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
500 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
501 yaffs_VerifyBlock(dev, bi, i);
503 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
504 nBlocksPerState[bi->blockState]++;
506 nIllegalBlockStates++;
509 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
510 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
512 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
513 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
514 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
516 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
517 T(YAFFS_TRACE_VERIFY,
518 (TSTR("%s %d blocks"TENDSTR),
519 blockStateName[i], nBlocksPerState[i]));
521 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
522 T(YAFFS_TRACE_VERIFY,
523 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
524 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
526 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
527 T(YAFFS_TRACE_VERIFY,
528 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
529 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
531 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
532 T(YAFFS_TRACE_VERIFY,
533 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
534 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
536 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
541 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
542 * case those tests will not be performed.
544 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
546 if (obj && yaffs_SkipVerification(obj->myDev))
549 if (!(tags && obj && oh)) {
550 T(YAFFS_TRACE_VERIFY,
551 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
552 (__u32)tags, (__u32)obj, (__u32)oh));
556 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
557 oh->type > YAFFS_OBJECT_TYPE_MAX)
558 T(YAFFS_TRACE_VERIFY,
559 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
560 tags->objectId, oh->type));
562 if (tags->objectId != obj->objectId)
563 T(YAFFS_TRACE_VERIFY,
564 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
565 tags->objectId, obj->objectId));
569 * Check that the object's parent ids match if parentCheck requested.
571 * Tests do not apply to the root object.
574 if (parentCheck && tags->objectId > 1 && !obj->parent)
575 T(YAFFS_TRACE_VERIFY,
576 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
577 tags->objectId, oh->parentObjectId));
579 if (parentCheck && obj->parent &&
580 oh->parentObjectId != obj->parent->objectId &&
581 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
582 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
583 T(YAFFS_TRACE_VERIFY,
584 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
585 tags->objectId, oh->parentObjectId, obj->parent->objectId));
587 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
588 T(YAFFS_TRACE_VERIFY,
589 (TSTR("Obj %d header name is NULL"TENDSTR),
592 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
593 T(YAFFS_TRACE_VERIFY,
594 (TSTR("Obj %d header name is 0xFF"TENDSTR),
600 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
601 __u32 level, int chunkOffset)
604 yaffs_Device *dev = obj->myDev;
610 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
611 if (tn->internal[i]) {
612 ok = yaffs_VerifyTnodeWorker(obj,
615 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
618 } else if (level == 0) {
619 yaffs_ExtendedTags tags;
620 __u32 objectId = obj->objectId;
622 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
624 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
625 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
628 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
629 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
630 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
631 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
632 objectId, chunkOffset, theChunk,
633 tags.objectId, tags.chunkId));
646 static void yaffs_VerifyFile(yaffs_Object *obj)
648 int requiredTallness;
654 yaffs_ExtendedTags tags;
661 if (yaffs_SkipVerification(obj->myDev))
665 objectId = obj->objectId;
667 /* Check file size is consistent with tnode depth */
668 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
669 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
670 requiredTallness = 0;
672 x >>= YAFFS_TNODES_INTERNAL_BITS;
676 actualTallness = obj->variant.fileVariant.topLevel;
678 if (requiredTallness > actualTallness)
679 T(YAFFS_TRACE_VERIFY,
680 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
681 obj->objectId, actualTallness, requiredTallness));
684 /* Check that the chunks in the tnode tree are all correct.
685 * We do this by scanning through the tnode tree and
686 * checking the tags for every chunk match.
689 if (yaffs_SkipNANDVerification(dev))
692 for (i = 1; i <= lastChunk; i++) {
693 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
696 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
698 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
699 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
700 if (tags.objectId != objectId || tags.chunkId != i) {
701 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
702 objectId, i, theChunk,
703 tags.objectId, tags.chunkId));
711 static void yaffs_VerifyHardLink(yaffs_Object *obj)
713 if (obj && yaffs_SkipVerification(obj->myDev))
716 /* Verify sane equivalent object */
719 static void yaffs_VerifySymlink(yaffs_Object *obj)
721 if (obj && yaffs_SkipVerification(obj->myDev))
724 /* Verify symlink string */
727 static void yaffs_VerifySpecial(yaffs_Object *obj)
729 if (obj && yaffs_SkipVerification(obj->myDev))
733 static void yaffs_VerifyObject(yaffs_Object *obj)
742 __u32 chunkShouldNotBeDeleted;
748 if (obj->beingCreated)
753 if (yaffs_SkipVerification(dev))
756 /* Check sane object header chunk */
758 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
759 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
761 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
762 chunkIdOk = chunkInRange || obj->hdrChunk == 0;
763 chunkValid = chunkInRange &&
764 yaffs_CheckChunkBit(dev,
765 obj->hdrChunk / dev->nChunksPerBlock,
766 obj->hdrChunk % dev->nChunksPerBlock);
767 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
770 (!chunkIdOk || chunkShouldNotBeDeleted)) {
771 T(YAFFS_TRACE_VERIFY,
772 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
773 obj->objectId, obj->hdrChunk,
774 chunkIdOk ? "" : ",out of range",
775 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
778 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
779 yaffs_ExtendedTags tags;
780 yaffs_ObjectHeader *oh;
781 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
783 oh = (yaffs_ObjectHeader *)buffer;
785 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
788 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
790 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
793 /* Verify it has a parent */
794 if (obj && !obj->fake &&
795 (!obj->parent || obj->parent->myDev != dev)) {
796 T(YAFFS_TRACE_VERIFY,
797 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
798 obj->objectId, obj->parent));
801 /* Verify parent is a directory */
802 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
803 T(YAFFS_TRACE_VERIFY,
804 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
805 obj->objectId, obj->parent->variantType));
808 switch (obj->variantType) {
809 case YAFFS_OBJECT_TYPE_FILE:
810 yaffs_VerifyFile(obj);
812 case YAFFS_OBJECT_TYPE_SYMLINK:
813 yaffs_VerifySymlink(obj);
815 case YAFFS_OBJECT_TYPE_DIRECTORY:
816 yaffs_VerifyDirectory(obj);
818 case YAFFS_OBJECT_TYPE_HARDLINK:
819 yaffs_VerifyHardLink(obj);
821 case YAFFS_OBJECT_TYPE_SPECIAL:
822 yaffs_VerifySpecial(obj);
824 case YAFFS_OBJECT_TYPE_UNKNOWN:
826 T(YAFFS_TRACE_VERIFY,
827 (TSTR("Obj %d has illegaltype %d"TENDSTR),
828 obj->objectId, obj->variantType));
833 static void yaffs_VerifyObjects(yaffs_Device *dev)
837 struct ylist_head *lh;
839 if (yaffs_SkipVerification(dev))
842 /* Iterate through the objects in each hash entry */
844 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
845 ylist_for_each(lh, &dev->objectBucket[i].list) {
847 obj = ylist_entry(lh, yaffs_Object, hashLink);
848 yaffs_VerifyObject(obj);
856 * Simple hash function. Needs to have a reasonable spread
859 static Y_INLINE int yaffs_HashFunction(int n)
862 return n % YAFFS_NOBJECT_BUCKETS;
866 * Access functions to useful fake objects.
867 * Note that root might have a presence in NAND if permissions are set.
870 yaffs_Object *yaffs_Root(yaffs_Device *dev)
875 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
877 return dev->lostNFoundDir;
882 * Erased NAND checking functions
885 int yaffs_CheckFF(__u8 *buffer, int nBytes)
887 /* Horrible, slow implementation */
896 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
899 int retval = YAFFS_OK;
900 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
901 yaffs_ExtendedTags tags;
904 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
906 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
909 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
910 T(YAFFS_TRACE_NANDACCESS,
911 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
915 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
921 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
923 yaffs_ExtendedTags *tags,
930 yaffs_InvalidateCheckpoint(dev);
933 yaffs_BlockInfo *bi = 0;
936 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
942 /* First check this chunk is erased, if it needs
943 * checking. The checking policy (unless forced
944 * always on) is as follows:
946 * Check the first page we try to write in a block.
947 * If the check passes then we don't need to check any
948 * more. If the check fails, we check again...
949 * If the block has been erased, we don't need to check.
951 * However, if the block has been prioritised for gc,
952 * then we think there might be something odd about
953 * this block and stop using it.
955 * Rationale: We should only ever see chunks that have
956 * not been erased if there was a partially written
957 * chunk due to power loss. This checking policy should
958 * catch that case with very few checks and thus save a
959 * lot of checks that are most likely not needed.
961 if (bi->gcPrioritise) {
962 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
963 /* try another chunk */
967 /* let's give it a try */
970 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
971 bi->skipErasedCheck = 0;
973 if (!bi->skipErasedCheck) {
974 erasedOk = yaffs_CheckChunkErased(dev, chunk);
975 if (erasedOk != YAFFS_OK) {
977 (TSTR("**>> yaffs chunk %d was not erased"
980 /* try another chunk */
983 bi->skipErasedCheck = 1;
986 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
988 if (writeOk != YAFFS_OK) {
989 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
990 /* try another chunk */
994 /* Copy the data into the robustification buffer */
995 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
997 } while (writeOk != YAFFS_OK &&
998 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1004 T(YAFFS_TRACE_ERROR,
1005 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1008 dev->nRetriedWrites += (attempts - 1);
1015 * Block retiring for handling a broken block.
1018 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1020 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1022 yaffs_InvalidateCheckpoint(dev);
1024 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1025 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1026 T(YAFFS_TRACE_ALWAYS, (TSTR(
1027 "yaffs: Failed to mark bad and erase block %d"
1028 TENDSTR), blockInNAND));
1030 yaffs_ExtendedTags tags;
1031 int chunkId = blockInNAND * dev->nChunksPerBlock;
1033 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1035 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1036 yaffs_InitialiseTags(&tags);
1037 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1038 if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1039 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1040 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1041 TCONT("write bad block marker to block %d")
1042 TENDSTR), blockInNAND));
1044 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1048 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1049 bi->gcPrioritise = 0;
1050 bi->needsRetiring = 0;
1052 dev->nRetiredBlocks++;
1056 * Functions for robustisizing TODO
1060 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1062 const yaffs_ExtendedTags *tags)
1066 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1067 const yaffs_ExtendedTags *tags)
1071 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1073 if (!bi->gcPrioritise) {
1074 bi->gcPrioritise = 1;
1075 dev->hasPendingPrioritisedGCs = 1;
1076 bi->chunkErrorStrikes++;
1078 if (bi->chunkErrorStrikes > 3) {
1079 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1080 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1086 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1089 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1090 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1092 yaffs_HandleChunkError(dev, bi);
1095 /* Was an actual write failure, so mark the block for retirement */
1096 bi->needsRetiring = 1;
1097 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1098 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1101 /* Delete the chunk */
1102 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1106 /*---------------- Name handling functions ------------*/
1108 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1113 const YUCHAR *bname = (const YUCHAR *) name;
1115 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1117 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1118 sum += yaffs_toupper(*bname) * i;
1120 sum += (*bname) * i;
1129 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1131 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1132 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1133 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
1134 yaffs_strcpy(obj->shortName, name);
1136 obj->shortName[0] = _Y('\0');
1138 obj->sum = yaffs_CalcNameSum(name);
1141 /*-------------------- TNODES -------------------
1143 * List of spare tnodes
1144 * The list is hooked together using the first pointer
1148 /* yaffs_CreateTnodes creates a bunch more tnodes and
1149 * adds them to the tnode free list.
1150 * Don't use this function directly
1153 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1157 yaffs_Tnode *newTnodes;
1161 yaffs_TnodeList *tnl;
1166 /* Calculate the tnode size in bytes for variable width tnode support.
1167 * Must be a multiple of 32-bits */
1168 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1170 if (tnodeSize < sizeof(yaffs_Tnode))
1171 tnodeSize = sizeof(yaffs_Tnode);
1173 /* make these things */
1175 newTnodes = YMALLOC(nTnodes * tnodeSize);
1176 mem = (__u8 *)newTnodes;
1179 T(YAFFS_TRACE_ERROR,
1180 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1184 /* Hook them into the free list */
1186 for (i = 0; i < nTnodes - 1; i++) {
1187 newTnodes[i].internal[0] = &newTnodes[i + 1];
1188 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1189 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1193 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1194 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1195 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1197 dev->freeTnodes = newTnodes;
1199 /* New hookup for wide tnodes */
1200 for (i = 0; i < nTnodes - 1; i++) {
1201 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1202 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1203 curr->internal[0] = next;
1206 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1207 curr->internal[0] = dev->freeTnodes;
1208 dev->freeTnodes = (yaffs_Tnode *)mem;
1213 dev->nFreeTnodes += nTnodes;
1214 dev->nTnodesCreated += nTnodes;
1216 /* Now add this bunch of tnodes to a list for freeing up.
1217 * NB If we can't add this to the management list it isn't fatal
1218 * but it just means we can't free this bunch of tnodes later.
1221 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1223 T(YAFFS_TRACE_ERROR,
1225 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1228 tnl->tnodes = newTnodes;
1229 tnl->next = dev->allocatedTnodeList;
1230 dev->allocatedTnodeList = tnl;
1233 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1238 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1240 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1242 yaffs_Tnode *tn = NULL;
1244 /* If there are none left make more */
1245 if (!dev->freeTnodes)
1246 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1248 if (dev->freeTnodes) {
1249 tn = dev->freeTnodes;
1250 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1251 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1252 /* Hoosterman, this thing looks like it isn't in the list */
1253 T(YAFFS_TRACE_ALWAYS,
1254 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1257 dev->freeTnodes = dev->freeTnodes->internal[0];
1261 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1266 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1268 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1269 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1271 if (tnodeSize < sizeof(yaffs_Tnode))
1272 tnodeSize = sizeof(yaffs_Tnode);
1275 memset(tn, 0, tnodeSize);
1280 /* FreeTnode frees up a tnode and puts it back on the free list */
1281 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1284 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1285 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1286 /* Hoosterman, this thing looks like it is already in the list */
1287 T(YAFFS_TRACE_ALWAYS,
1288 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1290 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1292 tn->internal[0] = dev->freeTnodes;
1293 dev->freeTnodes = tn;
1296 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1299 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1301 /* Free the list of allocated tnodes */
1302 yaffs_TnodeList *tmp;
1304 while (dev->allocatedTnodeList) {
1305 tmp = dev->allocatedTnodeList->next;
1307 YFREE(dev->allocatedTnodeList->tnodes);
1308 YFREE(dev->allocatedTnodeList);
1309 dev->allocatedTnodeList = tmp;
1313 dev->freeTnodes = NULL;
1314 dev->nFreeTnodes = 0;
1317 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1319 dev->allocatedTnodeList = NULL;
1320 dev->freeTnodes = NULL;
1321 dev->nFreeTnodes = 0;
1322 dev->nTnodesCreated = 0;
1326 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1329 __u32 *map = (__u32 *)tn;
1335 pos &= YAFFS_TNODES_LEVEL0_MASK;
1336 val >>= dev->chunkGroupBits;
1338 bitInMap = pos * dev->tnodeWidth;
1339 wordInMap = bitInMap / 32;
1340 bitInWord = bitInMap & (32 - 1);
1342 mask = dev->tnodeMask << bitInWord;
1344 map[wordInMap] &= ~mask;
1345 map[wordInMap] |= (mask & (val << bitInWord));
1347 if (dev->tnodeWidth > (32 - bitInWord)) {
1348 bitInWord = (32 - bitInWord);
1350 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1351 map[wordInMap] &= ~mask;
1352 map[wordInMap] |= (mask & (val >> bitInWord));
1356 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1359 __u32 *map = (__u32 *)tn;
1365 pos &= YAFFS_TNODES_LEVEL0_MASK;
1367 bitInMap = pos * dev->tnodeWidth;
1368 wordInMap = bitInMap / 32;
1369 bitInWord = bitInMap & (32 - 1);
1371 val = map[wordInMap] >> bitInWord;
1373 if (dev->tnodeWidth > (32 - bitInWord)) {
1374 bitInWord = (32 - bitInWord);
1376 val |= (map[wordInMap] << bitInWord);
1379 val &= dev->tnodeMask;
1380 val <<= dev->chunkGroupBits;
1385 /* ------------------- End of individual tnode manipulation -----------------*/
1387 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1388 * The look up tree is represented by the top tnode and the number of topLevel
1389 * in the tree. 0 means only the level 0 tnode is in the tree.
1392 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1393 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1394 yaffs_FileStructure *fStruct,
1397 yaffs_Tnode *tn = fStruct->top;
1399 int requiredTallness;
1400 int level = fStruct->topLevel;
1402 /* Check sane level and chunk Id */
1403 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1406 if (chunkId > YAFFS_MAX_CHUNK_ID)
1409 /* First check we're tall enough (ie enough topLevel) */
1411 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1412 requiredTallness = 0;
1414 i >>= YAFFS_TNODES_INTERNAL_BITS;
1418 if (requiredTallness > fStruct->topLevel)
1419 return NULL; /* Not tall enough, so we can't find it */
1421 /* Traverse down to level 0 */
1422 while (level > 0 && tn) {
1423 tn = tn->internal[(chunkId >>
1424 (YAFFS_TNODES_LEVEL0_BITS +
1426 YAFFS_TNODES_INTERNAL_BITS)) &
1427 YAFFS_TNODES_INTERNAL_MASK];
1434 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1435 * This happens in two steps:
1436 * 1. If the tree isn't tall enough, then make it taller.
1437 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1439 * Used when modifying the tree.
1441 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1442 * be plugged into the ttree.
1445 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1446 yaffs_FileStructure *fStruct,
1448 yaffs_Tnode *passedTn)
1450 int requiredTallness;
1458 /* Check sane level and page Id */
1459 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1462 if (chunkId > YAFFS_MAX_CHUNK_ID)
1465 /* First check we're tall enough (ie enough topLevel) */
1467 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1468 requiredTallness = 0;
1470 x >>= YAFFS_TNODES_INTERNAL_BITS;
1475 if (requiredTallness > fStruct->topLevel) {
1476 /* Not tall enough, gotta make the tree taller */
1477 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1479 tn = yaffs_GetTnode(dev);
1482 tn->internal[0] = fStruct->top;
1485 T(YAFFS_TRACE_ERROR,
1486 (TSTR("yaffs: no more tnodes" TENDSTR)));
1490 fStruct->topLevel = requiredTallness;
1493 /* Traverse down to level 0, adding anything we need */
1495 l = fStruct->topLevel;
1499 while (l > 0 && tn) {
1501 (YAFFS_TNODES_LEVEL0_BITS +
1502 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1503 YAFFS_TNODES_INTERNAL_MASK;
1506 if ((l > 1) && !tn->internal[x]) {
1507 /* Add missing non-level-zero tnode */
1508 tn->internal[x] = yaffs_GetTnode(dev);
1510 } else if (l == 1) {
1511 /* Looking from level 1 at level 0 */
1513 /* If we already have one, then release it.*/
1514 if (tn->internal[x])
1515 yaffs_FreeTnode(dev, tn->internal[x]);
1516 tn->internal[x] = passedTn;
1518 } else if (!tn->internal[x]) {
1519 /* Don't have one, none passed in */
1520 tn->internal[x] = yaffs_GetTnode(dev);
1524 tn = tn->internal[x];
1528 /* top is level 0 */
1530 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1531 yaffs_FreeTnode(dev, passedTn);
1538 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1539 yaffs_ExtendedTags *tags, int objectId,
1544 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1545 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1546 theChunk % dev->nChunksPerBlock)) {
1547 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1549 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1560 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1561 * chunks and tnodes in the file
1562 * Returns 1 if the tree was deleted.
1563 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1566 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1567 int chunkOffset, int *limit)
1572 yaffs_ExtendedTags tags;
1574 yaffs_Device *dev = in->myDev;
1580 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1582 if (tn->internal[i]) {
1583 if (limit && (*limit) < 0) {
1587 yaffs_DeleteWorker(in,
1595 YAFFS_TNODES_INTERNAL_BITS)
1600 yaffs_FreeTnode(dev,
1603 tn->internal[i] = NULL;
1607 return (allDone) ? 1 : 0;
1608 } else if (level == 0) {
1611 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1613 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1616 chunkInInode = (chunkOffset <<
1617 YAFFS_TNODES_LEVEL0_BITS) + i;
1620 yaffs_FindChunkInGroup(dev,
1626 if (foundChunk > 0) {
1627 yaffs_DeleteChunk(dev,
1632 *limit = *limit - 1;
1639 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1643 return (i < 0) ? 1 : 0;
1653 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1655 yaffs_BlockInfo *theBlock;
1657 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1659 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1661 theBlock->softDeletions++;
1666 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1667 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1669 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1672 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1673 __u32 level, int chunkOffset)
1678 yaffs_Device *dev = in->myDev;
1683 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1685 if (tn->internal[i]) {
1687 yaffs_SoftDeleteWorker(in,
1693 YAFFS_TNODES_INTERNAL_BITS)
1696 yaffs_FreeTnode(dev,
1699 tn->internal[i] = NULL;
1701 /* Hoosterman... how could this happen? */
1705 return (allDone) ? 1 : 0;
1706 } else if (level == 0) {
1708 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1709 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1711 /* Note this does not find the real chunk, only the chunk group.
1712 * We make an assumption that a chunk group is not larger than
1715 yaffs_SoftDeleteChunk(dev, theChunk);
1716 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1730 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1733 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1734 if (obj->nDataChunks <= 0) {
1735 /* Empty file with no duplicate object headers, just delete it immediately */
1736 yaffs_FreeTnode(obj->myDev,
1737 obj->variant.fileVariant.top);
1738 obj->variant.fileVariant.top = NULL;
1739 T(YAFFS_TRACE_TRACING,
1740 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1742 yaffs_DoGenericObjectDeletion(obj);
1744 yaffs_SoftDeleteWorker(obj,
1745 obj->variant.fileVariant.top,
1746 obj->variant.fileVariant.
1748 obj->softDeleted = 1;
1753 /* Pruning removes any part of the file structure tree that is beyond the
1754 * bounds of the file (ie that does not point to chunks).
1756 * A file should only get pruned when its size is reduced.
1758 * Before pruning, the chunks must be pulled from the tree and the
1759 * level 0 tnode entries must be zeroed out.
1760 * Could also use this for file deletion, but that's probably better handled
1761 * by a special case.
1764 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1765 __u32 level, int del0)
1773 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1774 if (tn->internal[i] && level > 0) {
1776 yaffs_PruneWorker(dev, tn->internal[i],
1778 (i == 0) ? del0 : 1);
1781 if (tn->internal[i])
1785 if (hasData == 0 && del0) {
1786 /* Free and return NULL */
1788 yaffs_FreeTnode(dev, tn);
1798 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1799 yaffs_FileStructure *fStruct)
1806 if (fStruct->topLevel > 0) {
1808 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1810 /* Now we have a tree with all the non-zero branches NULL but the height
1811 * is the same as it was.
1812 * Let's see if we can trim internal tnodes to shorten the tree.
1813 * We can do this if only the 0th element in the tnode is in use
1814 * (ie all the non-zero are NULL)
1817 while (fStruct->topLevel && !done) {
1821 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1822 if (tn->internal[i])
1827 fStruct->top = tn->internal[0];
1828 fStruct->topLevel--;
1829 yaffs_FreeTnode(dev, tn);
1839 /*-------------------- End of File Structure functions.-------------------*/
1841 /* yaffs_CreateFreeObjects creates a bunch more objects and
1842 * adds them to the object free list.
1844 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1847 yaffs_Object *newObjects;
1848 yaffs_ObjectList *list;
1853 /* make these things */
1854 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1855 list = YMALLOC(sizeof(yaffs_ObjectList));
1857 if (!newObjects || !list) {
1862 T(YAFFS_TRACE_ALLOCATE,
1863 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1867 /* Hook them into the free list */
1868 for (i = 0; i < nObjects - 1; i++) {
1869 newObjects[i].siblings.next =
1870 (struct ylist_head *)(&newObjects[i + 1]);
1873 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1874 dev->freeObjects = newObjects;
1875 dev->nFreeObjects += nObjects;
1876 dev->nObjectsCreated += nObjects;
1878 /* Now add this bunch of Objects to a list for freeing up. */
1880 list->objects = newObjects;
1881 list->next = dev->allocatedObjectList;
1882 dev->allocatedObjectList = list;
1888 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1889 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1891 yaffs_Object *tn = NULL;
1893 #ifdef VALGRIND_TEST
1894 tn = YMALLOC(sizeof(yaffs_Object));
1896 /* If there are none left make more */
1897 if (!dev->freeObjects)
1898 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1900 if (dev->freeObjects) {
1901 tn = dev->freeObjects;
1903 (yaffs_Object *) (dev->freeObjects->siblings.next);
1904 dev->nFreeObjects--;
1908 /* Now sweeten it up... */
1910 memset(tn, 0, sizeof(yaffs_Object));
1911 tn->beingCreated = 1;
1915 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1916 YINIT_LIST_HEAD(&(tn->hardLinks));
1917 YINIT_LIST_HEAD(&(tn->hashLink));
1918 YINIT_LIST_HEAD(&tn->siblings);
1921 /* Now make the directory sane */
1923 tn->parent = dev->rootDir;
1924 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1927 /* Add it to the lost and found directory.
1928 * NB Can't put root or lostNFound in lostNFound so
1929 * check if lostNFound exists first
1931 if (dev->lostNFoundDir)
1932 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1934 tn->beingCreated = 0;
1937 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1942 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1947 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1949 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1950 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1951 obj->unlinkAllowed = 0; /* ... or unlink it */
1954 obj->yst_mode = mode;
1956 obj->hdrChunk = 0; /* Not a valid chunk. */
1963 static void yaffs_UnhashObject(yaffs_Object *tn)
1966 yaffs_Device *dev = tn->myDev;
1968 /* If it is still linked into the bucket list, free from the list */
1969 if (!ylist_empty(&tn->hashLink)) {
1970 ylist_del_init(&tn->hashLink);
1971 bucket = yaffs_HashFunction(tn->objectId);
1972 dev->objectBucket[bucket].count--;
1976 /* FreeObject frees up a Object and puts it back on the free list */
1977 static void yaffs_FreeObject(yaffs_Object *tn)
1979 yaffs_Device *dev = tn->myDev;
1982 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
1987 if (!ylist_empty(&tn->siblings))
1993 /* We're still hooked up to a cached inode.
1994 * Don't delete now, but mark for later deletion
1996 tn->deferedFree = 1;
2001 yaffs_UnhashObject(tn);
2003 #ifdef VALGRIND_TEST
2006 /* Link into the free list. */
2007 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2008 dev->freeObjects = tn;
2009 dev->nFreeObjects++;
2011 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2016 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2018 if (obj->deferedFree)
2019 yaffs_FreeObject(obj);
2024 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2026 /* Free the list of allocated Objects */
2028 yaffs_ObjectList *tmp;
2030 while (dev->allocatedObjectList) {
2031 tmp = dev->allocatedObjectList->next;
2032 YFREE(dev->allocatedObjectList->objects);
2033 YFREE(dev->allocatedObjectList);
2035 dev->allocatedObjectList = tmp;
2038 dev->freeObjects = NULL;
2039 dev->nFreeObjects = 0;
2042 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2046 dev->allocatedObjectList = NULL;
2047 dev->freeObjects = NULL;
2048 dev->nFreeObjects = 0;
2050 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2051 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2052 dev->objectBucket[i].count = 0;
2056 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2061 int lowest = 999999;
2063 /* First let's see if we can find one that's empty. */
2065 for (i = 0; i < 10 && lowest > 0; i++) {
2067 x %= YAFFS_NOBJECT_BUCKETS;
2068 if (dev->objectBucket[x].count < lowest) {
2069 lowest = dev->objectBucket[x].count;
2075 /* If we didn't find an empty list, then try
2076 * looking a bit further for a short one
2079 for (i = 0; i < 10 && lowest > 3; i++) {
2081 x %= YAFFS_NOBJECT_BUCKETS;
2082 if (dev->objectBucket[x].count < lowest) {
2083 lowest = dev->objectBucket[x].count;
2092 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2094 int bucket = yaffs_FindNiceObjectBucket(dev);
2096 /* Now find an object value that has not already been taken
2097 * by scanning the list.
2101 struct ylist_head *i;
2103 __u32 n = (__u32) bucket;
2105 /* yaffs_CheckObjectHashSanity(); */
2109 n += YAFFS_NOBJECT_BUCKETS;
2110 if (1 || dev->objectBucket[bucket].count > 0) {
2111 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2112 /* If there is already one in the list */
2113 if (i && ylist_entry(i, yaffs_Object,
2114 hashLink)->objectId == n) {
2124 static void yaffs_HashObject(yaffs_Object *in)
2126 int bucket = yaffs_HashFunction(in->objectId);
2127 yaffs_Device *dev = in->myDev;
2129 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2130 dev->objectBucket[bucket].count++;
2133 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2135 int bucket = yaffs_HashFunction(number);
2136 struct ylist_head *i;
2139 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2140 /* Look if it is in the list */
2142 in = ylist_entry(i, yaffs_Object, hashLink);
2143 if (in->objectId == number) {
2145 /* Don't tell the VFS about this one if it is defered free */
2146 if (in->deferedFree)
2158 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2159 yaffs_ObjectType type)
2161 yaffs_Object *theObject;
2162 yaffs_Tnode *tn = NULL;
2165 number = yaffs_CreateNewObjectNumber(dev);
2167 theObject = yaffs_AllocateEmptyObject(dev);
2171 if (type == YAFFS_OBJECT_TYPE_FILE) {
2172 tn = yaffs_GetTnode(dev);
2174 yaffs_FreeObject(theObject);
2180 theObject->fake = 0;
2181 theObject->renameAllowed = 1;
2182 theObject->unlinkAllowed = 1;
2183 theObject->objectId = number;
2184 yaffs_HashObject(theObject);
2185 theObject->variantType = type;
2186 #ifdef CONFIG_YAFFS_WINCE
2187 yfsd_WinFileTimeNow(theObject->win_atime);
2188 theObject->win_ctime[0] = theObject->win_mtime[0] =
2189 theObject->win_atime[0];
2190 theObject->win_ctime[1] = theObject->win_mtime[1] =
2191 theObject->win_atime[1];
2195 theObject->yst_atime = theObject->yst_mtime =
2196 theObject->yst_ctime = Y_CURRENT_TIME;
2199 case YAFFS_OBJECT_TYPE_FILE:
2200 theObject->variant.fileVariant.fileSize = 0;
2201 theObject->variant.fileVariant.scannedFileSize = 0;
2202 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2203 theObject->variant.fileVariant.topLevel = 0;
2204 theObject->variant.fileVariant.top = tn;
2206 case YAFFS_OBJECT_TYPE_DIRECTORY:
2207 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2210 case YAFFS_OBJECT_TYPE_SYMLINK:
2211 case YAFFS_OBJECT_TYPE_HARDLINK:
2212 case YAFFS_OBJECT_TYPE_SPECIAL:
2213 /* No action required */
2215 case YAFFS_OBJECT_TYPE_UNKNOWN:
2216 /* todo this should not happen */
2224 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2226 yaffs_ObjectType type)
2228 yaffs_Object *theObject = NULL;
2231 theObject = yaffs_FindObjectByNumber(dev, number);
2234 theObject = yaffs_CreateNewObject(dev, number, type);
2241 static YCHAR *yaffs_CloneString(const YCHAR *str)
2243 YCHAR *newStr = NULL;
2246 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2248 yaffs_strcpy(newStr, str);
2256 * Mknod (create) a new object.
2257 * equivalentObject only has meaning for a hard link;
2258 * aliasString only has meaning for a sumlink.
2259 * rdev only has meaning for devices (a subset of special objects)
2262 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2263 yaffs_Object *parent,
2268 yaffs_Object *equivalentObject,
2269 const YCHAR *aliasString, __u32 rdev)
2274 yaffs_Device *dev = parent->myDev;
2276 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2277 if (yaffs_FindObjectByName(parent, name))
2280 in = yaffs_CreateNewObject(dev, -1, type);
2285 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2286 str = yaffs_CloneString(aliasString);
2288 yaffs_FreeObject(in);
2298 in->variantType = type;
2300 in->yst_mode = mode;
2302 #ifdef CONFIG_YAFFS_WINCE
2303 yfsd_WinFileTimeNow(in->win_atime);
2304 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2305 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2308 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2310 in->yst_rdev = rdev;
2314 in->nDataChunks = 0;
2316 yaffs_SetObjectName(in, name);
2319 yaffs_AddObjectToDirectory(parent, in);
2321 in->myDev = parent->myDev;
2324 case YAFFS_OBJECT_TYPE_SYMLINK:
2325 in->variant.symLinkVariant.alias = str;
2327 case YAFFS_OBJECT_TYPE_HARDLINK:
2328 in->variant.hardLinkVariant.equivalentObject =
2330 in->variant.hardLinkVariant.equivalentObjectId =
2331 equivalentObject->objectId;
2332 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2334 case YAFFS_OBJECT_TYPE_FILE:
2335 case YAFFS_OBJECT_TYPE_DIRECTORY:
2336 case YAFFS_OBJECT_TYPE_SPECIAL:
2337 case YAFFS_OBJECT_TYPE_UNKNOWN:
2342 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2343 /* Could not create the object header, fail the creation */
2344 yaffs_DeleteObject(in);
2353 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2354 __u32 mode, __u32 uid, __u32 gid)
2356 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2357 uid, gid, NULL, NULL, 0);
2360 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2361 __u32 mode, __u32 uid, __u32 gid)
2363 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2364 mode, uid, gid, NULL, NULL, 0);
2367 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2368 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2370 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2371 uid, gid, NULL, NULL, rdev);
2374 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2375 __u32 mode, __u32 uid, __u32 gid,
2378 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2379 uid, gid, NULL, alias, 0);
2382 /* yaffs_Link returns the object id of the equivalent object.*/
2383 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2384 yaffs_Object *equivalentObject)
2386 /* Get the real object in case we were fed a hard link as an equivalent object */
2387 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2389 if (yaffs_MknodObject
2390 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2391 equivalentObject, NULL, 0)) {
2392 return equivalentObject;
2399 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2400 const YCHAR *newName, int force, int shadows)
2405 yaffs_Object *existingTarget;
2408 newDir = obj->parent; /* use the old directory */
2410 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2411 T(YAFFS_TRACE_ALWAYS,
2413 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2418 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2419 if (obj->myDev->isYaffs2)
2420 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2422 unlinkOp = (newDir == obj->myDev->unlinkedDir
2423 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2425 deleteOp = (newDir == obj->myDev->deletedDir);
2427 existingTarget = yaffs_FindObjectByName(newDir, newName);
2429 /* If the object is a file going into the unlinked directory,
2430 * then it is OK to just stuff it in since duplicate names are allowed.
2431 * else only proceed if the new name does not exist and if we're putting
2432 * it into a directory.
2439 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2440 yaffs_SetObjectName(obj, newName);
2443 yaffs_AddObjectToDirectory(newDir, obj);
2448 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2449 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2456 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2457 yaffs_Object *newDir, const YCHAR *newName)
2459 yaffs_Object *obj = NULL;
2460 yaffs_Object *existingTarget = NULL;
2464 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2466 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2469 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2470 /* Special case for case insemsitive systems (eg. WinCE).
2471 * While look-up is case insensitive, the name isn't.
2472 * Therefore we might want to change x.txt to X.txt
2474 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2478 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2482 obj = yaffs_FindObjectByName(oldDir, oldName);
2484 if (obj && obj->renameAllowed) {
2486 /* Now do the handling for an existing target, if there is one */
2488 existingTarget = yaffs_FindObjectByName(newDir, newName);
2489 if (existingTarget &&
2490 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2491 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2492 /* There is a target that is a non-empty directory, so we fail */
2493 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2494 } else if (existingTarget && existingTarget != obj) {
2495 /* Nuke the target first, using shadowing,
2496 * but only if it isn't the same object
2498 yaffs_ChangeObjectName(obj, newDir, newName, force,
2499 existingTarget->objectId);
2500 yaffs_UnlinkObject(existingTarget);
2503 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2508 /*------------------------- Block Management and Page Allocation ----------------*/
2510 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2512 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2514 dev->blockInfo = NULL;
2515 dev->chunkBits = NULL;
2517 dev->allocationBlock = -1; /* force it to get a new one */
2519 /* If the first allocation strategy fails, thry the alternate one */
2520 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2521 if (!dev->blockInfo) {
2522 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2523 dev->blockInfoAlt = 1;
2525 dev->blockInfoAlt = 0;
2527 if (dev->blockInfo) {
2528 /* Set up dynamic blockinfo stuff. */
2529 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2530 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2531 if (!dev->chunkBits) {
2532 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2533 dev->chunkBitsAlt = 1;
2535 dev->chunkBitsAlt = 0;
2538 if (dev->blockInfo && dev->chunkBits) {
2539 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2540 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2547 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2549 if (dev->blockInfoAlt && dev->blockInfo)
2550 YFREE_ALT(dev->blockInfo);
2551 else if (dev->blockInfo)
2552 YFREE(dev->blockInfo);
2554 dev->blockInfoAlt = 0;
2556 dev->blockInfo = NULL;
2558 if (dev->chunkBitsAlt && dev->chunkBits)
2559 YFREE_ALT(dev->chunkBits);
2560 else if (dev->chunkBits)
2561 YFREE(dev->chunkBits);
2562 dev->chunkBitsAlt = 0;
2563 dev->chunkBits = NULL;
2566 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2567 yaffs_BlockInfo *bi)
2574 return 1; /* disqualification only applies to yaffs2. */
2576 if (!bi->hasShrinkHeader)
2577 return 1; /* can gc */
2579 /* Find the oldest dirty sequence number if we don't know it and save it
2580 * so we don't have to keep recomputing it.
2582 if (!dev->oldestDirtySequence) {
2583 seq = dev->sequenceNumber;
2585 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2587 b = yaffs_GetBlockInfo(dev, i);
2588 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2589 (b->pagesInUse - b->softDeletions) <
2590 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2591 seq = b->sequenceNumber;
2594 dev->oldestDirtySequence = seq;
2597 /* Can't do gc of this block if there are any blocks older than this one that have
2600 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2603 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2604 * for garbage collection.
2607 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2610 int b = dev->currentDirtyChecker;
2616 int prioritised = 0;
2617 yaffs_BlockInfo *bi;
2618 int pendingPrioritisedExist = 0;
2620 /* First let's see if we need to grab a prioritised block */
2621 if (dev->hasPendingPrioritisedGCs) {
2622 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2624 bi = yaffs_GetBlockInfo(dev, i);
2625 /* yaffs_VerifyBlock(dev,bi,i); */
2627 if (bi->gcPrioritise) {
2628 pendingPrioritisedExist = 1;
2629 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2630 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2631 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2634 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2639 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2640 dev->hasPendingPrioritisedGCs = 0;
2643 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2645 * else (we're doing a leasurely gc), then we only bother to do this if the
2646 * block has only a few pages in use.
2649 dev->nonAggressiveSkip--;
2651 if (!aggressive && (dev->nonAggressiveSkip > 0))
2656 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2660 dev->internalEndBlock - dev->internalStartBlock + 1;
2663 dev->internalEndBlock - dev->internalStartBlock + 1;
2664 iterations = iterations / 16;
2665 if (iterations > 200)
2669 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2671 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2672 b = dev->internalStartBlock;
2674 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2675 T(YAFFS_TRACE_ERROR,
2676 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2680 bi = yaffs_GetBlockInfo(dev, b);
2682 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2683 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2684 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2686 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2690 dev->currentDirtyChecker = b;
2694 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2695 dev->nChunksPerBlock - pagesInUse, prioritised));
2698 dev->oldestDirtySequence = 0;
2701 dev->nonAggressiveSkip = 4;
2706 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2708 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2712 /* If the block is still healthy erase it and mark as clean.
2713 * If the block has had a data failure, then retire it.
2716 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2717 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2718 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2720 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2722 if (!bi->needsRetiring) {
2723 yaffs_InvalidateCheckpoint(dev);
2724 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2726 dev->nErasureFailures++;
2727 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2728 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2733 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2735 for (i = 0; i < dev->nChunksPerBlock; i++) {
2736 if (!yaffs_CheckChunkErased
2737 (dev, blockNo * dev->nChunksPerBlock + i)) {
2738 T(YAFFS_TRACE_ERROR,
2740 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2741 TENDSTR), blockNo, i));
2747 /* Clean it up... */
2748 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2749 dev->nErasedBlocks++;
2751 bi->softDeletions = 0;
2752 bi->hasShrinkHeader = 0;
2753 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2754 bi->gcPrioritise = 0;
2755 yaffs_ClearChunkBits(dev, blockNo);
2757 T(YAFFS_TRACE_ERASE,
2758 (TSTR("Erased block %d" TENDSTR), blockNo));
2760 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2762 yaffs_RetireBlock(dev, blockNo);
2763 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2764 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2768 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2772 yaffs_BlockInfo *bi;
2774 if (dev->nErasedBlocks < 1) {
2775 /* Hoosterman we've got a problem.
2776 * Can't get space to gc
2778 T(YAFFS_TRACE_ERROR,
2779 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2784 /* Find an empty block. */
2786 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2787 dev->allocationBlockFinder++;
2788 if (dev->allocationBlockFinder < dev->internalStartBlock
2789 || dev->allocationBlockFinder > dev->internalEndBlock) {
2790 dev->allocationBlockFinder = dev->internalStartBlock;
2793 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2795 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2796 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2797 dev->sequenceNumber++;
2798 bi->sequenceNumber = dev->sequenceNumber;
2799 dev->nErasedBlocks--;
2800 T(YAFFS_TRACE_ALLOCATE,
2801 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2802 dev->allocationBlockFinder, dev->sequenceNumber,
2803 dev->nErasedBlocks));
2804 return dev->allocationBlockFinder;
2808 T(YAFFS_TRACE_ALWAYS,
2810 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2811 TENDSTR), dev->nErasedBlocks));
2818 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2820 if (!dev->nCheckpointBlocksRequired &&
2822 /* Not a valid value so recalculate */
2825 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2828 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2830 if (tnodeSize < sizeof(yaffs_Tnode))
2831 tnodeSize = sizeof(yaffs_Tnode);
2833 nBytes += sizeof(yaffs_CheckpointValidity);
2834 nBytes += sizeof(yaffs_CheckpointDevice);
2835 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2836 nBytes += devBlocks * dev->chunkBitmapStride;
2837 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2838 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2839 nBytes += sizeof(yaffs_CheckpointValidity);
2840 nBytes += sizeof(__u32); /* checksum*/
2842 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2844 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2846 dev->nCheckpointBlocksRequired = nBlocks;
2849 return dev->nCheckpointBlocksRequired;
2853 * Check if there's space to allocate...
2854 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2856 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2859 int reservedBlocks = dev->nReservedBlocks;
2860 int checkpointBlocks;
2862 if (dev->isYaffs2) {
2863 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2864 dev->blocksInCheckpoint;
2865 if (checkpointBlocks < 0)
2866 checkpointBlocks = 0;
2868 checkpointBlocks = 0;
2871 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2873 return (dev->nFreeChunks > reservedChunks);
2876 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2877 yaffs_BlockInfo **blockUsedPtr)
2880 yaffs_BlockInfo *bi;
2882 if (dev->allocationBlock < 0) {
2883 /* Get next block to allocate off */
2884 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2885 dev->allocationPage = 0;
2888 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2889 /* Not enough space to allocate unless we're allowed to use the reserve. */
2893 if (dev->nErasedBlocks < dev->nReservedBlocks
2894 && dev->allocationPage == 0) {
2895 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2898 /* Next page please.... */
2899 if (dev->allocationBlock >= 0) {
2900 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2902 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2903 dev->allocationPage;
2905 yaffs_SetChunkBit(dev, dev->allocationBlock,
2906 dev->allocationPage);
2908 dev->allocationPage++;
2912 /* If the block is full set the state to full */
2913 if (dev->allocationPage >= dev->nChunksPerBlock) {
2914 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2915 dev->allocationBlock = -1;
2924 T(YAFFS_TRACE_ERROR,
2925 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2930 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2934 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2936 if (dev->allocationBlock > 0)
2937 n += (dev->nChunksPerBlock - dev->allocationPage);
2943 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2949 int retVal = YAFFS_OK;
2952 int isCheckpointBlock;
2956 int chunksBefore = yaffs_GetErasedChunks(dev);
2959 yaffs_ExtendedTags tags;
2961 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2963 yaffs_Object *object;
2965 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2967 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2969 T(YAFFS_TRACE_TRACING,
2970 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2973 bi->hasShrinkHeader,
2976 /*yaffs_VerifyFreeChunks(dev); */
2978 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2980 /* Take off the number of soft deleted entries because
2981 * they're going to get really deleted during GC.
2983 dev->nFreeChunks -= bi->softDeletions;
2987 if (isCheckpointBlock ||
2988 !yaffs_StillSomeChunkBits(dev, block)) {
2989 T(YAFFS_TRACE_TRACING,
2991 ("Collecting block %d that has no chunks in use" TENDSTR),
2993 yaffs_BlockBecameDirty(dev, block);
2996 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2998 yaffs_VerifyBlock(dev, bi, block);
3000 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3001 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3003 for (/* init already done */;
3004 retVal == YAFFS_OK &&
3005 dev->gcChunk < dev->nChunksPerBlock &&
3006 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3008 dev->gcChunk++, oldChunk++) {
3009 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3011 /* This page is in use and might need to be copied off */
3017 yaffs_InitialiseTags(&tags);
3019 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3023 yaffs_FindObjectByNumber(dev,
3026 T(YAFFS_TRACE_GC_DETAIL,
3028 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3029 dev->gcChunk, tags.objectId, tags.chunkId,
3032 if (object && !yaffs_SkipVerification(dev)) {
3033 if (tags.chunkId == 0)
3034 matchingChunk = object->hdrChunk;
3035 else if (object->softDeleted)
3036 matchingChunk = oldChunk; /* Defeat the test */
3038 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3040 if (oldChunk != matchingChunk)
3041 T(YAFFS_TRACE_ERROR,
3042 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3043 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3048 T(YAFFS_TRACE_ERROR,
3050 ("page %d in gc has no object: %d %d %d "
3052 tags.objectId, tags.chunkId, tags.byteCount));
3057 object->softDeleted &&
3058 tags.chunkId != 0) {
3059 /* Data chunk in a soft deleted file, throw it away
3060 * It's a soft deleted data chunk,
3061 * No need to copy this, just forget about it and
3062 * fix up the object.
3065 object->nDataChunks--;
3067 if (object->nDataChunks <= 0) {
3068 /* remeber to clean up the object */
3069 dev->gcCleanupList[cleanups] =
3075 /* Todo object && object->deleted && object->nDataChunks == 0 */
3076 /* Deleted object header with no data chunks.
3077 * Can be discarded and the file deleted.
3079 object->hdrChunk = 0;
3080 yaffs_FreeTnode(object->myDev,
3083 object->variant.fileVariant.top = NULL;
3084 yaffs_DoGenericObjectDeletion(object);
3086 } else if (object) {
3087 /* It's either a data chunk in a live file or
3088 * an ObjectHeader, so we're interested in it.
3089 * NB Need to keep the ObjectHeaders of deleted files
3090 * until the whole file has been deleted off
3092 tags.serialNumber++;
3096 if (tags.chunkId == 0) {
3097 /* It is an object Id,
3098 * We need to nuke the shrinkheader flags first
3099 * We no longer want the shrinkHeader flag since its work is done
3100 * and if it is left in place it will mess up scanning.
3103 yaffs_ObjectHeader *oh;
3104 oh = (yaffs_ObjectHeader *)buffer;
3106 tags.extraIsShrinkHeader = 0;
3108 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3112 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3115 retVal = YAFFS_FAIL;
3118 /* Ok, now fix up the Tnodes etc. */
3120 if (tags.chunkId == 0) {
3122 object->hdrChunk = newChunk;
3123 object->serial = tags.serialNumber;
3125 /* It's a data chunk */
3126 yaffs_PutChunkIntoFile
3134 if (retVal == YAFFS_OK)
3135 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3140 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3143 /* Do any required cleanups */
3144 for (i = 0; i < cleanups; i++) {
3145 /* Time to delete the file too */
3147 yaffs_FindObjectByNumber(dev,
3148 dev->gcCleanupList[i]);
3150 yaffs_FreeTnode(dev,
3151 object->variant.fileVariant.
3153 object->variant.fileVariant.top = NULL;
3156 ("yaffs: About to finally delete object %d"
3157 TENDSTR), object->objectId));
3158 yaffs_DoGenericObjectDeletion(object);
3159 object->myDev->nDeletedFiles--;
3166 yaffs_VerifyCollectedBlock(dev, bi, block);
3168 chunksAfter = yaffs_GetErasedChunks(dev);
3169 if (chunksBefore >= chunksAfter) {
3172 ("gc did not increase free chunks before %d after %d"
3173 TENDSTR), chunksBefore, chunksAfter));
3176 /* If the gc completed then clear the current gcBlock so that we find another. */
3177 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3187 /* New garbage collector
3188 * If we're very low on erased blocks then we do aggressive garbage collection
3189 * otherwise we do "leasurely" garbage collection.
3190 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3191 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3193 * The idea is to help clear out space in a more spread-out manner.
3194 * Dunno if it really does anything useful.
3196 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3200 int gcOk = YAFFS_OK;
3203 int checkpointBlockAdjust;
3205 if (dev->isDoingGC) {
3206 /* Bail out so we don't get recursive gc */
3210 /* This loop should pass the first time.
3211 * We'll only see looping here if the erase of the collected block fails.
3217 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3218 if (checkpointBlockAdjust < 0)
3219 checkpointBlockAdjust = 0;
3221 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3222 /* We need a block soon...*/
3225 /* We're in no hurry */
3229 if (dev->gcBlock <= 0) {
3230 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3234 block = dev->gcBlock;
3237 dev->garbageCollections++;
3239 dev->passiveGarbageCollections++;
3243 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3244 dev->nErasedBlocks, aggressive));
3246 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3249 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3252 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3253 TENDSTR), dev->nErasedBlocks, maxTries, block));
3255 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3259 return aggressive ? gcOk : YAFFS_OK;
3262 /*------------------------- TAGS --------------------------------*/
3264 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3267 return (tags->chunkId == chunkInObject &&
3268 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3273 /*-------------------- Data file manipulation -----------------*/
3275 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3276 yaffs_ExtendedTags *tags)
3278 /*Get the Tnode, then get the level 0 offset chunk offset */
3281 yaffs_ExtendedTags localTags;
3284 yaffs_Device *dev = in->myDev;
3287 /* Passed a NULL, so use our own tags space */
3291 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3294 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3297 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3303 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3304 yaffs_ExtendedTags *tags)
3306 /* Get the Tnode, then get the level 0 offset chunk offset */
3309 yaffs_ExtendedTags localTags;
3311 yaffs_Device *dev = in->myDev;
3315 /* Passed a NULL, so use our own tags space */
3319 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3323 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3326 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3329 /* Delete the entry in the filestructure (if found) */
3331 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, 0);
3337 #ifdef YAFFS_PARANOID
3339 static int yaffs_CheckFileSanity(yaffs_Object *in)
3347 yaffs_Tags localTags;
3348 yaffs_Tags *tags = &localTags;
3352 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3355 objId = in->objectId;
3356 fSize = in->variant.fileVariant.fileSize;
3358 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3360 for (chunk = 1; chunk <= nChunks; chunk++) {
3361 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3366 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3368 if (yaffs_CheckChunkBits
3369 (dev, theChunk / dev->nChunksPerBlock,
3370 theChunk % dev->nChunksPerBlock)) {
3372 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3376 (tags, in->objectId, chunk, chunkDeleted)) {
3386 /* T(("No level 0 found for %d\n", chunk)); */
3390 return failed ? YAFFS_FAIL : YAFFS_OK;
3395 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3396 int chunkInNAND, int inScan)
3398 /* NB inScan is zero unless scanning.
3399 * For forward scanning, inScan is > 0;
3400 * for backward scanning inScan is < 0
3404 yaffs_Device *dev = in->myDev;
3406 yaffs_ExtendedTags existingTags;
3407 yaffs_ExtendedTags newTags;
3408 unsigned existingSerial, newSerial;
3410 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3411 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3412 * If it is not during Scanning then something went wrong!
3415 T(YAFFS_TRACE_ERROR,
3417 ("yaffs tragedy:attempt to put data chunk into a non-file"
3422 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3426 tn = yaffs_AddOrFindLevel0Tnode(dev,
3427 &in->variant.fileVariant,
3433 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3436 /* If we're scanning then we need to test for duplicates
3437 * NB This does not need to be efficient since it should only ever
3438 * happen when the power fails during a write, then only one
3439 * chunk should ever be affected.
3441 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3442 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3445 if (existingChunk > 0) {
3446 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3447 * thus we have to do a FindChunkInFile to get the real chunk id.
3449 * We have a duplicate now we need to decide which one to use:
3451 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3452 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3453 * YAFFS1: Get both sets of tags and compare serial numbers.
3457 /* Only do this for forward scanning */
3458 yaffs_ReadChunkWithTagsFromNAND(dev,
3462 /* Do a proper find */
3464 yaffs_FindChunkInFile(in, chunkInInode,
3468 if (existingChunk <= 0) {
3469 /*Hoosterman - how did this happen? */
3471 T(YAFFS_TRACE_ERROR,
3473 ("yaffs tragedy: existing chunk < 0 in scan"
3478 /* NB The deleted flags should be false, otherwise the chunks will
3479 * not be loaded during a scan
3483 newSerial = newTags.serialNumber;
3484 existingSerial = existingTags.serialNumber;
3488 (in->myDev->isYaffs2 ||
3489 existingChunk <= 0 ||
3490 ((existingSerial + 1) & 3) == newSerial)) {
3491 /* Forward scanning.
3493 * Delete the old one and drop through to update the tnode
3495 yaffs_DeleteChunk(dev, existingChunk, 1,
3498 /* Backward scanning or we want to use the existing one
3500 * Delete the new one and return early so that the tnode isn't changed
3502 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3510 if (existingChunk == 0)
3513 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3518 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3521 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3523 if (chunkInNAND >= 0)
3524 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3527 T(YAFFS_TRACE_NANDACCESS,
3528 (TSTR("Chunk %d not found zero instead" TENDSTR),
3530 /* get sane (zero) data if you read a hole */
3531 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3537 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3541 yaffs_ExtendedTags tags;
3542 yaffs_BlockInfo *bi;
3548 block = chunkId / dev->nChunksPerBlock;
3549 page = chunkId % dev->nChunksPerBlock;
3552 if (!yaffs_CheckChunkBit(dev, block, page))
3553 T(YAFFS_TRACE_VERIFY,
3554 (TSTR("Deleting invalid chunk %d"TENDSTR),
3557 bi = yaffs_GetBlockInfo(dev, block);
3559 T(YAFFS_TRACE_DELETION,
3560 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3563 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3565 yaffs_InitialiseTags(&tags);
3567 tags.chunkDeleted = 1;
3569 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3570 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3572 dev->nUnmarkedDeletions++;
3575 /* Pull out of the management area.
3576 * If the whole block became dirty, this will kick off an erasure.
3578 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3579 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3580 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3581 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3584 yaffs_ClearChunkBit(dev, block, page);
3588 if (bi->pagesInUse == 0 &&
3589 !bi->hasShrinkHeader &&
3590 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3591 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3592 yaffs_BlockBecameDirty(dev, block);
3599 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3600 const __u8 *buffer, int nBytes,
3603 /* Find old chunk Need to do this to get serial number
3604 * Write new one and patch into tree.
3605 * Invalidate old tags.
3609 yaffs_ExtendedTags prevTags;
3612 yaffs_ExtendedTags newTags;
3614 yaffs_Device *dev = in->myDev;
3616 yaffs_CheckGarbageCollection(dev);
3618 /* Get the previous chunk at this location in the file if it exists */
3619 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3621 /* Set up new tags */
3622 yaffs_InitialiseTags(&newTags);
3624 newTags.chunkId = chunkInInode;
3625 newTags.objectId = in->objectId;
3626 newTags.serialNumber =
3627 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3628 newTags.byteCount = nBytes;
3630 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3631 T(YAFFS_TRACE_ERROR,
3632 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3637 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3640 if (newChunkId >= 0) {
3641 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3643 if (prevChunkId >= 0)
3644 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3646 yaffs_CheckFileSanity(in);
3652 /* UpdateObjectHeader updates the header on NAND for an object.
3653 * If name is not NULL, then that new name is used.
3655 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3656 int isShrink, int shadows)
3659 yaffs_BlockInfo *bi;
3661 yaffs_Device *dev = in->myDev;
3668 yaffs_ExtendedTags newTags;
3669 yaffs_ExtendedTags oldTags;
3671 __u8 *buffer = NULL;
3672 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3674 yaffs_ObjectHeader *oh = NULL;
3676 yaffs_strcpy(oldName, _Y("silly old name"));
3680 in == dev->rootDir || /* The rootDir should also be saved */
3683 yaffs_CheckGarbageCollection(dev);
3684 yaffs_CheckObjectDetailsLoaded(in);
3686 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3687 oh = (yaffs_ObjectHeader *) buffer;
3689 prevChunkId = in->hdrChunk;
3691 if (prevChunkId > 0) {
3692 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3695 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3697 memcpy(oldName, oh->name, sizeof(oh->name));
3700 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3702 oh->type = in->variantType;
3703 oh->yst_mode = in->yst_mode;
3704 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3706 #ifdef CONFIG_YAFFS_WINCE
3707 oh->win_atime[0] = in->win_atime[0];
3708 oh->win_ctime[0] = in->win_ctime[0];
3709 oh->win_mtime[0] = in->win_mtime[0];
3710 oh->win_atime[1] = in->win_atime[1];
3711 oh->win_ctime[1] = in->win_ctime[1];
3712 oh->win_mtime[1] = in->win_mtime[1];
3714 oh->yst_uid = in->yst_uid;
3715 oh->yst_gid = in->yst_gid;
3716 oh->yst_atime = in->yst_atime;
3717 oh->yst_mtime = in->yst_mtime;
3718 oh->yst_ctime = in->yst_ctime;
3719 oh->yst_rdev = in->yst_rdev;
3722 oh->parentObjectId = in->parent->objectId;
3724 oh->parentObjectId = 0;
3726 if (name && *name) {
3727 memset(oh->name, 0, sizeof(oh->name));
3728 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3729 } else if (prevChunkId >= 0)
3730 memcpy(oh->name, oldName, sizeof(oh->name));
3732 memset(oh->name, 0, sizeof(oh->name));
3734 oh->isShrink = isShrink;
3736 switch (in->variantType) {
3737 case YAFFS_OBJECT_TYPE_UNKNOWN:
3738 /* Should not happen */
3740 case YAFFS_OBJECT_TYPE_FILE:
3742 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3743 || oh->parentObjectId ==
3744 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3745 fileVariant.fileSize;
3747 case YAFFS_OBJECT_TYPE_HARDLINK:
3748 oh->equivalentObjectId =
3749 in->variant.hardLinkVariant.equivalentObjectId;
3751 case YAFFS_OBJECT_TYPE_SPECIAL:
3754 case YAFFS_OBJECT_TYPE_DIRECTORY:
3757 case YAFFS_OBJECT_TYPE_SYMLINK:
3758 yaffs_strncpy(oh->alias,
3759 in->variant.symLinkVariant.alias,
3760 YAFFS_MAX_ALIAS_LENGTH);
3761 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3766 yaffs_InitialiseTags(&newTags);
3768 newTags.chunkId = 0;
3769 newTags.objectId = in->objectId;
3770 newTags.serialNumber = in->serial;
3772 /* Add extra info for file header */
3774 newTags.extraHeaderInfoAvailable = 1;
3775 newTags.extraParentObjectId = oh->parentObjectId;
3776 newTags.extraFileLength = oh->fileSize;
3777 newTags.extraIsShrinkHeader = oh->isShrink;
3778 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3779 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3780 newTags.extraObjectType = in->variantType;
3782 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3784 /* Create new chunk in NAND */
3786 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3787 (prevChunkId >= 0) ? 1 : 0);
3789 if (newChunkId >= 0) {
3791 in->hdrChunk = newChunkId;
3793 if (prevChunkId >= 0) {
3794 yaffs_DeleteChunk(dev, prevChunkId, 1,
3798 if (!yaffs_ObjectHasCachedWriteData(in))
3801 /* If this was a shrink, then mark the block that the chunk lives on */
3803 bi = yaffs_GetBlockInfo(in->myDev,
3804 newChunkId / in->myDev->nChunksPerBlock);
3805 bi->hasShrinkHeader = 1;
3810 retVal = newChunkId;
3815 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3820 /*------------------------ Short Operations Cache ----------------------------------------
3821 * In many situations where there is no high level buffering (eg WinCE) a lot of
3822 * reads might be short sequential reads, and a lot of writes may be short
3823 * sequential writes. eg. scanning/writing a jpeg file.
3824 * In these cases, a short read/write cache can provide a huge perfomance benefit
3825 * with dumb-as-a-rock code.
3826 * In Linux, the page cache provides read buffering aand the short op cache provides write
3829 * There are a limited number (~10) of cache chunks per device so that we don't
3830 * need a very intelligent search.
3833 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3835 yaffs_Device *dev = obj->myDev;
3837 yaffs_ChunkCache *cache;
3838 int nCaches = obj->myDev->nShortOpCaches;
3840 for (i = 0; i < nCaches; i++) {
3841 cache = &dev->srCache[i];
3842 if (cache->object == obj &&
3851 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3853 yaffs_Device *dev = obj->myDev;
3854 int lowest = -99; /* Stop compiler whining. */
3856 yaffs_ChunkCache *cache;
3857 int chunkWritten = 0;
3858 int nCaches = obj->myDev->nShortOpCaches;
3864 /* Find the dirty cache for this object with the lowest chunk id. */
3865 for (i = 0; i < nCaches; i++) {
3866 if (dev->srCache[i].object == obj &&
3867 dev->srCache[i].dirty) {
3869 || dev->srCache[i].chunkId <
3871 cache = &dev->srCache[i];
3872 lowest = cache->chunkId;
3877 if (cache && !cache->locked) {
3878 /* Write it out and free it up */
3881 yaffs_WriteChunkDataToObject(cache->object,
3887 cache->object = NULL;
3890 } while (cache && chunkWritten > 0);
3893 /* Hoosterman, disk full while writing cache out. */
3894 T(YAFFS_TRACE_ERROR,
3895 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3902 /*yaffs_FlushEntireDeviceCache(dev)
3907 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3910 int nCaches = dev->nShortOpCaches;
3913 /* Find a dirty object in the cache and flush it...
3914 * until there are no further dirty objects.
3918 for (i = 0; i < nCaches && !obj; i++) {
3919 if (dev->srCache[i].object &&
3920 dev->srCache[i].dirty)
3921 obj = dev->srCache[i].object;
3925 yaffs_FlushFilesChunkCache(obj);
3932 /* Grab us a cache chunk for use.
3933 * First look for an empty one.
3934 * Then look for the least recently used non-dirty one.
3935 * Then look for the least recently used dirty one...., flush and look again.
3937 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3941 if (dev->nShortOpCaches > 0) {
3942 for (i = 0; i < dev->nShortOpCaches; i++) {
3943 if (!dev->srCache[i].object)
3944 return &dev->srCache[i];
3951 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3953 yaffs_ChunkCache *cache;
3954 yaffs_Object *theObj;
3959 if (dev->nShortOpCaches > 0) {
3960 /* Try find a non-dirty one... */
3962 cache = yaffs_GrabChunkCacheWorker(dev);
3965 /* They were all dirty, find the last recently used object and flush
3966 * its cache, then find again.
3967 * NB what's here is not very accurate, we actually flush the object
3968 * the last recently used page.
3971 /* With locking we can't assume we can use entry zero */
3978 for (i = 0; i < dev->nShortOpCaches; i++) {
3979 if (dev->srCache[i].object &&
3980 !dev->srCache[i].locked &&
3981 (dev->srCache[i].lastUse < usage || !cache)) {
3982 usage = dev->srCache[i].lastUse;
3983 theObj = dev->srCache[i].object;
3984 cache = &dev->srCache[i];
3989 if (!cache || cache->dirty) {
3990 /* Flush and try again */
3991 yaffs_FlushFilesChunkCache(theObj);
3992 cache = yaffs_GrabChunkCacheWorker(dev);
4002 /* Find a cached chunk */
4003 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4006 yaffs_Device *dev = obj->myDev;
4008 if (dev->nShortOpCaches > 0) {
4009 for (i = 0; i < dev->nShortOpCaches; i++) {
4010 if (dev->srCache[i].object == obj &&
4011 dev->srCache[i].chunkId == chunkId) {
4014 return &dev->srCache[i];
4021 /* Mark the chunk for the least recently used algorithym */
4022 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4026 if (dev->nShortOpCaches > 0) {
4027 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4028 /* Reset the cache usages */
4030 for (i = 1; i < dev->nShortOpCaches; i++)
4031 dev->srCache[i].lastUse = 0;
4038 cache->lastUse = dev->srLastUse;
4045 /* Invalidate a single cache page.
4046 * Do this when a whole page gets written,
4047 * ie the short cache for this page is no longer valid.
4049 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4051 if (object->myDev->nShortOpCaches > 0) {
4052 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4055 cache->object = NULL;
4059 /* Invalidate all the cache pages associated with this object
4060 * Do this whenever ther file is deleted or resized.
4062 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4065 yaffs_Device *dev = in->myDev;
4067 if (dev->nShortOpCaches > 0) {
4068 /* Invalidate it. */
4069 for (i = 0; i < dev->nShortOpCaches; i++) {
4070 if (dev->srCache[i].object == in)
4071 dev->srCache[i].object = NULL;
4076 /*--------------------- Checkpointing --------------------*/
4079 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4081 yaffs_CheckpointValidity cp;
4083 memset(&cp, 0, sizeof(cp));
4085 cp.structType = sizeof(cp);
4086 cp.magic = YAFFS_MAGIC;
4087 cp.version = YAFFS_CHECKPOINT_VERSION;
4088 cp.head = (head) ? 1 : 0;
4090 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4094 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4096 yaffs_CheckpointValidity cp;
4099 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4102 ok = (cp.structType == sizeof(cp)) &&
4103 (cp.magic == YAFFS_MAGIC) &&
4104 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4105 (cp.head == ((head) ? 1 : 0));
4109 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4112 cp->nErasedBlocks = dev->nErasedBlocks;
4113 cp->allocationBlock = dev->allocationBlock;
4114 cp->allocationPage = dev->allocationPage;
4115 cp->nFreeChunks = dev->nFreeChunks;
4117 cp->nDeletedFiles = dev->nDeletedFiles;
4118 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4119 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4120 cp->sequenceNumber = dev->sequenceNumber;
4121 cp->oldestDirtySequence = dev->oldestDirtySequence;
4125 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4126 yaffs_CheckpointDevice *cp)
4128 dev->nErasedBlocks = cp->nErasedBlocks;
4129 dev->allocationBlock = cp->allocationBlock;
4130 dev->allocationPage = cp->allocationPage;
4131 dev->nFreeChunks = cp->nFreeChunks;
4133 dev->nDeletedFiles = cp->nDeletedFiles;
4134 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4135 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4136 dev->sequenceNumber = cp->sequenceNumber;
4137 dev->oldestDirtySequence = cp->oldestDirtySequence;
4141 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4143 yaffs_CheckpointDevice cp;
4145 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4149 /* Write device runtime values*/
4150 yaffs_DeviceToCheckpointDevice(&cp, dev);
4151 cp.structType = sizeof(cp);
4153 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4155 /* Write block info */
4157 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4158 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4161 /* Write chunk bits */
4163 nBytes = nBlocks * dev->chunkBitmapStride;
4164 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4170 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4172 yaffs_CheckpointDevice cp;
4174 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4178 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4182 if (cp.structType != sizeof(cp))
4186 yaffs_CheckpointDeviceToDevice(dev, &cp);
4188 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4190 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4194 nBytes = nBlocks * dev->chunkBitmapStride;
4196 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4201 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4205 cp->objectId = obj->objectId;
4206 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4207 cp->hdrChunk = obj->hdrChunk;
4208 cp->variantType = obj->variantType;
4209 cp->deleted = obj->deleted;
4210 cp->softDeleted = obj->softDeleted;
4211 cp->unlinked = obj->unlinked;
4212 cp->fake = obj->fake;
4213 cp->renameAllowed = obj->renameAllowed;
4214 cp->unlinkAllowed = obj->unlinkAllowed;
4215 cp->serial = obj->serial;
4216 cp->nDataChunks = obj->nDataChunks;
4218 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4219 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4220 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4221 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4224 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4227 yaffs_Object *parent;
4229 if (obj->variantType != cp->variantType) {
4230 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4231 TCONT("chunk %d does not match existing object type %d")
4232 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4237 obj->objectId = cp->objectId;
4240 parent = yaffs_FindOrCreateObjectByNumber(
4243 YAFFS_OBJECT_TYPE_DIRECTORY);
4248 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4249 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4250 TCONT(" chunk %d Parent type, %d, not directory")
4252 cp->objectId, cp->parentId, cp->variantType,
4253 cp->hdrChunk, parent->variantType));
4256 yaffs_AddObjectToDirectory(parent, obj);
4259 obj->hdrChunk = cp->hdrChunk;
4260 obj->variantType = cp->variantType;
4261 obj->deleted = cp->deleted;
4262 obj->softDeleted = cp->softDeleted;
4263 obj->unlinked = cp->unlinked;
4264 obj->fake = cp->fake;
4265 obj->renameAllowed = cp->renameAllowed;
4266 obj->unlinkAllowed = cp->unlinkAllowed;
4267 obj->serial = cp->serial;
4268 obj->nDataChunks = cp->nDataChunks;
4270 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4271 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4272 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4273 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4275 if (obj->hdrChunk > 0)
4276 obj->lazyLoaded = 1;
4282 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4283 __u32 level, int chunkOffset)
4286 yaffs_Device *dev = in->myDev;
4288 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4290 if (tnodeSize < sizeof(yaffs_Tnode))
4291 tnodeSize = sizeof(yaffs_Tnode);
4297 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4298 if (tn->internal[i]) {
4299 ok = yaffs_CheckpointTnodeWorker(in,
4302 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4305 } else if (level == 0) {
4306 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4307 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4309 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4317 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4319 __u32 endMarker = ~0;
4322 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4323 ok = yaffs_CheckpointTnodeWorker(obj,
4324 obj->variant.fileVariant.top,
4325 obj->variant.fileVariant.topLevel,
4328 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4335 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4339 yaffs_Device *dev = obj->myDev;
4340 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4343 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4345 if (tnodeSize < sizeof(yaffs_Tnode))
4346 tnodeSize = sizeof(yaffs_Tnode);
4348 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4350 while (ok && (~baseChunk)) {
4352 /* Read level 0 tnode */
4355 tn = yaffs_GetTnodeRaw(dev);
4357 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4362 ok = yaffs_AddOrFindLevel0Tnode(dev,
4368 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4372 T(YAFFS_TRACE_CHECKPOINT, (
4373 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4374 nread, baseChunk, ok));
4380 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4383 yaffs_CheckpointObject cp;
4386 struct ylist_head *lh;
4389 /* Iterate through the objects in each hash entry,
4390 * dumping them to the checkpointing stream.
4393 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4394 ylist_for_each(lh, &dev->objectBucket[i].list) {
4396 obj = ylist_entry(lh, yaffs_Object, hashLink);
4397 if (!obj->deferedFree) {
4398 yaffs_ObjectToCheckpointObject(&cp, obj);
4399 cp.structType = sizeof(cp);
4401 T(YAFFS_TRACE_CHECKPOINT, (
4402 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4403 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, (unsigned) obj));
4405 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4407 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4408 ok = yaffs_WriteCheckpointTnodes(obj);
4414 /* Dump end of list */
4415 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4416 cp.structType = sizeof(cp);
4419 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4424 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4427 yaffs_CheckpointObject cp;
4430 yaffs_Object *hardList = NULL;
4432 while (ok && !done) {
4433 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4434 if (cp.structType != sizeof(cp)) {
4435 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4436 cp.structType, sizeof(cp), ok));
4440 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4441 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4443 if (ok && cp.objectId == ~0)
4446 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4448 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4451 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4452 ok = yaffs_ReadCheckpointTnodes(obj);
4453 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4454 obj->hardLinks.next =
4455 (struct ylist_head *) hardList;
4464 yaffs_HardlinkFixup(dev, hardList);
4469 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4471 __u32 checkpointSum;
4474 yaffs_GetCheckpointSum(dev, &checkpointSum);
4476 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4484 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4486 __u32 checkpointSum0;
4487 __u32 checkpointSum1;
4490 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4492 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4497 if (checkpointSum0 != checkpointSum1)
4504 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4508 if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4509 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4514 ok = yaffs_CheckpointOpen(dev, 1);
4517 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4518 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4521 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4522 ok = yaffs_WriteCheckpointDevice(dev);
4525 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4526 ok = yaffs_WriteCheckpointObjects(dev);
4529 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4530 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4534 ok = yaffs_WriteCheckpointSum(dev);
4536 if (!yaffs_CheckpointClose(dev))
4540 dev->isCheckpointed = 1;
4542 dev->isCheckpointed = 0;
4544 return dev->isCheckpointed;
4547 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4551 if (dev->skipCheckpointRead || !dev->isYaffs2) {
4552 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4557 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4560 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4561 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4564 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4565 ok = yaffs_ReadCheckpointDevice(dev);
4568 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4569 ok = yaffs_ReadCheckpointObjects(dev);
4572 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4573 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4577 ok = yaffs_ReadCheckpointSum(dev);
4578 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4581 if (!yaffs_CheckpointClose(dev))
4585 dev->isCheckpointed = 1;
4587 dev->isCheckpointed = 0;
4593 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4595 if (dev->isCheckpointed ||
4596 dev->blocksInCheckpoint > 0) {
4597 dev->isCheckpointed = 0;
4598 yaffs_CheckpointInvalidateStream(dev);
4599 if (dev->superBlock && dev->markSuperBlockDirty)
4600 dev->markSuperBlockDirty(dev->superBlock);
4605 int yaffs_CheckpointSave(yaffs_Device *dev)
4608 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4610 yaffs_VerifyObjects(dev);
4611 yaffs_VerifyBlocks(dev);
4612 yaffs_VerifyFreeChunks(dev);
4614 if (!dev->isCheckpointed) {
4615 yaffs_InvalidateCheckpoint(dev);
4616 yaffs_WriteCheckpointData(dev);
4619 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4621 return dev->isCheckpointed;
4624 int yaffs_CheckpointRestore(yaffs_Device *dev)
4627 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4629 retval = yaffs_ReadCheckpointData(dev);
4631 if (dev->isCheckpointed) {
4632 yaffs_VerifyObjects(dev);
4633 yaffs_VerifyBlocks(dev);
4634 yaffs_VerifyFreeChunks(dev);
4637 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4642 /*--------------------- File read/write ------------------------
4643 * Read and write have very similar structures.
4644 * In general the read/write has three parts to it
4645 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4646 * Some complete chunks
4647 * An incomplete chunk to end off with
4649 * Curve-balls: the first chunk might also be the last chunk.
4652 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4661 yaffs_ChunkCache *cache;
4668 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4669 /* start = offset % dev->nDataBytesPerChunk; */
4670 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4673 /* OK now check for the curveball where the start and end are in
4676 if ((start + n) < dev->nDataBytesPerChunk)
4679 nToCopy = dev->nDataBytesPerChunk - start;
4681 cache = yaffs_FindChunkCache(in, chunk);
4683 /* If the chunk is already in the cache or it is less than a whole chunk
4684 * or we're using inband tags then use the cache (if there is caching)
4685 * else bypass the cache.
4687 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4688 if (dev->nShortOpCaches > 0) {
4690 /* If we can't find the data in the cache, then load it up. */
4693 cache = yaffs_GrabChunkCache(in->myDev);
4695 cache->chunkId = chunk;
4698 yaffs_ReadChunkDataFromObject(in, chunk,
4704 yaffs_UseChunkCache(dev, cache, 0);
4709 memcpy(buffer, &cache->data[start], nToCopy);
4713 /* Read into the local buffer then copy..*/
4716 yaffs_GetTempBuffer(dev, __LINE__);
4717 yaffs_ReadChunkDataFromObject(in, chunk,
4720 memcpy(buffer, &localBuffer[start], nToCopy);
4723 yaffs_ReleaseTempBuffer(dev, localBuffer,
4729 /* A full chunk. Read directly into the supplied buffer. */
4730 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4744 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4745 int nBytes, int writeThrough)
4754 int startOfWrite = offset;
4755 int chunkWritten = 0;
4763 while (n > 0 && chunkWritten >= 0) {
4764 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4765 /* start = offset % dev->nDataBytesPerChunk; */
4766 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4768 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4769 start >= dev->nDataBytesPerChunk) {
4770 T(YAFFS_TRACE_ERROR, (
4771 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4773 (int)offset, chunk, start));
4777 /* OK now check for the curveball where the start and end are in
4781 if ((start + n) < dev->nDataBytesPerChunk) {
4784 /* Now folks, to calculate how many bytes to write back....
4785 * If we're overwriting and not writing to then end of file then
4786 * we need to write back as much as was there before.
4789 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4791 if (chunkStart > in->variant.fileVariant.fileSize)
4792 nBytesRead = 0; /* Past end of file */
4794 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4796 if (nBytesRead > dev->nDataBytesPerChunk)
4797 nBytesRead = dev->nDataBytesPerChunk;
4801 (start + n)) ? nBytesRead : (start + n);
4803 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4807 nToCopy = dev->nDataBytesPerChunk - start;
4808 nToWriteBack = dev->nDataBytesPerChunk;
4811 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4812 /* An incomplete start or end chunk (or maybe both start and end chunk),
4813 * or we're using inband tags, so we want to use the cache buffers.
4815 if (dev->nShortOpCaches > 0) {
4816 yaffs_ChunkCache *cache;
4817 /* If we can't find the data in the cache, then load the cache */
4818 cache = yaffs_FindChunkCache(in, chunk);
4821 && yaffs_CheckSpaceForAllocation(in->
4823 cache = yaffs_GrabChunkCache(in->myDev);
4825 cache->chunkId = chunk;
4828 yaffs_ReadChunkDataFromObject(in, chunk,
4833 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4834 /* Drop the cache if it was a read cache item and
4835 * no space check has been made for it.
4841 yaffs_UseChunkCache(dev, cache, 1);
4845 memcpy(&cache->data[start], buffer,
4850 cache->nBytes = nToWriteBack;
4854 yaffs_WriteChunkDataToObject
4857 cache->data, cache->nBytes,
4863 chunkWritten = -1; /* fail the write */
4866 /* An incomplete start or end chunk (or maybe both start and end chunk)
4867 * Read into the local buffer then copy, then copy over and write back.
4871 yaffs_GetTempBuffer(dev, __LINE__);
4873 yaffs_ReadChunkDataFromObject(in, chunk,
4878 memcpy(&localBuffer[start], buffer, nToCopy);
4881 yaffs_WriteChunkDataToObject(in, chunk,
4886 yaffs_ReleaseTempBuffer(dev, localBuffer,
4892 /* A full chunk. Write directly from the supplied buffer. */
4897 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4898 dev->nDataBytesPerChunk,
4901 /* Since we've overwritten the cached data, we better invalidate it. */
4902 yaffs_InvalidateChunkCache(in, chunk);
4905 if (chunkWritten >= 0) {
4914 /* Update file object */
4916 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
4917 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4925 /* ---------------------- File resizing stuff ------------------ */
4927 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4930 yaffs_Device *dev = in->myDev;
4931 int oldFileSize = in->variant.fileVariant.fileSize;
4933 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4935 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4936 dev->nDataBytesPerChunk;
4940 /* Delete backwards so that we don't end up with holes if
4941 * power is lost part-way through the operation.
4943 for (i = lastDel; i >= startDel; i--) {
4944 /* NB this could be optimised somewhat,
4945 * eg. could retrieve the tags and write them without
4946 * using yaffs_DeleteChunk
4949 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4952 (dev->internalStartBlock * dev->nChunksPerBlock)
4954 ((dev->internalEndBlock +
4955 1) * dev->nChunksPerBlock)) {
4956 T(YAFFS_TRACE_ALWAYS,
4957 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4961 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4968 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
4971 int oldFileSize = in->variant.fileVariant.fileSize;
4972 __u32 newSizeOfPartialChunk;
4975 yaffs_Device *dev = in->myDev;
4977 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4979 yaffs_FlushFilesChunkCache(in);
4980 yaffs_InvalidateWholeChunkCache(in);
4982 yaffs_CheckGarbageCollection(dev);
4984 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
4987 if (newSize == oldFileSize)
4990 if (newSize < oldFileSize) {
4992 yaffs_PruneResizedChunks(in, newSize);
4994 if (newSizeOfPartialChunk != 0) {
4995 int lastChunk = 1 + newFullChunks;
4997 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4999 /* Got to read and rewrite the last chunk with its new size and zero pad */
5000 yaffs_ReadChunkDataFromObject(in, lastChunk,
5003 memset(localBuffer + newSizeOfPartialChunk, 0,
5004 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5006 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5007 newSizeOfPartialChunk, 1);
5009 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5012 in->variant.fileVariant.fileSize = newSize;
5014 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5016 /* newsSize > oldFileSize */
5017 in->variant.fileVariant.fileSize = newSize;
5021 /* Write a new object header.
5022 * show we've shrunk the file, if need be
5023 * Do this only if the file is not in the deleted directories.
5026 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5027 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5028 yaffs_UpdateObjectHeader(in, NULL, 0,
5029 (newSize < oldFileSize) ? 1 : 0, 0);
5034 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5036 obj = yaffs_GetEquivalentObject(obj);
5038 switch (obj->variantType) {
5039 case YAFFS_OBJECT_TYPE_FILE:
5040 return obj->variant.fileVariant.fileSize;
5041 case YAFFS_OBJECT_TYPE_SYMLINK:
5042 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5050 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
5054 yaffs_FlushFilesChunkCache(in);
5056 #ifdef CONFIG_YAFFS_WINCE
5057 yfsd_WinFileTimeNow(in->win_mtime);
5060 in->yst_mtime = Y_CURRENT_TIME;
5065 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5066 0) ? YAFFS_OK : YAFFS_FAIL;
5075 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5078 /* First off, invalidate the file's data in the cache, without flushing. */
5079 yaffs_InvalidateWholeChunkCache(in);
5081 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5082 /* Move to the unlinked directory so we have a record that it was deleted. */
5083 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5087 yaffs_RemoveObjectFromDirectory(in);
5088 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5091 yaffs_FreeObject(in);
5096 /* yaffs_DeleteFile deletes the whole file data
5097 * and the inode associated with the file.
5098 * It does not delete the links associated with the file.
5100 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5104 int immediateDeletion = 0;
5108 immediateDeletion = 1;
5111 immediateDeletion = 1;
5114 if (immediateDeletion) {
5116 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5117 _Y("deleted"), 0, 0);
5118 T(YAFFS_TRACE_TRACING,
5119 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5122 in->myDev->nDeletedFiles++;
5123 if (1 || in->myDev->isYaffs2)
5124 yaffs_ResizeFile(in, 0);
5125 yaffs_SoftDeleteFile(in);
5128 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5129 _Y("unlinked"), 0, 0);
5136 int yaffs_DeleteFile(yaffs_Object *in)
5138 int retVal = YAFFS_OK;
5139 int deleted = in->deleted;
5141 yaffs_ResizeFile(in, 0);
5143 if (in->nDataChunks > 0) {
5144 /* Use soft deletion if there is data in the file.
5145 * That won't be the case if it has been resized to zero.
5148 retVal = yaffs_UnlinkFileIfNeeded(in);
5150 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5153 in->myDev->nDeletedFiles++;
5154 yaffs_SoftDeleteFile(in);
5156 return deleted ? YAFFS_OK : YAFFS_FAIL;
5158 /* The file has no data chunks so we toss it immediately */
5159 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5160 in->variant.fileVariant.top = NULL;
5161 yaffs_DoGenericObjectDeletion(in);
5167 static int yaffs_DeleteDirectory(yaffs_Object *in)
5169 /* First check that the directory is empty. */
5170 if (ylist_empty(&in->variant.directoryVariant.children))
5171 return yaffs_DoGenericObjectDeletion(in);
5177 static int yaffs_DeleteSymLink(yaffs_Object *in)
5179 YFREE(in->variant.symLinkVariant.alias);
5181 return yaffs_DoGenericObjectDeletion(in);
5184 static int yaffs_DeleteHardLink(yaffs_Object *in)
5186 /* remove this hardlink from the list assocaited with the equivalent
5189 ylist_del_init(&in->hardLinks);
5190 return yaffs_DoGenericObjectDeletion(in);
5193 int yaffs_DeleteObject(yaffs_Object *obj)
5196 switch (obj->variantType) {
5197 case YAFFS_OBJECT_TYPE_FILE:
5198 retVal = yaffs_DeleteFile(obj);
5200 case YAFFS_OBJECT_TYPE_DIRECTORY:
5201 return yaffs_DeleteDirectory(obj);
5203 case YAFFS_OBJECT_TYPE_SYMLINK:
5204 retVal = yaffs_DeleteSymLink(obj);
5206 case YAFFS_OBJECT_TYPE_HARDLINK:
5207 retVal = yaffs_DeleteHardLink(obj);
5209 case YAFFS_OBJECT_TYPE_SPECIAL:
5210 retVal = yaffs_DoGenericObjectDeletion(obj);
5212 case YAFFS_OBJECT_TYPE_UNKNOWN:
5214 break; /* should not happen. */
5220 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5223 int immediateDeletion = 0;
5227 immediateDeletion = 1;
5229 if (obj->inUse <= 0)
5230 immediateDeletion = 1;
5233 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5234 return yaffs_DeleteHardLink(obj);
5235 } else if (!ylist_empty(&obj->hardLinks)) {
5236 /* Curve ball: We're unlinking an object that has a hardlink.
5238 * This problem arises because we are not strictly following
5239 * The Linux link/inode model.
5241 * We can't really delete the object.
5242 * Instead, we do the following:
5243 * - Select a hardlink.
5244 * - Unhook it from the hard links
5245 * - Unhook it from its parent directory (so that the rename can work)
5246 * - Rename the object to the hardlink's name.
5247 * - Delete the hardlink
5252 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5254 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5256 ylist_del_init(&hl->hardLinks);
5257 ylist_del_init(&hl->siblings);
5259 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5261 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5263 if (retVal == YAFFS_OK)
5264 retVal = yaffs_DoGenericObjectDeletion(hl);
5268 } else if (immediateDeletion) {
5269 switch (obj->variantType) {
5270 case YAFFS_OBJECT_TYPE_FILE:
5271 return yaffs_DeleteFile(obj);
5273 case YAFFS_OBJECT_TYPE_DIRECTORY:
5274 return yaffs_DeleteDirectory(obj);
5276 case YAFFS_OBJECT_TYPE_SYMLINK:
5277 return yaffs_DeleteSymLink(obj);
5279 case YAFFS_OBJECT_TYPE_SPECIAL:
5280 return yaffs_DoGenericObjectDeletion(obj);
5282 case YAFFS_OBJECT_TYPE_HARDLINK:
5283 case YAFFS_OBJECT_TYPE_UNKNOWN:
5288 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5289 _Y("unlinked"), 0, 0);
5293 static int yaffs_UnlinkObject(yaffs_Object *obj)
5296 if (obj && obj->unlinkAllowed)
5297 return yaffs_UnlinkWorker(obj);
5302 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5306 obj = yaffs_FindObjectByName(dir, name);
5307 return yaffs_UnlinkObject(obj);
5310 /*----------------------- Initialisation Scanning ---------------------- */
5312 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5313 int backwardScanning)
5317 if (!backwardScanning) {
5318 /* Handle YAFFS1 forward scanning case
5319 * For YAFFS1 we always do the deletion
5323 /* Handle YAFFS2 case (backward scanning)
5324 * If the shadowed object exists then ignore.
5326 if (yaffs_FindObjectByNumber(dev, objId))
5330 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5331 * We put it in unlinked dir to be cleaned up after the scanning
5334 yaffs_FindOrCreateObjectByNumber(dev, objId,
5335 YAFFS_OBJECT_TYPE_FILE);
5338 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5339 obj->variant.fileVariant.shrinkSize = 0;
5340 obj->valid = 1; /* So that we don't read any other info for this file */
5350 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5357 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5359 in = yaffs_FindObjectByNumber(dev,
5360 hl->variant.hardLinkVariant.
5361 equivalentObjectId);
5364 /* Add the hardlink pointers */
5365 hl->variant.hardLinkVariant.equivalentObject = in;
5366 ylist_add(&hl->hardLinks, &in->hardLinks);
5368 /* Todo Need to report/handle this better.
5369 * Got a problem... hardlink to a non-existant object
5371 hl->variant.hardLinkVariant.equivalentObject = NULL;
5372 YINIT_LIST_HEAD(&hl->hardLinks);
5382 static int ybicmp(const void *a, const void *b)
5384 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5385 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5386 register int ablock = ((yaffs_BlockIndex *)a)->block;
5387 register int bblock = ((yaffs_BlockIndex *)b)->block;
5389 return ablock - bblock;
5395 struct yaffs_ShadowFixerStruct {
5398 struct yaffs_ShadowFixerStruct *next;
5402 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5405 * Sort out state of unlinked and deleted objects after scanning.
5407 struct ylist_head *i;
5408 struct ylist_head *n;
5411 /* Soft delete all the unlinked files */
5412 ylist_for_each_safe(i, n,
5413 &dev->unlinkedDir->variant.directoryVariant.children) {
5415 l = ylist_entry(i, yaffs_Object, siblings);
5416 yaffs_DeleteObject(l);
5420 ylist_for_each_safe(i, n,
5421 &dev->deletedDir->variant.directoryVariant.children) {
5423 l = ylist_entry(i, yaffs_Object, siblings);
5424 yaffs_DeleteObject(l);
5430 static int yaffs_Scan(yaffs_Device *dev)
5432 yaffs_ExtendedTags tags;
5442 yaffs_BlockState state;
5443 yaffs_Object *hardList = NULL;
5444 yaffs_BlockInfo *bi;
5445 __u32 sequenceNumber;
5446 yaffs_ObjectHeader *oh;
5448 yaffs_Object *parent;
5450 int alloc_failed = 0;
5452 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5460 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5461 dev->internalStartBlock, dev->internalEndBlock));
5463 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5465 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5467 /* Scan all the blocks to determine their state */
5468 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5469 bi = yaffs_GetBlockInfo(dev, blk);
5470 yaffs_ClearChunkBits(dev, blk);
5472 bi->softDeletions = 0;
5474 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5476 bi->blockState = state;
5477 bi->sequenceNumber = sequenceNumber;
5479 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5480 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5482 T(YAFFS_TRACE_SCAN_DEBUG,
5483 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5484 state, sequenceNumber));
5486 if (state == YAFFS_BLOCK_STATE_DEAD) {
5487 T(YAFFS_TRACE_BAD_BLOCKS,
5488 (TSTR("block %d is bad" TENDSTR), blk));
5489 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5490 T(YAFFS_TRACE_SCAN_DEBUG,
5491 (TSTR("Block empty " TENDSTR)));
5492 dev->nErasedBlocks++;
5493 dev->nFreeChunks += dev->nChunksPerBlock;
5497 startIterator = dev->internalStartBlock;
5498 endIterator = dev->internalEndBlock;
5500 /* For each block.... */
5501 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5508 blk = blockIterator;
5510 bi = yaffs_GetBlockInfo(dev, blk);
5511 state = bi->blockState;
5515 /* For each chunk in each block that needs scanning....*/
5516 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5517 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5518 /* Read the tags and decide what to do */
5519 chunk = blk * dev->nChunksPerBlock + c;
5521 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5524 /* Let's have a good look at this chunk... */
5526 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5532 /*T((" %d %d deleted\n",blk,c)); */
5533 } else if (!tags.chunkUsed) {
5534 /* An unassigned chunk in the block
5535 * This means that either the block is empty or
5536 * this is the one being allocated from
5540 /* We're looking at the first chunk in the block so the block is unused */
5541 state = YAFFS_BLOCK_STATE_EMPTY;
5542 dev->nErasedBlocks++;
5544 /* this is the block being allocated from */
5547 (" Allocating from %d %d" TENDSTR),
5549 state = YAFFS_BLOCK_STATE_ALLOCATING;
5550 dev->allocationBlock = blk;
5551 dev->allocationPage = c;
5552 dev->allocationBlockFinder = blk;
5553 /* Set it to here to encourage the allocator to go forth from here. */
5557 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5558 } else if (tags.chunkId > 0) {
5559 /* chunkId > 0 so it is a data chunk... */
5560 unsigned int endpos;
5562 yaffs_SetChunkBit(dev, blk, c);
5565 in = yaffs_FindOrCreateObjectByNumber(dev,
5568 YAFFS_OBJECT_TYPE_FILE);
5569 /* PutChunkIntoFile checks for a clash (two data chunks with
5570 * the same chunkId).
5577 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5582 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5585 in->variantType == YAFFS_OBJECT_TYPE_FILE
5586 && in->variant.fileVariant.scannedFileSize <
5588 in->variant.fileVariant.
5589 scannedFileSize = endpos;
5590 if (!dev->useHeaderFileSize) {
5591 in->variant.fileVariant.
5593 in->variant.fileVariant.
5598 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5600 /* chunkId == 0, so it is an ObjectHeader.
5601 * Thus, we read in the object header and make the object
5603 yaffs_SetChunkBit(dev, blk, c);
5606 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5610 oh = (yaffs_ObjectHeader *) chunkData;
5612 in = yaffs_FindObjectByNumber(dev,
5614 if (in && in->variantType != oh->type) {
5615 /* This should not happen, but somehow
5616 * Wev'e ended up with an objectId that has been reused but not yet
5617 * deleted, and worse still it has changed type. Delete the old object.
5620 yaffs_DeleteObject(in);
5625 in = yaffs_FindOrCreateObjectByNumber(dev,
5633 if (in && oh->shadowsObject > 0) {
5635 struct yaffs_ShadowFixerStruct *fixer;
5636 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5638 fixer->next = shadowFixerList;
5639 shadowFixerList = fixer;
5640 fixer->objectId = tags.objectId;
5641 fixer->shadowedId = oh->shadowsObject;
5646 if (in && in->valid) {
5647 /* We have already filled this one. We have a duplicate and need to resolve it. */
5649 unsigned existingSerial = in->serial;
5650 unsigned newSerial = tags.serialNumber;
5652 if (((existingSerial + 1) & 3) == newSerial) {
5653 /* Use new one - destroy the exisiting one */
5654 yaffs_DeleteChunk(dev,
5659 /* Use existing - destroy this one. */
5660 yaffs_DeleteChunk(dev, chunk, 1,
5665 if (in && !in->valid &&
5666 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5667 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5668 /* We only load some info, don't fiddle with directory structure */
5670 in->variantType = oh->type;
5672 in->yst_mode = oh->yst_mode;
5673 #ifdef CONFIG_YAFFS_WINCE
5674 in->win_atime[0] = oh->win_atime[0];
5675 in->win_ctime[0] = oh->win_ctime[0];
5676 in->win_mtime[0] = oh->win_mtime[0];
5677 in->win_atime[1] = oh->win_atime[1];
5678 in->win_ctime[1] = oh->win_ctime[1];
5679 in->win_mtime[1] = oh->win_mtime[1];
5681 in->yst_uid = oh->yst_uid;
5682 in->yst_gid = oh->yst_gid;
5683 in->yst_atime = oh->yst_atime;
5684 in->yst_mtime = oh->yst_mtime;
5685 in->yst_ctime = oh->yst_ctime;
5686 in->yst_rdev = oh->yst_rdev;
5688 in->hdrChunk = chunk;
5689 in->serial = tags.serialNumber;
5691 } else if (in && !in->valid) {
5692 /* we need to load this info */
5695 in->variantType = oh->type;
5697 in->yst_mode = oh->yst_mode;
5698 #ifdef CONFIG_YAFFS_WINCE
5699 in->win_atime[0] = oh->win_atime[0];
5700 in->win_ctime[0] = oh->win_ctime[0];
5701 in->win_mtime[0] = oh->win_mtime[0];
5702 in->win_atime[1] = oh->win_atime[1];
5703 in->win_ctime[1] = oh->win_ctime[1];
5704 in->win_mtime[1] = oh->win_mtime[1];
5706 in->yst_uid = oh->yst_uid;
5707 in->yst_gid = oh->yst_gid;
5708 in->yst_atime = oh->yst_atime;
5709 in->yst_mtime = oh->yst_mtime;
5710 in->yst_ctime = oh->yst_ctime;
5711 in->yst_rdev = oh->yst_rdev;
5713 in->hdrChunk = chunk;
5714 in->serial = tags.serialNumber;
5716 yaffs_SetObjectName(in, oh->name);
5719 /* directory stuff...
5724 yaffs_FindOrCreateObjectByNumber
5725 (dev, oh->parentObjectId,
5726 YAFFS_OBJECT_TYPE_DIRECTORY);
5729 if (parent && parent->variantType ==
5730 YAFFS_OBJECT_TYPE_UNKNOWN) {
5731 /* Set up as a directory */
5732 parent->variantType =
5733 YAFFS_OBJECT_TYPE_DIRECTORY;
5734 YINIT_LIST_HEAD(&parent->variant.
5737 } else if (!parent || parent->variantType !=
5738 YAFFS_OBJECT_TYPE_DIRECTORY) {
5739 /* Hoosterman, another problem....
5740 * We're trying to use a non-directory as a directory
5743 T(YAFFS_TRACE_ERROR,
5745 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5747 parent = dev->lostNFoundDir;
5750 yaffs_AddObjectToDirectory(parent, in);
5752 if (0 && (parent == dev->deletedDir ||
5753 parent == dev->unlinkedDir)) {
5754 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5755 dev->nDeletedFiles++;
5757 /* Note re hardlinks.
5758 * Since we might scan a hardlink before its equivalent object is scanned
5759 * we put them all in a list.
5760 * After scanning is complete, we should have all the objects, so we run through this
5761 * list and fix up all the chains.
5764 switch (in->variantType) {
5765 case YAFFS_OBJECT_TYPE_UNKNOWN:
5766 /* Todo got a problem */
5768 case YAFFS_OBJECT_TYPE_FILE:
5769 if (dev->useHeaderFileSize)
5771 in->variant.fileVariant.
5776 case YAFFS_OBJECT_TYPE_HARDLINK:
5777 in->variant.hardLinkVariant.
5778 equivalentObjectId =
5779 oh->equivalentObjectId;
5780 in->hardLinks.next =
5781 (struct ylist_head *)
5785 case YAFFS_OBJECT_TYPE_DIRECTORY:
5788 case YAFFS_OBJECT_TYPE_SPECIAL:
5791 case YAFFS_OBJECT_TYPE_SYMLINK:
5792 in->variant.symLinkVariant.alias =
5793 yaffs_CloneString(oh->alias);
5794 if (!in->variant.symLinkVariant.alias)
5800 if (parent == dev->deletedDir) {
5801 yaffs_DestroyObject(in);
5802 bi->hasShrinkHeader = 1;
5809 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5810 /* If we got this far while scanning, then the block is fully allocated.*/
5811 state = YAFFS_BLOCK_STATE_FULL;
5814 bi->blockState = state;
5816 /* Now let's see if it was dirty */
5817 if (bi->pagesInUse == 0 &&
5818 !bi->hasShrinkHeader &&
5819 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5820 yaffs_BlockBecameDirty(dev, blk);
5826 /* Ok, we've done all the scanning.
5827 * Fix up the hard link chains.
5828 * We should now have scanned all the objects, now it's time to add these
5832 yaffs_HardlinkFixup(dev, hardList);
5834 /* Fix up any shadowed objects */
5836 struct yaffs_ShadowFixerStruct *fixer;
5839 while (shadowFixerList) {
5840 fixer = shadowFixerList;
5841 shadowFixerList = fixer->next;
5842 /* Complete the rename transaction by deleting the shadowed object
5843 * then setting the object header to unshadowed.
5845 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
5847 yaffs_DeleteObject(obj);
5849 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
5852 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5858 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5863 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5869 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5872 yaffs_ObjectHeader *oh;
5874 yaffs_ExtendedTags tags;
5876 int alloc_failed = 0;
5884 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
5886 in->lazyLoaded ? "not yet" : "already"));
5889 if (in->lazyLoaded && in->hdrChunk > 0) {
5891 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5893 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
5894 oh = (yaffs_ObjectHeader *) chunkData;
5896 in->yst_mode = oh->yst_mode;
5897 #ifdef CONFIG_YAFFS_WINCE
5898 in->win_atime[0] = oh->win_atime[0];
5899 in->win_ctime[0] = oh->win_ctime[0];
5900 in->win_mtime[0] = oh->win_mtime[0];
5901 in->win_atime[1] = oh->win_atime[1];
5902 in->win_ctime[1] = oh->win_ctime[1];
5903 in->win_mtime[1] = oh->win_mtime[1];
5905 in->yst_uid = oh->yst_uid;
5906 in->yst_gid = oh->yst_gid;
5907 in->yst_atime = oh->yst_atime;
5908 in->yst_mtime = oh->yst_mtime;
5909 in->yst_ctime = oh->yst_ctime;
5910 in->yst_rdev = oh->yst_rdev;
5913 yaffs_SetObjectName(in, oh->name);
5915 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5916 in->variant.symLinkVariant.alias =
5917 yaffs_CloneString(oh->alias);
5918 if (!in->variant.symLinkVariant.alias)
5919 alloc_failed = 1; /* Not returned to caller */
5922 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5926 static int yaffs_ScanBackwards(yaffs_Device *dev)
5928 yaffs_ExtendedTags tags;
5933 int nBlocksToScan = 0;
5939 yaffs_BlockState state;
5940 yaffs_Object *hardList = NULL;
5941 yaffs_BlockInfo *bi;
5942 __u32 sequenceNumber;
5943 yaffs_ObjectHeader *oh;
5945 yaffs_Object *parent;
5946 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5952 int foundChunksInBlock;
5953 int equivalentObjectId;
5954 int alloc_failed = 0;
5957 yaffs_BlockIndex *blockIndex = NULL;
5958 int altBlockIndex = 0;
5960 if (!dev->isYaffs2) {
5962 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5968 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5969 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5972 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5974 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5977 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5983 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5987 dev->blocksInCheckpoint = 0;
5989 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5991 /* Scan all the blocks to determine their state */
5992 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5993 bi = yaffs_GetBlockInfo(dev, blk);
5994 yaffs_ClearChunkBits(dev, blk);
5996 bi->softDeletions = 0;
5998 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6000 bi->blockState = state;
6001 bi->sequenceNumber = sequenceNumber;
6003 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6004 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6005 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6006 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6008 T(YAFFS_TRACE_SCAN_DEBUG,
6009 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6010 state, sequenceNumber));
6013 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6014 dev->blocksInCheckpoint++;
6016 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6017 T(YAFFS_TRACE_BAD_BLOCKS,
6018 (TSTR("block %d is bad" TENDSTR), blk));
6019 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6020 T(YAFFS_TRACE_SCAN_DEBUG,
6021 (TSTR("Block empty " TENDSTR)));
6022 dev->nErasedBlocks++;
6023 dev->nFreeChunks += dev->nChunksPerBlock;
6024 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6026 /* Determine the highest sequence number */
6027 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6028 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6030 blockIndex[nBlocksToScan].seq = sequenceNumber;
6031 blockIndex[nBlocksToScan].block = blk;
6035 if (sequenceNumber >= dev->sequenceNumber)
6036 dev->sequenceNumber = sequenceNumber;
6038 /* TODO: Nasty sequence number! */
6041 ("Block scanning block %d has bad sequence number %d"
6042 TENDSTR), blk, sequenceNumber));
6049 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6055 /* Sort the blocks */
6056 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6058 /* Use qsort now. */
6059 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6063 /* Dungy old bubble sort... */
6065 yaffs_BlockIndex temp;
6069 for (i = 0; i < nBlocksToScan; i++)
6070 for (j = i + 1; j < nBlocksToScan; j++)
6071 if (blockIndex[i].seq > blockIndex[j].seq) {
6072 temp = blockIndex[j];
6073 blockIndex[j] = blockIndex[i];
6074 blockIndex[i] = temp;
6081 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6083 /* Now scan the blocks looking at the data. */
6085 endIterator = nBlocksToScan - 1;
6086 T(YAFFS_TRACE_SCAN_DEBUG,
6087 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6089 /* For each block.... backwards */
6090 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6092 /* Cooperative multitasking! This loop can run for so
6093 long that watchdog timers expire. */
6096 /* get the block to scan in the correct order */
6097 blk = blockIndex[blockIterator].block;
6099 bi = yaffs_GetBlockInfo(dev, blk);
6102 state = bi->blockState;
6106 /* For each chunk in each block that needs scanning.... */
6107 foundChunksInBlock = 0;
6108 for (c = dev->nChunksPerBlock - 1;
6109 !alloc_failed && c >= 0 &&
6110 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6111 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6112 /* Scan backwards...
6113 * Read the tags and decide what to do
6116 chunk = blk * dev->nChunksPerBlock + c;
6118 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6121 /* Let's have a good look at this chunk... */
6123 if (!tags.chunkUsed) {
6124 /* An unassigned chunk in the block.
6125 * If there are used chunks after this one, then
6126 * it is a chunk that was skipped due to failing the erased
6127 * check. Just skip it so that it can be deleted.
6128 * But, more typically, We get here when this is an unallocated
6129 * chunk and his means that either the block is empty or
6130 * this is the one being allocated from
6133 if (foundChunksInBlock) {
6134 /* This is a chunk that was skipped due to failing the erased check */
6135 } else if (c == 0) {
6136 /* We're looking at the first chunk in the block so the block is unused */
6137 state = YAFFS_BLOCK_STATE_EMPTY;
6138 dev->nErasedBlocks++;
6140 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6141 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6142 if (dev->sequenceNumber == bi->sequenceNumber) {
6143 /* this is the block being allocated from */
6147 (" Allocating from %d %d"
6150 state = YAFFS_BLOCK_STATE_ALLOCATING;
6151 dev->allocationBlock = blk;
6152 dev->allocationPage = c;
6153 dev->allocationBlockFinder = blk;
6155 /* This is a partially written block that is not
6156 * the current allocation block. This block must have
6157 * had a write failure, so set up for retirement.
6160 /* bi->needsRetiring = 1; ??? TODO */
6161 bi->gcPrioritise = 1;
6163 T(YAFFS_TRACE_ALWAYS,
6164 (TSTR("Partially written block %d detected" TENDSTR),
6172 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6174 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6179 } else if (tags.chunkId > 0) {
6180 /* chunkId > 0 so it is a data chunk... */
6181 unsigned int endpos;
6183 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6185 foundChunksInBlock = 1;
6188 yaffs_SetChunkBit(dev, blk, c);
6191 in = yaffs_FindOrCreateObjectByNumber(dev,
6194 YAFFS_OBJECT_TYPE_FILE);
6201 in->variantType == YAFFS_OBJECT_TYPE_FILE
6203 in->variant.fileVariant.shrinkSize) {
6204 /* This has not been invalidated by a resize */
6205 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6210 /* File size is calculated by looking at the data chunks if we have not
6211 * seen an object header yet. Stop this practice once we find an object header.
6215 1) * dev->nDataBytesPerChunk +
6218 if (!in->valid && /* have not got an object header yet */
6219 in->variant.fileVariant.
6220 scannedFileSize < endpos) {
6221 in->variant.fileVariant.
6222 scannedFileSize = endpos;
6223 in->variant.fileVariant.
6225 in->variant.fileVariant.
6230 /* This chunk has been invalidated by a resize, so delete */
6231 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6235 /* chunkId == 0, so it is an ObjectHeader.
6236 * Thus, we read in the object header and make the object
6238 foundChunksInBlock = 1;
6240 yaffs_SetChunkBit(dev, blk, c);
6246 if (tags.extraHeaderInfoAvailable) {
6247 in = yaffs_FindOrCreateObjectByNumber
6248 (dev, tags.objectId,
6249 tags.extraObjectType);
6255 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6258 tags.extraShadows ||
6260 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6261 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6263 /* If we don't have valid info then we need to read the chunk
6264 * TODO In future we can probably defer reading the chunk and
6265 * living with invalid data until needed.
6268 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6273 oh = (yaffs_ObjectHeader *) chunkData;
6275 if (dev->inbandTags) {
6276 /* Fix up the header if they got corrupted by inband tags */
6277 oh->shadowsObject = oh->inbandShadowsObject;
6278 oh->isShrink = oh->inbandIsShrink;
6282 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6290 /* TODO Hoosterman we have a problem! */
6291 T(YAFFS_TRACE_ERROR,
6293 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6294 TENDSTR), tags.objectId, chunk));
6299 /* We have already filled this one.
6300 * We have a duplicate that will be discarded, but
6301 * we first have to suck out resize info if it is a file.
6304 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6306 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6307 (tags.extraHeaderInfoAvailable &&
6308 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6310 (oh) ? oh->fileSize : tags.
6312 __u32 parentObjectId =
6314 parentObjectId : tags.
6315 extraParentObjectId;
6319 (oh) ? oh->isShrink : tags.
6320 extraIsShrinkHeader;
6322 /* If it is deleted (unlinked at start also means deleted)
6323 * we treat the file size as being zeroed at this point.
6325 if (parentObjectId ==
6326 YAFFS_OBJECTID_DELETED
6327 || parentObjectId ==
6328 YAFFS_OBJECTID_UNLINKED) {
6334 in->variant.fileVariant.
6335 shrinkSize > thisSize) {
6336 in->variant.fileVariant.
6342 bi->hasShrinkHeader = 1;
6345 /* Use existing - destroy this one. */
6346 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6350 if (!in->valid && in->variantType !=
6351 (oh ? oh->type : tags.extraObjectType))
6352 T(YAFFS_TRACE_ERROR, (
6353 TSTR("yaffs tragedy: Bad object type, "
6354 TCONT("%d != %d, for object %d at chunk ")
6355 TCONT("%d during scan")
6357 oh->type : tags.extraObjectType,
6358 in->variantType, tags.objectId,
6362 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6364 YAFFS_OBJECTID_LOSTNFOUND)) {
6365 /* We only load some info, don't fiddle with directory structure */
6369 in->variantType = oh->type;
6371 in->yst_mode = oh->yst_mode;
6372 #ifdef CONFIG_YAFFS_WINCE
6373 in->win_atime[0] = oh->win_atime[0];
6374 in->win_ctime[0] = oh->win_ctime[0];
6375 in->win_mtime[0] = oh->win_mtime[0];
6376 in->win_atime[1] = oh->win_atime[1];
6377 in->win_ctime[1] = oh->win_ctime[1];
6378 in->win_mtime[1] = oh->win_mtime[1];
6380 in->yst_uid = oh->yst_uid;
6381 in->yst_gid = oh->yst_gid;
6382 in->yst_atime = oh->yst_atime;
6383 in->yst_mtime = oh->yst_mtime;
6384 in->yst_ctime = oh->yst_ctime;
6385 in->yst_rdev = oh->yst_rdev;
6389 in->variantType = tags.extraObjectType;
6393 in->hdrChunk = chunk;
6395 } else if (!in->valid) {
6396 /* we need to load this info */
6399 in->hdrChunk = chunk;
6402 in->variantType = oh->type;
6404 in->yst_mode = oh->yst_mode;
6405 #ifdef CONFIG_YAFFS_WINCE
6406 in->win_atime[0] = oh->win_atime[0];
6407 in->win_ctime[0] = oh->win_ctime[0];
6408 in->win_mtime[0] = oh->win_mtime[0];
6409 in->win_atime[1] = oh->win_atime[1];
6410 in->win_ctime[1] = oh->win_ctime[1];
6411 in->win_mtime[1] = oh->win_mtime[1];
6413 in->yst_uid = oh->yst_uid;
6414 in->yst_gid = oh->yst_gid;
6415 in->yst_atime = oh->yst_atime;
6416 in->yst_mtime = oh->yst_mtime;
6417 in->yst_ctime = oh->yst_ctime;
6418 in->yst_rdev = oh->yst_rdev;
6421 if (oh->shadowsObject > 0)
6422 yaffs_HandleShadowedObject(dev,
6428 yaffs_SetObjectName(in, oh->name);
6430 yaffs_FindOrCreateObjectByNumber
6431 (dev, oh->parentObjectId,
6432 YAFFS_OBJECT_TYPE_DIRECTORY);
6434 fileSize = oh->fileSize;
6435 isShrink = oh->isShrink;
6436 equivalentObjectId = oh->equivalentObjectId;
6439 in->variantType = tags.extraObjectType;
6441 yaffs_FindOrCreateObjectByNumber
6442 (dev, tags.extraParentObjectId,
6443 YAFFS_OBJECT_TYPE_DIRECTORY);
6444 fileSize = tags.extraFileLength;
6445 isShrink = tags.extraIsShrinkHeader;
6446 equivalentObjectId = tags.extraEquivalentObjectId;
6455 /* directory stuff...
6459 if (parent && parent->variantType ==
6460 YAFFS_OBJECT_TYPE_UNKNOWN) {
6461 /* Set up as a directory */
6462 parent->variantType =
6463 YAFFS_OBJECT_TYPE_DIRECTORY;
6464 YINIT_LIST_HEAD(&parent->variant.
6467 } else if (!parent || parent->variantType !=
6468 YAFFS_OBJECT_TYPE_DIRECTORY) {
6469 /* Hoosterman, another problem....
6470 * We're trying to use a non-directory as a directory
6473 T(YAFFS_TRACE_ERROR,
6475 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6477 parent = dev->lostNFoundDir;
6480 yaffs_AddObjectToDirectory(parent, in);
6482 itsUnlinked = (parent == dev->deletedDir) ||
6483 (parent == dev->unlinkedDir);
6486 /* Mark the block as having a shrinkHeader */
6487 bi->hasShrinkHeader = 1;
6490 /* Note re hardlinks.
6491 * Since we might scan a hardlink before its equivalent object is scanned
6492 * we put them all in a list.
6493 * After scanning is complete, we should have all the objects, so we run
6494 * through this list and fix up all the chains.
6497 switch (in->variantType) {
6498 case YAFFS_OBJECT_TYPE_UNKNOWN:
6499 /* Todo got a problem */
6501 case YAFFS_OBJECT_TYPE_FILE:
6503 if (in->variant.fileVariant.
6504 scannedFileSize < fileSize) {
6505 /* This covers the case where the file size is greater
6506 * than where the data is
6507 * This will happen if the file is resized to be larger
6508 * than its current data extents.
6510 in->variant.fileVariant.fileSize = fileSize;
6511 in->variant.fileVariant.scannedFileSize =
6512 in->variant.fileVariant.fileSize;
6516 in->variant.fileVariant.shrinkSize > fileSize) {
6517 in->variant.fileVariant.shrinkSize = fileSize;
6521 case YAFFS_OBJECT_TYPE_HARDLINK:
6523 in->variant.hardLinkVariant.equivalentObjectId =
6525 in->hardLinks.next =
6526 (struct ylist_head *) hardList;
6530 case YAFFS_OBJECT_TYPE_DIRECTORY:
6533 case YAFFS_OBJECT_TYPE_SPECIAL:
6536 case YAFFS_OBJECT_TYPE_SYMLINK:
6538 in->variant.symLinkVariant.alias =
6539 yaffs_CloneString(oh->alias);
6540 if (!in->variant.symLinkVariant.alias)
6550 } /* End of scanning for each chunk */
6552 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6553 /* If we got this far while scanning, then the block is fully allocated. */
6554 state = YAFFS_BLOCK_STATE_FULL;
6557 bi->blockState = state;
6559 /* Now let's see if it was dirty */
6560 if (bi->pagesInUse == 0 &&
6561 !bi->hasShrinkHeader &&
6562 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6563 yaffs_BlockBecameDirty(dev, blk);
6569 YFREE_ALT(blockIndex);
6573 /* Ok, we've done all the scanning.
6574 * Fix up the hard link chains.
6575 * We should now have scanned all the objects, now it's time to add these
6578 yaffs_HardlinkFixup(dev, hardList);
6581 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6586 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6591 /*------------------------------ Directory Functions ----------------------------- */
6593 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6595 struct ylist_head *lh;
6596 yaffs_Object *listObj;
6601 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6606 if (yaffs_SkipVerification(obj->myDev))
6610 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6615 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6616 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6620 /* Iterate through the objects in each hash entry */
6622 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6624 listObj = ylist_entry(lh, yaffs_Object, siblings);
6625 yaffs_VerifyObject(listObj);
6632 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6637 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6639 struct ylist_head *lh;
6640 yaffs_Object *listObj;
6647 if (yaffs_SkipFullVerification(directory->myDev))
6650 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6651 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6655 /* Iterate through the objects in each hash entry */
6657 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6659 listObj = ylist_entry(lh, yaffs_Object, siblings);
6660 if (listObj->parent != directory) {
6661 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6664 yaffs_VerifyObjectInDirectory(listObj);
6670 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6672 yaffs_Device *dev = obj->myDev;
6673 yaffs_Object *parent;
6675 yaffs_VerifyObjectInDirectory(obj);
6676 parent = obj->parent;
6678 yaffs_VerifyDirectory(parent);
6680 if (dev && dev->removeObjectCallback)
6681 dev->removeObjectCallback(obj);
6684 ylist_del_init(&obj->siblings);
6687 yaffs_VerifyDirectory(parent);
6691 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6695 T(YAFFS_TRACE_ALWAYS,
6697 ("tragedy: Trying to add an object to a null pointer directory"
6702 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6703 T(YAFFS_TRACE_ALWAYS,
6705 ("tragedy: Trying to add an object to a non-directory"
6710 if (obj->siblings.prev == NULL) {
6711 /* Not initialised */
6716 yaffs_VerifyDirectory(directory);
6718 yaffs_RemoveObjectFromDirectory(obj);
6722 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6723 obj->parent = directory;
6725 if (directory == obj->myDev->unlinkedDir
6726 || directory == obj->myDev->deletedDir) {
6728 obj->myDev->nUnlinkedFiles++;
6729 obj->renameAllowed = 0;
6732 yaffs_VerifyDirectory(directory);
6733 yaffs_VerifyObjectInDirectory(obj);
6736 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
6741 struct ylist_head *i;
6742 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6750 T(YAFFS_TRACE_ALWAYS,
6752 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6757 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6758 T(YAFFS_TRACE_ALWAYS,
6760 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6764 sum = yaffs_CalcNameSum(name);
6766 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6768 l = ylist_entry(i, yaffs_Object, siblings);
6770 if (l->parent != directory)
6773 yaffs_CheckObjectDetailsLoaded(l);
6775 /* Special case for lost-n-found */
6776 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6777 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
6779 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
6780 /* LostnFound chunk called Objxxx
6783 yaffs_GetObjectName(l, buffer,
6784 YAFFS_MAX_NAME_LENGTH);
6785 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
6796 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
6797 int (*fn) (yaffs_Object *))
6799 struct ylist_head *i;
6803 T(YAFFS_TRACE_ALWAYS,
6805 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6810 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6811 T(YAFFS_TRACE_ALWAYS,
6813 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6818 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6820 l = ylist_entry(i, yaffs_Object, siblings);
6831 /* GetEquivalentObject dereferences any hard links to get to the
6835 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
6837 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6838 /* We want the object id of the equivalent object, not this one */
6839 obj = obj->variant.hardLinkVariant.equivalentObject;
6840 yaffs_CheckObjectDetailsLoaded(obj);
6845 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
6847 memset(name, 0, buffSize * sizeof(YCHAR));
6849 yaffs_CheckObjectDetailsLoaded(obj);
6851 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6852 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6853 } else if (obj->hdrChunk <= 0) {
6855 YCHAR numString[20];
6856 YCHAR *x = &numString[19];
6857 unsigned v = obj->objectId;
6861 *x = '0' + (v % 10);
6864 /* make up a name */
6865 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6866 yaffs_strcat(locName, x);
6867 yaffs_strncpy(name, locName, buffSize - 1);
6870 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6871 else if (obj->shortName[0])
6872 yaffs_strcpy(name, obj->shortName);
6876 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6878 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6880 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6882 if (obj->hdrChunk > 0) {
6883 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6884 obj->hdrChunk, buffer,
6887 yaffs_strncpy(name, oh->name, buffSize - 1);
6889 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6892 return yaffs_strlen(name);
6895 int yaffs_GetObjectFileLength(yaffs_Object *obj)
6897 /* Dereference any hard linking */
6898 obj = yaffs_GetEquivalentObject(obj);
6900 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
6901 return obj->variant.fileVariant.fileSize;
6902 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
6903 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6905 /* Only a directory should drop through to here */
6906 return obj->myDev->nDataBytesPerChunk;
6910 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
6913 struct ylist_head *i;
6916 count++; /* the object itself */
6918 ylist_for_each(i, &obj->hardLinks)
6919 count++; /* add the hard links; */
6924 int yaffs_GetObjectInode(yaffs_Object *obj)
6926 obj = yaffs_GetEquivalentObject(obj);
6928 return obj->objectId;
6931 unsigned yaffs_GetObjectType(yaffs_Object *obj)
6933 obj = yaffs_GetEquivalentObject(obj);
6935 switch (obj->variantType) {
6936 case YAFFS_OBJECT_TYPE_FILE:
6939 case YAFFS_OBJECT_TYPE_DIRECTORY:
6942 case YAFFS_OBJECT_TYPE_SYMLINK:
6945 case YAFFS_OBJECT_TYPE_HARDLINK:
6948 case YAFFS_OBJECT_TYPE_SPECIAL:
6949 if (S_ISFIFO(obj->yst_mode))
6951 if (S_ISCHR(obj->yst_mode))
6953 if (S_ISBLK(obj->yst_mode))
6955 if (S_ISSOCK(obj->yst_mode))
6963 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
6965 obj = yaffs_GetEquivalentObject(obj);
6966 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
6967 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6969 return yaffs_CloneString(_Y(""));
6972 #ifndef CONFIG_YAFFS_WINCE
6974 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
6976 unsigned int valid = attr->ia_valid;
6978 if (valid & ATTR_MODE)
6979 obj->yst_mode = attr->ia_mode;
6980 if (valid & ATTR_UID)
6981 obj->yst_uid = attr->ia_uid;
6982 if (valid & ATTR_GID)
6983 obj->yst_gid = attr->ia_gid;
6985 if (valid & ATTR_ATIME)
6986 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6987 if (valid & ATTR_CTIME)
6988 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6989 if (valid & ATTR_MTIME)
6990 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6992 if (valid & ATTR_SIZE)
6993 yaffs_ResizeFile(obj, attr->ia_size);
6995 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7000 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7002 unsigned int valid = 0;
7004 attr->ia_mode = obj->yst_mode;
7006 attr->ia_uid = obj->yst_uid;
7008 attr->ia_gid = obj->yst_gid;
7011 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7012 valid |= ATTR_ATIME;
7013 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7014 valid |= ATTR_CTIME;
7015 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7016 valid |= ATTR_MTIME;
7018 attr->ia_size = yaffs_GetFileSize(obj);
7021 attr->ia_valid = valid;
7029 int yaffs_DumpObject(yaffs_Object *obj)
7033 yaffs_GetObjectName(obj, name, 256);
7035 T(YAFFS_TRACE_ALWAYS,
7037 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7038 " chunk %d type %d size %d\n"
7039 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7040 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7041 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7047 /*---------------------------- Initialisation code -------------------------------------- */
7049 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7052 /* Common functions, gotta have */
7053 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7056 #ifdef CONFIG_YAFFS_YAFFS2
7058 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7059 if (dev->writeChunkWithTagsToNAND &&
7060 dev->readChunkWithTagsFromNAND &&
7061 !dev->writeChunkToNAND &&
7062 !dev->readChunkFromNAND &&
7063 dev->markNANDBlockBad && dev->queryNANDBlock)
7067 /* Can use the "spare" style interface for yaffs1 */
7068 if (!dev->isYaffs2 &&
7069 !dev->writeChunkWithTagsToNAND &&
7070 !dev->readChunkWithTagsFromNAND &&
7071 dev->writeChunkToNAND &&
7072 dev->readChunkFromNAND &&
7073 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7080 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7082 /* Initialise the unlinked, deleted, root and lost and found directories */
7084 dev->lostNFoundDir = dev->rootDir = NULL;
7085 dev->unlinkedDir = dev->deletedDir = NULL;
7088 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7091 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7094 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7095 YAFFS_ROOT_MODE | S_IFDIR);
7096 dev->lostNFoundDir =
7097 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7098 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7100 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7101 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7108 int yaffs_GutsInitialise(yaffs_Device *dev)
7110 int init_failed = 0;
7114 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7116 /* Check stuff that must be set */
7119 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7123 dev->internalStartBlock = dev->startBlock;
7124 dev->internalEndBlock = dev->endBlock;
7125 dev->blockOffset = 0;
7126 dev->chunkOffset = 0;
7127 dev->nFreeChunks = 0;
7131 if (dev->startBlock == 0) {
7132 dev->internalStartBlock = dev->startBlock + 1;
7133 dev->internalEndBlock = dev->endBlock + 1;
7134 dev->blockOffset = 1;
7135 dev->chunkOffset = dev->nChunksPerBlock;
7138 /* Check geometry parameters. */
7140 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7141 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7142 (dev->inbandTags && !dev->isYaffs2) ||
7143 dev->nChunksPerBlock < 2 ||
7144 dev->nReservedBlocks < 2 ||
7145 dev->internalStartBlock <= 0 ||
7146 dev->internalEndBlock <= 0 ||
7147 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) { /* otherwise it is too small */
7148 T(YAFFS_TRACE_ALWAYS,
7150 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7151 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7155 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7156 T(YAFFS_TRACE_ALWAYS,
7157 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7161 /* Sort out space for inband tags, if required */
7162 if (dev->inbandTags)
7163 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7165 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7167 /* Got the right mix of functions? */
7168 if (!yaffs_CheckDevFunctions(dev)) {
7169 /* Function missing */
7170 T(YAFFS_TRACE_ALWAYS,
7172 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7177 /* This is really a compilation check. */
7178 if (!yaffs_CheckStructures()) {
7179 T(YAFFS_TRACE_ALWAYS,
7180 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7184 if (dev->isMounted) {
7185 T(YAFFS_TRACE_ALWAYS,
7186 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7190 /* Finished with most checks. One or two more checks happen later on too. */
7194 /* OK now calculate a few things for the device */
7197 * Calculate all the chunk size manipulation numbers:
7199 x = dev->nDataBytesPerChunk;
7200 /* We always use dev->chunkShift and dev->chunkDiv */
7201 dev->chunkShift = Shifts(x);
7202 x >>= dev->chunkShift;
7204 /* We only use chunk mask if chunkDiv is 1 */
7205 dev->chunkMask = (1<<dev->chunkShift) - 1;
7208 * Calculate chunkGroupBits.
7209 * We need to find the next power of 2 > than internalEndBlock
7212 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7216 /* Set up tnode width if wide tnodes are enabled. */
7217 if (!dev->wideTnodesDisabled) {
7218 /* bits must be even so that we end up with 32-bit words */
7222 dev->tnodeWidth = 16;
7224 dev->tnodeWidth = bits;
7226 dev->tnodeWidth = 16;
7228 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7230 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7231 * so if the bitwidth of the
7232 * chunk range we're using is greater than 16 we need
7233 * to figure out chunk shift and chunkGroupSize
7236 if (bits <= dev->tnodeWidth)
7237 dev->chunkGroupBits = 0;
7239 dev->chunkGroupBits = bits - dev->tnodeWidth;
7242 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7244 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7245 /* We have a problem because the soft delete won't work if
7246 * the chunk group size > chunks per block.
7247 * This can be remedied by using larger "virtual blocks".
7249 T(YAFFS_TRACE_ALWAYS,
7250 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7255 /* OK, we've finished verifying the device, lets continue with initialisation */
7257 /* More device initialisation */
7258 dev->garbageCollections = 0;
7259 dev->passiveGarbageCollections = 0;
7260 dev->currentDirtyChecker = 0;
7261 dev->bufferedBlock = -1;
7262 dev->doingBufferedBlockRewrite = 0;
7263 dev->nDeletedFiles = 0;
7264 dev->nBackgroundDeletions = 0;
7265 dev->nUnlinkedFiles = 0;
7267 dev->eccUnfixed = 0;
7268 dev->tagsEccFixed = 0;
7269 dev->tagsEccUnfixed = 0;
7270 dev->nErasureFailures = 0;
7271 dev->nErasedBlocks = 0;
7273 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7275 /* Initialise temporary buffers and caches. */
7276 if (!yaffs_InitialiseTempBuffers(dev))
7279 dev->srCache = NULL;
7280 dev->gcCleanupList = NULL;
7284 dev->nShortOpCaches > 0) {
7287 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7289 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7290 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7292 dev->srCache = YMALLOC(srCacheBytes);
7294 buf = (__u8 *) dev->srCache;
7297 memset(dev->srCache, 0, srCacheBytes);
7299 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7300 dev->srCache[i].object = NULL;
7301 dev->srCache[i].lastUse = 0;
7302 dev->srCache[i].dirty = 0;
7303 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7314 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7315 if (!dev->gcCleanupList)
7320 dev->useHeaderFileSize = 1;
7322 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7325 yaffs_InitialiseTnodes(dev);
7326 yaffs_InitialiseObjects(dev);
7328 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7333 /* Now scan the flash. */
7334 if (dev->isYaffs2) {
7335 if (yaffs_CheckpointRestore(dev)) {
7336 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7337 T(YAFFS_TRACE_ALWAYS,
7338 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7341 /* Clean up the mess caused by an aborted checkpoint load
7342 * and scan backwards.
7344 yaffs_DeinitialiseBlocks(dev);
7345 yaffs_DeinitialiseTnodes(dev);
7346 yaffs_DeinitialiseObjects(dev);
7349 dev->nErasedBlocks = 0;
7350 dev->nFreeChunks = 0;
7351 dev->allocationBlock = -1;
7352 dev->allocationPage = -1;
7353 dev->nDeletedFiles = 0;
7354 dev->nUnlinkedFiles = 0;
7355 dev->nBackgroundDeletions = 0;
7356 dev->oldestDirtySequence = 0;
7358 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7361 yaffs_InitialiseTnodes(dev);
7362 yaffs_InitialiseObjects(dev);
7364 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7367 if (!init_failed && !yaffs_ScanBackwards(dev))
7370 } else if (!yaffs_Scan(dev))
7373 yaffs_StripDeletedObjects(dev);
7377 /* Clean up the mess */
7378 T(YAFFS_TRACE_TRACING,
7379 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7381 yaffs_Deinitialise(dev);
7385 /* Zero out stats */
7386 dev->nPageReads = 0;
7387 dev->nPageWrites = 0;
7388 dev->nBlockErasures = 0;
7390 dev->nRetriedWrites = 0;
7392 dev->nRetiredBlocks = 0;
7394 yaffs_VerifyFreeChunks(dev);
7395 yaffs_VerifyBlocks(dev);
7398 T(YAFFS_TRACE_TRACING,
7399 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7404 void yaffs_Deinitialise(yaffs_Device *dev)
7406 if (dev->isMounted) {
7409 yaffs_DeinitialiseBlocks(dev);
7410 yaffs_DeinitialiseTnodes(dev);
7411 yaffs_DeinitialiseObjects(dev);
7412 if (dev->nShortOpCaches > 0 &&
7415 for (i = 0; i < dev->nShortOpCaches; i++) {
7416 if (dev->srCache[i].data)
7417 YFREE(dev->srCache[i].data);
7418 dev->srCache[i].data = NULL;
7421 YFREE(dev->srCache);
7422 dev->srCache = NULL;
7425 YFREE(dev->gcCleanupList);
7427 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7428 YFREE(dev->tempBuffer[i].buffer);
7432 if (dev->deinitialiseNAND)
7433 dev->deinitialiseNAND(dev);
7437 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7442 yaffs_BlockInfo *blk;
7444 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7446 blk = yaffs_GetBlockInfo(dev, b);
7448 switch (blk->blockState) {
7449 case YAFFS_BLOCK_STATE_EMPTY:
7450 case YAFFS_BLOCK_STATE_ALLOCATING:
7451 case YAFFS_BLOCK_STATE_COLLECTING:
7452 case YAFFS_BLOCK_STATE_FULL:
7454 (dev->nChunksPerBlock - blk->pagesInUse +
7455 blk->softDeletions);
7465 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7467 /* This is what we report to the outside world */
7470 int nDirtyCacheChunks;
7471 int blocksForCheckpoint;
7475 nFree = dev->nFreeChunks;
7477 nFree = yaffs_CountFreeChunks(dev);
7480 nFree += dev->nDeletedFiles;
7482 /* Now count the number of dirty chunks in the cache and subtract those */
7484 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7485 if (dev->srCache[i].dirty)
7486 nDirtyCacheChunks++;
7489 nFree -= nDirtyCacheChunks;
7491 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7493 /* Now we figure out how much to reserve for the checkpoint and report that... */
7494 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7495 if (blocksForCheckpoint < 0)
7496 blocksForCheckpoint = 0;
7498 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7507 static int yaffs_freeVerificationFailures;
7509 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7514 if (yaffs_SkipVerification(dev))
7517 counted = yaffs_CountFreeChunks(dev);
7519 difference = dev->nFreeChunks - counted;
7522 T(YAFFS_TRACE_ALWAYS,
7523 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7524 dev->nFreeChunks, counted, difference));
7525 yaffs_freeVerificationFailures++;
7529 /*---------------------------------------- YAFFS test code ----------------------*/
7531 #define yaffs_CheckStruct(structure, syze, name) \
7533 if (sizeof(structure) != syze) { \
7534 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7535 name, syze, sizeof(structure))); \
7536 return YAFFS_FAIL; \
7540 static int yaffs_CheckStructures(void)
7542 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7543 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7544 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7545 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7546 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7548 #ifndef CONFIG_YAFFS_WINCE
7549 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");