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.96 2009-12-03 03:42:28 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 void yaffs_UpdateParent(yaffs_Object *obj);
53 static int yaffs_UnlinkObject(yaffs_Object *obj);
54 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
56 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
58 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
60 yaffs_ExtendedTags *tags,
62 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
63 int chunkInNAND, int inScan);
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66 yaffs_ObjectType type);
67 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
69 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
70 int force, int isShrink, int shadows);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
74 int chunkOffset, int *limit);
75 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
77 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
80 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
83 static int yaffs_UnlinkWorker(yaffs_Object *obj);
85 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
88 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
89 yaffs_BlockInfo **blockUsedPtr);
91 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
97 static int yaffs_CheckFileSanity(yaffs_Object *in);
99 #define yaffs_CheckFileSanity(in)
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
107 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
108 yaffs_ExtendedTags *tags);
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
112 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
113 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_LoadLevel0Tnode(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;
1484 fStruct->topLevel++;
1486 T(YAFFS_TRACE_ERROR,
1487 (TSTR("yaffs: no more tnodes" TENDSTR)));
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);
1509 if(!tn->internal[x])
1512 } else if (l == 1) {
1513 /* Looking from level 1 at level 0 */
1515 /* If we already have one, then release it.*/
1516 if (tn->internal[x])
1517 yaffs_FreeTnode(dev, tn->internal[x]);
1518 tn->internal[x] = passedTn;
1520 } else if (!tn->internal[x]) {
1521 /* Don't have one, none passed in */
1522 tn->internal[x] = yaffs_GetTnode(dev);
1523 if(!tn->internal[x])
1528 tn = tn->internal[x];
1532 /* top is level 0 */
1534 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1535 yaffs_FreeTnode(dev, passedTn);
1542 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1543 yaffs_ExtendedTags *tags, int objectId,
1548 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1549 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1550 theChunk % dev->nChunksPerBlock)) {
1552 if(dev->chunkGroupSize == 1)
1555 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1557 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1569 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1570 * chunks and tnodes in the file
1571 * Returns 1 if the tree was deleted.
1572 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1575 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1576 int chunkOffset, int *limit)
1581 yaffs_ExtendedTags tags;
1583 yaffs_Device *dev = in->myDev;
1589 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1591 if (tn->internal[i]) {
1592 if (limit && (*limit) < 0) {
1596 yaffs_DeleteWorker(in,
1604 YAFFS_TNODES_INTERNAL_BITS)
1609 yaffs_FreeTnode(dev,
1612 tn->internal[i] = NULL;
1616 return (allDone) ? 1 : 0;
1617 } else if (level == 0) {
1620 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1622 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1625 chunkInInode = (chunkOffset <<
1626 YAFFS_TNODES_LEVEL0_BITS) + i;
1629 yaffs_FindChunkInGroup(dev,
1635 if (foundChunk > 0) {
1636 yaffs_DeleteChunk(dev,
1641 *limit = *limit - 1;
1648 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1652 return (i < 0) ? 1 : 0;
1662 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1664 yaffs_BlockInfo *theBlock;
1666 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1668 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1670 theBlock->softDeletions++;
1675 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1676 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1678 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1681 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1682 __u32 level, int chunkOffset)
1687 yaffs_Device *dev = in->myDev;
1692 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1694 if (tn->internal[i]) {
1696 yaffs_SoftDeleteWorker(in,
1702 YAFFS_TNODES_INTERNAL_BITS)
1705 yaffs_FreeTnode(dev,
1708 tn->internal[i] = NULL;
1710 /* Hoosterman... how could this happen? */
1714 return (allDone) ? 1 : 0;
1715 } else if (level == 0) {
1717 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1718 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1720 /* Note this does not find the real chunk, only the chunk group.
1721 * We make an assumption that a chunk group is not larger than
1724 yaffs_SoftDeleteChunk(dev, theChunk);
1725 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1739 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1742 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1743 if (obj->nDataChunks <= 0) {
1744 /* Empty file with no duplicate object headers, just delete it immediately */
1745 yaffs_FreeTnode(obj->myDev,
1746 obj->variant.fileVariant.top);
1747 obj->variant.fileVariant.top = NULL;
1748 T(YAFFS_TRACE_TRACING,
1749 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1751 yaffs_DoGenericObjectDeletion(obj);
1753 yaffs_SoftDeleteWorker(obj,
1754 obj->variant.fileVariant.top,
1755 obj->variant.fileVariant.
1757 obj->softDeleted = 1;
1762 /* Pruning removes any part of the file structure tree that is beyond the
1763 * bounds of the file (ie that does not point to chunks).
1765 * A file should only get pruned when its size is reduced.
1767 * Before pruning, the chunks must be pulled from the tree and the
1768 * level 0 tnode entries must be zeroed out.
1769 * Could also use this for file deletion, but that's probably better handled
1770 * by a special case.
1773 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1774 __u32 level, int del0)
1782 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1783 if (tn->internal[i] && level > 0) {
1785 yaffs_PruneWorker(dev, tn->internal[i],
1787 (i == 0) ? del0 : 1);
1790 if (tn->internal[i])
1794 if (hasData == 0 && del0) {
1795 /* Free and return NULL */
1797 yaffs_FreeTnode(dev, tn);
1807 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1808 yaffs_FileStructure *fStruct)
1815 if (fStruct->topLevel > 0) {
1817 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1819 /* Now we have a tree with all the non-zero branches NULL but the height
1820 * is the same as it was.
1821 * Let's see if we can trim internal tnodes to shorten the tree.
1822 * We can do this if only the 0th element in the tnode is in use
1823 * (ie all the non-zero are NULL)
1826 while (fStruct->topLevel && !done) {
1830 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1831 if (tn->internal[i])
1836 fStruct->top = tn->internal[0];
1837 fStruct->topLevel--;
1838 yaffs_FreeTnode(dev, tn);
1848 /*-------------------- End of File Structure functions.-------------------*/
1850 /* yaffs_CreateFreeObjects creates a bunch more objects and
1851 * adds them to the object free list.
1853 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1856 yaffs_Object *newObjects;
1857 yaffs_ObjectList *list;
1862 /* make these things */
1863 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1864 list = YMALLOC(sizeof(yaffs_ObjectList));
1866 if (!newObjects || !list) {
1875 T(YAFFS_TRACE_ALLOCATE,
1876 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1880 /* Hook them into the free list */
1881 for (i = 0; i < nObjects - 1; i++) {
1882 newObjects[i].siblings.next =
1883 (struct ylist_head *)(&newObjects[i + 1]);
1886 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1887 dev->freeObjects = newObjects;
1888 dev->nFreeObjects += nObjects;
1889 dev->nObjectsCreated += nObjects;
1891 /* Now add this bunch of Objects to a list for freeing up. */
1893 list->objects = newObjects;
1894 list->next = dev->allocatedObjectList;
1895 dev->allocatedObjectList = list;
1901 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1902 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1904 yaffs_Object *tn = NULL;
1906 #ifdef VALGRIND_TEST
1907 tn = YMALLOC(sizeof(yaffs_Object));
1909 /* If there are none left make more */
1910 if (!dev->freeObjects)
1911 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1913 if (dev->freeObjects) {
1914 tn = dev->freeObjects;
1916 (yaffs_Object *) (dev->freeObjects->siblings.next);
1917 dev->nFreeObjects--;
1921 /* Now sweeten it up... */
1923 memset(tn, 0, sizeof(yaffs_Object));
1924 tn->beingCreated = 1;
1928 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1929 YINIT_LIST_HEAD(&(tn->hardLinks));
1930 YINIT_LIST_HEAD(&(tn->hashLink));
1931 YINIT_LIST_HEAD(&tn->siblings);
1934 /* Now make the directory sane */
1936 tn->parent = dev->rootDir;
1937 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1940 /* Add it to the lost and found directory.
1941 * NB Can't put root or lostNFound in lostNFound so
1942 * check if lostNFound exists first
1944 if (dev->lostNFoundDir)
1945 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1947 tn->beingCreated = 0;
1950 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1955 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1960 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1962 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1963 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1964 obj->unlinkAllowed = 0; /* ... or unlink it */
1967 obj->yst_mode = mode;
1969 obj->hdrChunk = 0; /* Not a valid chunk. */
1976 static void yaffs_UnhashObject(yaffs_Object *tn)
1979 yaffs_Device *dev = tn->myDev;
1981 /* If it is still linked into the bucket list, free from the list */
1982 if (!ylist_empty(&tn->hashLink)) {
1983 ylist_del_init(&tn->hashLink);
1984 bucket = yaffs_HashFunction(tn->objectId);
1985 dev->objectBucket[bucket].count--;
1989 /* FreeObject frees up a Object and puts it back on the free list */
1990 static void yaffs_FreeObject(yaffs_Object *tn)
1992 yaffs_Device *dev = tn->myDev;
1995 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2000 if (!ylist_empty(&tn->siblings))
2006 /* We're still hooked up to a cached inode.
2007 * Don't delete now, but mark for later deletion
2009 tn->deferedFree = 1;
2014 yaffs_UnhashObject(tn);
2016 #ifdef VALGRIND_TEST
2020 /* Link into the free list. */
2021 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2022 dev->freeObjects = tn;
2023 dev->nFreeObjects++;
2025 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2030 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2032 if (obj->deferedFree)
2033 yaffs_FreeObject(obj);
2038 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2040 /* Free the list of allocated Objects */
2042 yaffs_ObjectList *tmp;
2044 while (dev->allocatedObjectList) {
2045 tmp = dev->allocatedObjectList->next;
2046 YFREE(dev->allocatedObjectList->objects);
2047 YFREE(dev->allocatedObjectList);
2049 dev->allocatedObjectList = tmp;
2052 dev->freeObjects = NULL;
2053 dev->nFreeObjects = 0;
2056 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2060 dev->allocatedObjectList = NULL;
2061 dev->freeObjects = NULL;
2062 dev->nFreeObjects = 0;
2064 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2065 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2066 dev->objectBucket[i].count = 0;
2070 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2075 int lowest = 999999;
2077 /* First let's see if we can find one that's empty. */
2079 for (i = 0; i < 10 && lowest > 0; i++) {
2081 x %= YAFFS_NOBJECT_BUCKETS;
2082 if (dev->objectBucket[x].count < lowest) {
2083 lowest = dev->objectBucket[x].count;
2089 /* If we didn't find an empty list, then try
2090 * looking a bit further for a short one
2093 for (i = 0; i < 10 && lowest > 3; i++) {
2095 x %= YAFFS_NOBJECT_BUCKETS;
2096 if (dev->objectBucket[x].count < lowest) {
2097 lowest = dev->objectBucket[x].count;
2106 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2108 int bucket = yaffs_FindNiceObjectBucket(dev);
2110 /* Now find an object value that has not already been taken
2111 * by scanning the list.
2115 struct ylist_head *i;
2117 __u32 n = (__u32) bucket;
2119 /* yaffs_CheckObjectHashSanity(); */
2123 n += YAFFS_NOBJECT_BUCKETS;
2124 if (1 || dev->objectBucket[bucket].count > 0) {
2125 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2126 /* If there is already one in the list */
2127 if (i && ylist_entry(i, yaffs_Object,
2128 hashLink)->objectId == n) {
2138 static void yaffs_HashObject(yaffs_Object *in)
2140 int bucket = yaffs_HashFunction(in->objectId);
2141 yaffs_Device *dev = in->myDev;
2143 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2144 dev->objectBucket[bucket].count++;
2147 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2149 int bucket = yaffs_HashFunction(number);
2150 struct ylist_head *i;
2153 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2154 /* Look if it is in the list */
2156 in = ylist_entry(i, yaffs_Object, hashLink);
2157 if (in->objectId == number) {
2159 /* Don't tell the VFS about this one if it is defered free */
2160 if (in->deferedFree)
2172 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2173 yaffs_ObjectType type)
2175 yaffs_Object *theObject;
2176 yaffs_Tnode *tn = NULL;
2179 number = yaffs_CreateNewObjectNumber(dev);
2181 if (type == YAFFS_OBJECT_TYPE_FILE) {
2182 tn = yaffs_GetTnode(dev);
2187 theObject = yaffs_AllocateEmptyObject(dev);
2190 yaffs_FreeTnode(dev,tn);
2196 theObject->fake = 0;
2197 theObject->renameAllowed = 1;
2198 theObject->unlinkAllowed = 1;
2199 theObject->objectId = number;
2200 yaffs_HashObject(theObject);
2201 theObject->variantType = type;
2202 #ifdef CONFIG_YAFFS_WINCE
2203 yfsd_WinFileTimeNow(theObject->win_atime);
2204 theObject->win_ctime[0] = theObject->win_mtime[0] =
2205 theObject->win_atime[0];
2206 theObject->win_ctime[1] = theObject->win_mtime[1] =
2207 theObject->win_atime[1];
2211 theObject->yst_atime = theObject->yst_mtime =
2212 theObject->yst_ctime = Y_CURRENT_TIME;
2215 case YAFFS_OBJECT_TYPE_FILE:
2216 theObject->variant.fileVariant.fileSize = 0;
2217 theObject->variant.fileVariant.scannedFileSize = 0;
2218 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2219 theObject->variant.fileVariant.topLevel = 0;
2220 theObject->variant.fileVariant.top = tn;
2222 case YAFFS_OBJECT_TYPE_DIRECTORY:
2223 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2226 case YAFFS_OBJECT_TYPE_SYMLINK:
2227 case YAFFS_OBJECT_TYPE_HARDLINK:
2228 case YAFFS_OBJECT_TYPE_SPECIAL:
2229 /* No action required */
2231 case YAFFS_OBJECT_TYPE_UNKNOWN:
2232 /* todo this should not happen */
2240 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2242 yaffs_ObjectType type)
2244 yaffs_Object *theObject = NULL;
2247 theObject = yaffs_FindObjectByNumber(dev, number);
2250 theObject = yaffs_CreateNewObject(dev, number, type);
2257 static YCHAR *yaffs_CloneString(const YCHAR *str)
2259 YCHAR *newStr = NULL;
2264 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2266 yaffs_strcpy(newStr, str);
2273 * Mknod (create) a new object.
2274 * equivalentObject only has meaning for a hard link;
2275 * aliasString only has meaning for a symlink.
2276 * rdev only has meaning for devices (a subset of special objects)
2279 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2280 yaffs_Object *parent,
2285 yaffs_Object *equivalentObject,
2286 const YCHAR *aliasString, __u32 rdev)
2291 yaffs_Device *dev = parent->myDev;
2293 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2294 if (yaffs_FindObjectByName(parent, name))
2297 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2298 str = yaffs_CloneString(aliasString);
2303 in = yaffs_CreateNewObject(dev, -1, type);
2317 in->variantType = type;
2319 in->yst_mode = mode;
2321 #ifdef CONFIG_YAFFS_WINCE
2322 yfsd_WinFileTimeNow(in->win_atime);
2323 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2324 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2327 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2329 in->yst_rdev = rdev;
2333 in->nDataChunks = 0;
2335 yaffs_SetObjectName(in, name);
2338 yaffs_AddObjectToDirectory(parent, in);
2340 in->myDev = parent->myDev;
2343 case YAFFS_OBJECT_TYPE_SYMLINK:
2344 in->variant.symLinkVariant.alias = str;
2346 case YAFFS_OBJECT_TYPE_HARDLINK:
2347 in->variant.hardLinkVariant.equivalentObject =
2349 in->variant.hardLinkVariant.equivalentObjectId =
2350 equivalentObject->objectId;
2351 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2353 case YAFFS_OBJECT_TYPE_FILE:
2354 case YAFFS_OBJECT_TYPE_DIRECTORY:
2355 case YAFFS_OBJECT_TYPE_SPECIAL:
2356 case YAFFS_OBJECT_TYPE_UNKNOWN:
2361 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2362 /* Could not create the object header, fail the creation */
2363 yaffs_DeleteObject(in);
2367 yaffs_UpdateParent(parent);
2373 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2374 __u32 mode, __u32 uid, __u32 gid)
2376 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2377 uid, gid, NULL, NULL, 0);
2380 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2381 __u32 mode, __u32 uid, __u32 gid)
2383 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2384 mode, uid, gid, NULL, NULL, 0);
2387 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2388 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2390 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2391 uid, gid, NULL, NULL, rdev);
2394 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2395 __u32 mode, __u32 uid, __u32 gid,
2398 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2399 uid, gid, NULL, alias, 0);
2402 /* yaffs_Link returns the object id of the equivalent object.*/
2403 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2404 yaffs_Object *equivalentObject)
2406 /* Get the real object in case we were fed a hard link as an equivalent object */
2407 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2409 if (yaffs_MknodObject
2410 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2411 equivalentObject, NULL, 0)) {
2412 return equivalentObject;
2419 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2420 const YCHAR *newName, int force, int shadows)
2425 yaffs_Object *existingTarget;
2428 newDir = obj->parent; /* use the old directory */
2430 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2431 T(YAFFS_TRACE_ALWAYS,
2433 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2438 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2439 if (obj->myDev->isYaffs2)
2440 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2442 unlinkOp = (newDir == obj->myDev->unlinkedDir
2443 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2445 deleteOp = (newDir == obj->myDev->deletedDir);
2447 existingTarget = yaffs_FindObjectByName(newDir, newName);
2449 /* If the object is a file going into the unlinked directory,
2450 * then it is OK to just stuff it in since duplicate names are allowed.
2451 * else only proceed if the new name does not exist and if we're putting
2452 * it into a directory.
2459 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2460 yaffs_SetObjectName(obj, newName);
2463 yaffs_AddObjectToDirectory(newDir, obj);
2468 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2469 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2476 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2477 yaffs_Object *newDir, const YCHAR *newName)
2479 yaffs_Object *obj = NULL;
2480 yaffs_Object *existingTarget = NULL;
2486 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2488 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2491 dev = oldDir->myDev;
2493 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2494 /* Special case for case insemsitive systems (eg. WinCE).
2495 * While look-up is case insensitive, the name isn't.
2496 * Therefore we might want to change x.txt to X.txt
2498 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2502 if(yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2506 obj = yaffs_FindObjectByName(oldDir, oldName);
2508 if (obj && obj->renameAllowed) {
2510 /* Now do the handling for an existing target, if there is one */
2512 existingTarget = yaffs_FindObjectByName(newDir, newName);
2513 if (existingTarget &&
2514 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2515 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2516 /* There is a target that is a non-empty directory, so we fail */
2517 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2518 } else if (existingTarget && existingTarget != obj) {
2519 /* Nuke the target first, using shadowing,
2520 * but only if it isn't the same object.
2522 * Note we must disable gc otherwise it can mess up the shadowing.
2526 yaffs_ChangeObjectName(obj, newDir, newName, force,
2527 existingTarget->objectId);
2528 existingTarget->isShadowed = 1;
2529 yaffs_UnlinkObject(existingTarget);
2533 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2535 yaffs_UpdateParent(oldDir);
2536 if(newDir != oldDir)
2537 yaffs_UpdateParent(newDir);
2544 /*------------------------- Block Management and Page Allocation ----------------*/
2546 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2548 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2550 dev->blockInfo = NULL;
2551 dev->chunkBits = NULL;
2553 dev->allocationBlock = -1; /* force it to get a new one */
2555 /* If the first allocation strategy fails, thry the alternate one */
2556 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2557 if (!dev->blockInfo) {
2558 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2559 dev->blockInfoAlt = 1;
2561 dev->blockInfoAlt = 0;
2563 if (dev->blockInfo) {
2564 /* Set up dynamic blockinfo stuff. */
2565 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2566 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2567 if (!dev->chunkBits) {
2568 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2569 dev->chunkBitsAlt = 1;
2571 dev->chunkBitsAlt = 0;
2574 if (dev->blockInfo && dev->chunkBits) {
2575 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2576 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2583 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2585 if (dev->blockInfoAlt && dev->blockInfo)
2586 YFREE_ALT(dev->blockInfo);
2587 else if (dev->blockInfo)
2588 YFREE(dev->blockInfo);
2590 dev->blockInfoAlt = 0;
2592 dev->blockInfo = NULL;
2594 if (dev->chunkBitsAlt && dev->chunkBits)
2595 YFREE_ALT(dev->chunkBits);
2596 else if (dev->chunkBits)
2597 YFREE(dev->chunkBits);
2598 dev->chunkBitsAlt = 0;
2599 dev->chunkBits = NULL;
2602 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2603 yaffs_BlockInfo *bi)
2610 return 1; /* disqualification only applies to yaffs2. */
2612 if (!bi->hasShrinkHeader)
2613 return 1; /* can gc */
2615 /* Find the oldest dirty sequence number if we don't know it and save it
2616 * so we don't have to keep recomputing it.
2618 if (!dev->oldestDirtySequence) {
2619 seq = dev->sequenceNumber;
2621 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2623 b = yaffs_GetBlockInfo(dev, i);
2624 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2625 (b->pagesInUse - b->softDeletions) <
2626 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2627 seq = b->sequenceNumber;
2630 dev->oldestDirtySequence = seq;
2633 /* Can't do gc of this block if there are any blocks older than this one that have
2636 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2639 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2640 * for garbage collection.
2643 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2646 int b = dev->currentDirtyChecker;
2652 int prioritised = 0;
2653 yaffs_BlockInfo *bi;
2654 int pendingPrioritisedExist = 0;
2656 /* First let's see if we need to grab a prioritised block */
2657 if (dev->hasPendingPrioritisedGCs) {
2658 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2660 bi = yaffs_GetBlockInfo(dev, i);
2661 /* yaffs_VerifyBlock(dev,bi,i); */
2663 if (bi->gcPrioritise) {
2664 pendingPrioritisedExist = 1;
2665 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2666 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2667 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2670 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2675 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2676 dev->hasPendingPrioritisedGCs = 0;
2679 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2681 * else (we're doing a leasurely gc), then we only bother to do this if the
2682 * block has only a few pages in use.
2685 dev->nonAggressiveSkip--;
2687 if (!aggressive && (dev->nonAggressiveSkip > 0))
2692 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2696 dev->internalEndBlock - dev->internalStartBlock + 1;
2699 dev->internalEndBlock - dev->internalStartBlock + 1;
2700 iterations = iterations / 16;
2701 if (iterations > 200)
2705 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2707 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2708 b = dev->internalStartBlock;
2710 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2711 T(YAFFS_TRACE_ERROR,
2712 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2716 bi = yaffs_GetBlockInfo(dev, b);
2718 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2719 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2720 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2722 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2726 dev->currentDirtyChecker = b;
2730 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2731 dev->nChunksPerBlock - pagesInUse, prioritised));
2734 dev->oldestDirtySequence = 0;
2737 dev->nonAggressiveSkip = 4;
2742 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2744 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2748 /* If the block is still healthy erase it and mark as clean.
2749 * If the block has had a data failure, then retire it.
2752 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2753 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2754 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2756 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2758 if (!bi->needsRetiring) {
2759 yaffs_InvalidateCheckpoint(dev);
2760 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2762 dev->nErasureFailures++;
2763 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2764 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2769 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2771 for (i = 0; i < dev->nChunksPerBlock; i++) {
2772 if (!yaffs_CheckChunkErased
2773 (dev, blockNo * dev->nChunksPerBlock + i)) {
2774 T(YAFFS_TRACE_ERROR,
2776 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2777 TENDSTR), blockNo, i));
2783 /* Clean it up... */
2784 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2785 dev->nErasedBlocks++;
2787 bi->softDeletions = 0;
2788 bi->hasShrinkHeader = 0;
2789 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2790 bi->gcPrioritise = 0;
2791 yaffs_ClearChunkBits(dev, blockNo);
2793 T(YAFFS_TRACE_ERASE,
2794 (TSTR("Erased block %d" TENDSTR), blockNo));
2796 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2798 yaffs_RetireBlock(dev, blockNo);
2799 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2800 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2804 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2808 yaffs_BlockInfo *bi;
2810 if (dev->nErasedBlocks < 1) {
2811 /* Hoosterman we've got a problem.
2812 * Can't get space to gc
2814 T(YAFFS_TRACE_ERROR,
2815 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2820 /* Find an empty block. */
2822 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2823 dev->allocationBlockFinder++;
2824 if (dev->allocationBlockFinder < dev->internalStartBlock
2825 || dev->allocationBlockFinder > dev->internalEndBlock) {
2826 dev->allocationBlockFinder = dev->internalStartBlock;
2829 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2831 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2832 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2833 dev->sequenceNumber++;
2834 bi->sequenceNumber = dev->sequenceNumber;
2835 dev->nErasedBlocks--;
2836 T(YAFFS_TRACE_ALLOCATE,
2837 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2838 dev->allocationBlockFinder, dev->sequenceNumber,
2839 dev->nErasedBlocks));
2840 return dev->allocationBlockFinder;
2844 T(YAFFS_TRACE_ALWAYS,
2846 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2847 TENDSTR), dev->nErasedBlocks));
2854 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2856 if (!dev->nCheckpointBlocksRequired &&
2858 /* Not a valid value so recalculate */
2861 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2864 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2866 if (tnodeSize < sizeof(yaffs_Tnode))
2867 tnodeSize = sizeof(yaffs_Tnode);
2869 nBytes += sizeof(yaffs_CheckpointValidity);
2870 nBytes += sizeof(yaffs_CheckpointDevice);
2871 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2872 nBytes += devBlocks * dev->chunkBitmapStride;
2873 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2874 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2875 nBytes += sizeof(yaffs_CheckpointValidity);
2876 nBytes += sizeof(__u32); /* checksum*/
2878 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2880 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2882 dev->nCheckpointBlocksRequired = nBlocks;
2885 return dev->nCheckpointBlocksRequired;
2889 * Check if there's space to allocate...
2890 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2892 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2895 int reservedBlocks = dev->nReservedBlocks;
2896 int checkpointBlocks;
2898 if (dev->isYaffs2) {
2899 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2900 dev->blocksInCheckpoint;
2901 if (checkpointBlocks < 0)
2902 checkpointBlocks = 0;
2904 checkpointBlocks = 0;
2907 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2909 return (dev->nFreeChunks > reservedChunks);
2912 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2913 yaffs_BlockInfo **blockUsedPtr)
2916 yaffs_BlockInfo *bi;
2918 if (dev->allocationBlock < 0) {
2919 /* Get next block to allocate off */
2920 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2921 dev->allocationPage = 0;
2924 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2925 /* Not enough space to allocate unless we're allowed to use the reserve. */
2929 if (dev->nErasedBlocks < dev->nReservedBlocks
2930 && dev->allocationPage == 0) {
2931 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2934 /* Next page please.... */
2935 if (dev->allocationBlock >= 0) {
2936 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2938 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2939 dev->allocationPage;
2941 yaffs_SetChunkBit(dev, dev->allocationBlock,
2942 dev->allocationPage);
2944 dev->allocationPage++;
2948 /* If the block is full set the state to full */
2949 if (dev->allocationPage >= dev->nChunksPerBlock) {
2950 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2951 dev->allocationBlock = -1;
2960 T(YAFFS_TRACE_ERROR,
2961 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2966 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2970 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2972 if (dev->allocationBlock > 0)
2973 n += (dev->nChunksPerBlock - dev->allocationPage);
2979 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2985 int retVal = YAFFS_OK;
2988 int isCheckpointBlock;
2992 int chunksBefore = yaffs_GetErasedChunks(dev);
2995 yaffs_ExtendedTags tags;
2997 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2999 yaffs_Object *object;
3001 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3004 T(YAFFS_TRACE_TRACING,
3005 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3008 bi->hasShrinkHeader,
3011 /*yaffs_VerifyFreeChunks(dev); */
3013 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3014 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3016 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3018 /* Take off the number of soft deleted entries because
3019 * they're going to get really deleted during GC.
3021 if(dev->gcChunk == 0) /* first time through for this block */
3022 dev->nFreeChunks -= bi->softDeletions;
3026 if (isCheckpointBlock ||
3027 !yaffs_StillSomeChunkBits(dev, block)) {
3028 T(YAFFS_TRACE_TRACING,
3030 ("Collecting block %d that has no chunks in use" TENDSTR),
3032 yaffs_BlockBecameDirty(dev, block);
3035 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3037 yaffs_VerifyBlock(dev, bi, block);
3039 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3040 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3042 for (/* init already done */;
3043 retVal == YAFFS_OK &&
3044 dev->gcChunk < dev->nChunksPerBlock &&
3045 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3047 dev->gcChunk++, oldChunk++) {
3048 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3050 /* This page is in use and might need to be copied off */
3056 yaffs_InitialiseTags(&tags);
3058 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3062 yaffs_FindObjectByNumber(dev,
3065 T(YAFFS_TRACE_GC_DETAIL,
3067 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3068 dev->gcChunk, tags.objectId, tags.chunkId,
3071 if (object && !yaffs_SkipVerification(dev)) {
3072 if (tags.chunkId == 0)
3073 matchingChunk = object->hdrChunk;
3074 else if (object->softDeleted)
3075 matchingChunk = oldChunk; /* Defeat the test */
3077 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3079 if (oldChunk != matchingChunk)
3080 T(YAFFS_TRACE_ERROR,
3081 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3082 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3087 T(YAFFS_TRACE_ERROR,
3089 ("page %d in gc has no object: %d %d %d "
3091 tags.objectId, tags.chunkId, tags.byteCount));
3096 object->softDeleted &&
3097 tags.chunkId != 0) {
3098 /* Data chunk in a soft deleted file, throw it away
3099 * It's a soft deleted data chunk,
3100 * No need to copy this, just forget about it and
3101 * fix up the object.
3104 object->nDataChunks--;
3106 if (object->nDataChunks <= 0) {
3107 /* remeber to clean up the object */
3108 dev->gcCleanupList[cleanups] =
3114 /* Todo object && object->deleted && object->nDataChunks == 0 */
3115 /* Deleted object header with no data chunks.
3116 * Can be discarded and the file deleted.
3118 object->hdrChunk = 0;
3119 yaffs_FreeTnode(object->myDev,
3122 object->variant.fileVariant.top = NULL;
3123 yaffs_DoGenericObjectDeletion(object);
3125 } else if (object) {
3126 /* It's either a data chunk in a live file or
3127 * an ObjectHeader, so we're interested in it.
3128 * NB Need to keep the ObjectHeaders of deleted files
3129 * until the whole file has been deleted off
3131 tags.serialNumber++;
3135 if (tags.chunkId == 0) {
3136 /* It is an object Id,
3137 * We need to nuke the shrinkheader flags first
3138 * We no longer want the shrinkHeader flag since its work is done
3139 * and if it is left in place it will mess up scanning.
3142 yaffs_ObjectHeader *oh;
3143 oh = (yaffs_ObjectHeader *)buffer;
3145 tags.extraIsShrinkHeader = 0;
3147 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3151 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3154 retVal = YAFFS_FAIL;
3157 /* Ok, now fix up the Tnodes etc. */
3159 if (tags.chunkId == 0) {
3161 object->hdrChunk = newChunk;
3162 object->serial = tags.serialNumber;
3164 /* It's a data chunk */
3165 yaffs_PutChunkIntoFile
3173 if (retVal == YAFFS_OK)
3174 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3179 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3182 /* Do any required cleanups */
3183 for (i = 0; i < cleanups; i++) {
3184 /* Time to delete the file too */
3186 yaffs_FindObjectByNumber(dev,
3187 dev->gcCleanupList[i]);
3189 yaffs_FreeTnode(dev,
3190 object->variant.fileVariant.
3192 object->variant.fileVariant.top = NULL;
3195 ("yaffs: About to finally delete object %d"
3196 TENDSTR), object->objectId));
3197 yaffs_DoGenericObjectDeletion(object);
3198 object->myDev->nDeletedFiles--;
3205 yaffs_VerifyCollectedBlock(dev, bi, block);
3207 chunksAfter = yaffs_GetErasedChunks(dev);
3208 if (chunksBefore >= chunksAfter) {
3211 ("gc did not increase free chunks before %d after %d"
3212 TENDSTR), chunksBefore, chunksAfter));
3215 /* If the gc completed then clear the current gcBlock so that we find another. */
3216 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3226 /* New garbage collector
3227 * If we're very low on erased blocks then we do aggressive garbage collection
3228 * otherwise we do "leasurely" garbage collection.
3229 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3230 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3232 * The idea is to help clear out space in a more spread-out manner.
3233 * Dunno if it really does anything useful.
3235 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3239 int gcOk = YAFFS_OK;
3242 int checkpointBlockAdjust;
3244 if (dev->isDoingGC) {
3245 /* Bail out so we don't get recursive gc */
3249 /* This loop should pass the first time.
3250 * We'll only see looping here if the erase of the collected block fails.
3256 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3257 if (checkpointBlockAdjust < 0)
3258 checkpointBlockAdjust = 0;
3260 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3261 /* We need a block soon...*/
3264 /* We're in no hurry */
3268 if (dev->gcBlock <= 0) {
3269 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3273 block = dev->gcBlock;
3276 dev->garbageCollections++;
3278 dev->passiveGarbageCollections++;
3282 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3283 dev->nErasedBlocks, aggressive));
3285 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3288 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3291 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3292 TENDSTR), dev->nErasedBlocks, maxTries, block));
3294 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3298 return aggressive ? gcOk : YAFFS_OK;
3301 /*------------------------- TAGS --------------------------------*/
3303 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3306 return (tags->chunkId == chunkInObject &&
3307 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3312 /*-------------------- Data file manipulation -----------------*/
3314 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3315 yaffs_ExtendedTags *tags)
3317 /*Get the Tnode, then get the level 0 offset chunk offset */
3320 yaffs_ExtendedTags localTags;
3323 yaffs_Device *dev = in->myDev;
3326 /* Passed a NULL, so use our own tags space */
3330 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3333 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3336 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3342 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3343 yaffs_ExtendedTags *tags)
3345 /* Get the Tnode, then get the level 0 offset chunk offset */
3348 yaffs_ExtendedTags localTags;
3350 yaffs_Device *dev = in->myDev;
3354 /* Passed a NULL, so use our own tags space */
3358 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3362 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3365 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3368 /* Delete the entry in the filestructure (if found) */
3370 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3376 #ifdef YAFFS_PARANOID
3378 static int yaffs_CheckFileSanity(yaffs_Object *in)
3386 yaffs_Tags localTags;
3387 yaffs_Tags *tags = &localTags;
3391 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3394 objId = in->objectId;
3395 fSize = in->variant.fileVariant.fileSize;
3397 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3399 for (chunk = 1; chunk <= nChunks; chunk++) {
3400 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3405 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3407 if (yaffs_CheckChunkBits
3408 (dev, theChunk / dev->nChunksPerBlock,
3409 theChunk % dev->nChunksPerBlock)) {
3411 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3415 (tags, in->objectId, chunk, chunkDeleted)) {
3425 /* T(("No level 0 found for %d\n", chunk)); */
3429 return failed ? YAFFS_FAIL : YAFFS_OK;
3434 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3435 int chunkInNAND, int inScan)
3437 /* NB inScan is zero unless scanning.
3438 * For forward scanning, inScan is > 0;
3439 * for backward scanning inScan is < 0
3441 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3445 yaffs_Device *dev = in->myDev;
3447 yaffs_ExtendedTags existingTags;
3448 yaffs_ExtendedTags newTags;
3449 unsigned existingSerial, newSerial;
3451 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3452 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3453 * If it is not during Scanning then something went wrong!
3456 T(YAFFS_TRACE_ERROR,
3458 ("yaffs tragedy:attempt to put data chunk into a non-file"
3463 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3467 tn = yaffs_AddOrFindLevel0Tnode(dev,
3468 &in->variant.fileVariant,
3475 /* Dummy insert, bail now */
3479 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3482 /* If we're scanning then we need to test for duplicates
3483 * NB This does not need to be efficient since it should only ever
3484 * happen when the power fails during a write, then only one
3485 * chunk should ever be affected.
3487 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3488 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3491 if (existingChunk > 0) {
3492 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3493 * thus we have to do a FindChunkInFile to get the real chunk id.
3495 * We have a duplicate now we need to decide which one to use:
3497 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3498 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3499 * YAFFS1: Get both sets of tags and compare serial numbers.
3503 /* Only do this for forward scanning */
3504 yaffs_ReadChunkWithTagsFromNAND(dev,
3508 /* Do a proper find */
3510 yaffs_FindChunkInFile(in, chunkInInode,
3514 if (existingChunk <= 0) {
3515 /*Hoosterman - how did this happen? */
3517 T(YAFFS_TRACE_ERROR,
3519 ("yaffs tragedy: existing chunk < 0 in scan"
3524 /* NB The deleted flags should be false, otherwise the chunks will
3525 * not be loaded during a scan
3529 newSerial = newTags.serialNumber;
3530 existingSerial = existingTags.serialNumber;
3534 (in->myDev->isYaffs2 ||
3535 existingChunk <= 0 ||
3536 ((existingSerial + 1) & 3) == newSerial)) {
3537 /* Forward scanning.
3539 * Delete the old one and drop through to update the tnode
3541 yaffs_DeleteChunk(dev, existingChunk, 1,
3544 /* Backward scanning or we want to use the existing one
3546 * Delete the new one and return early so that the tnode isn't changed
3548 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3556 if (existingChunk == 0)
3559 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3564 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3567 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3569 if (chunkInNAND >= 0)
3570 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3573 T(YAFFS_TRACE_NANDACCESS,
3574 (TSTR("Chunk %d not found zero instead" TENDSTR),
3576 /* get sane (zero) data if you read a hole */
3577 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3583 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3587 yaffs_ExtendedTags tags;
3588 yaffs_BlockInfo *bi;
3594 block = chunkId / dev->nChunksPerBlock;
3595 page = chunkId % dev->nChunksPerBlock;
3598 if (!yaffs_CheckChunkBit(dev, block, page))
3599 T(YAFFS_TRACE_VERIFY,
3600 (TSTR("Deleting invalid chunk %d"TENDSTR),
3603 bi = yaffs_GetBlockInfo(dev, block);
3605 T(YAFFS_TRACE_DELETION,
3606 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3609 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3611 yaffs_InitialiseTags(&tags);
3613 tags.chunkDeleted = 1;
3615 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3616 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3618 dev->nUnmarkedDeletions++;
3621 /* Pull out of the management area.
3622 * If the whole block became dirty, this will kick off an erasure.
3624 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3625 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3626 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3627 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3630 yaffs_ClearChunkBit(dev, block, page);
3634 if (bi->pagesInUse == 0 &&
3635 !bi->hasShrinkHeader &&
3636 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3637 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3638 yaffs_BlockBecameDirty(dev, block);
3645 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3646 const __u8 *buffer, int nBytes,
3649 /* Find old chunk Need to do this to get serial number
3650 * Write new one and patch into tree.
3651 * Invalidate old tags.
3655 yaffs_ExtendedTags prevTags;
3658 yaffs_ExtendedTags newTags;
3660 yaffs_Device *dev = in->myDev;
3662 yaffs_CheckGarbageCollection(dev);
3664 /* Get the previous chunk at this location in the file if it exists */
3665 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3667 /* Set up new tags */
3668 yaffs_InitialiseTags(&newTags);
3670 newTags.chunkId = chunkInInode;
3671 newTags.objectId = in->objectId;
3672 newTags.serialNumber =
3673 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3674 newTags.byteCount = nBytes;
3676 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3677 T(YAFFS_TRACE_ERROR,
3678 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3683 * If there isn't already a chunk there then do a dummy
3684 * insert to make sue we have the desired tnode structure.
3686 if(prevChunkId < 1 &&
3687 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3691 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3694 if (newChunkId > 0) {
3695 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3697 if (prevChunkId > 0)
3698 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3700 yaffs_CheckFileSanity(in);
3706 /* UpdateObjectHeader updates the header on NAND for an object.
3707 * If name is not NULL, then that new name is used.
3709 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3710 int isShrink, int shadows)
3713 yaffs_BlockInfo *bi;
3715 yaffs_Device *dev = in->myDev;
3722 yaffs_ExtendedTags newTags;
3723 yaffs_ExtendedTags oldTags;
3724 YCHAR *alias = NULL;
3726 __u8 *buffer = NULL;
3727 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3729 yaffs_ObjectHeader *oh = NULL;
3731 yaffs_strcpy(oldName, _Y("silly old name"));
3735 in == dev->rootDir || /* The rootDir should also be saved */
3738 yaffs_CheckGarbageCollection(dev);
3739 yaffs_CheckObjectDetailsLoaded(in);
3741 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3742 oh = (yaffs_ObjectHeader *) buffer;
3744 prevChunkId = in->hdrChunk;
3746 if (prevChunkId > 0) {
3747 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3750 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3752 memcpy(oldName, oh->name, sizeof(oh->name));
3755 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3757 oh->type = in->variantType;
3758 oh->yst_mode = in->yst_mode;
3759 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3761 #ifdef CONFIG_YAFFS_WINCE
3762 oh->win_atime[0] = in->win_atime[0];
3763 oh->win_ctime[0] = in->win_ctime[0];
3764 oh->win_mtime[0] = in->win_mtime[0];
3765 oh->win_atime[1] = in->win_atime[1];
3766 oh->win_ctime[1] = in->win_ctime[1];
3767 oh->win_mtime[1] = in->win_mtime[1];
3769 oh->yst_uid = in->yst_uid;
3770 oh->yst_gid = in->yst_gid;
3771 oh->yst_atime = in->yst_atime;
3772 oh->yst_mtime = in->yst_mtime;
3773 oh->yst_ctime = in->yst_ctime;
3774 oh->yst_rdev = in->yst_rdev;
3777 oh->parentObjectId = in->parent->objectId;
3779 oh->parentObjectId = 0;
3781 if (name && *name) {
3782 memset(oh->name, 0, sizeof(oh->name));
3783 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3784 } else if (prevChunkId > 0)
3785 memcpy(oh->name, oldName, sizeof(oh->name));
3787 memset(oh->name, 0, sizeof(oh->name));
3789 oh->isShrink = isShrink;
3791 switch (in->variantType) {
3792 case YAFFS_OBJECT_TYPE_UNKNOWN:
3793 /* Should not happen */
3795 case YAFFS_OBJECT_TYPE_FILE:
3797 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3798 || oh->parentObjectId ==
3799 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3800 fileVariant.fileSize;
3802 case YAFFS_OBJECT_TYPE_HARDLINK:
3803 oh->equivalentObjectId =
3804 in->variant.hardLinkVariant.equivalentObjectId;
3806 case YAFFS_OBJECT_TYPE_SPECIAL:
3809 case YAFFS_OBJECT_TYPE_DIRECTORY:
3812 case YAFFS_OBJECT_TYPE_SYMLINK:
3813 alias = in->variant.symLinkVariant.alias;
3815 alias = _Y("no alias");
3816 yaffs_strncpy(oh->alias,
3818 YAFFS_MAX_ALIAS_LENGTH);
3819 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3824 yaffs_InitialiseTags(&newTags);
3826 newTags.chunkId = 0;
3827 newTags.objectId = in->objectId;
3828 newTags.serialNumber = in->serial;
3830 /* Add extra info for file header */
3832 newTags.extraHeaderInfoAvailable = 1;
3833 newTags.extraParentObjectId = oh->parentObjectId;
3834 newTags.extraFileLength = oh->fileSize;
3835 newTags.extraIsShrinkHeader = oh->isShrink;
3836 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3837 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3838 newTags.extraObjectType = in->variantType;
3840 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3842 /* Create new chunk in NAND */
3844 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3845 (prevChunkId > 0) ? 1 : 0);
3847 if (newChunkId >= 0) {
3849 in->hdrChunk = newChunkId;
3851 if (prevChunkId > 0) {
3852 yaffs_DeleteChunk(dev, prevChunkId, 1,
3856 if (!yaffs_ObjectHasCachedWriteData(in))
3859 /* If this was a shrink, then mark the block that the chunk lives on */
3861 bi = yaffs_GetBlockInfo(in->myDev,
3862 newChunkId / in->myDev->nChunksPerBlock);
3863 bi->hasShrinkHeader = 1;
3868 retVal = newChunkId;
3873 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3878 /*------------------------ Short Operations Cache ----------------------------------------
3879 * In many situations where there is no high level buffering (eg WinCE) a lot of
3880 * reads might be short sequential reads, and a lot of writes may be short
3881 * sequential writes. eg. scanning/writing a jpeg file.
3882 * In these cases, a short read/write cache can provide a huge perfomance benefit
3883 * with dumb-as-a-rock code.
3884 * In Linux, the page cache provides read buffering aand the short op cache provides write
3887 * There are a limited number (~10) of cache chunks per device so that we don't
3888 * need a very intelligent search.
3891 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3893 yaffs_Device *dev = obj->myDev;
3895 yaffs_ChunkCache *cache;
3896 int nCaches = obj->myDev->nShortOpCaches;
3898 for (i = 0; i < nCaches; i++) {
3899 cache = &dev->srCache[i];
3900 if (cache->object == obj &&
3909 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3911 yaffs_Device *dev = obj->myDev;
3912 int lowest = -99; /* Stop compiler whining. */
3914 yaffs_ChunkCache *cache;
3915 int chunkWritten = 0;
3916 int nCaches = obj->myDev->nShortOpCaches;
3922 /* Find the dirty cache for this object with the lowest chunk id. */
3923 for (i = 0; i < nCaches; i++) {
3924 if (dev->srCache[i].object == obj &&
3925 dev->srCache[i].dirty) {
3927 || dev->srCache[i].chunkId <
3929 cache = &dev->srCache[i];
3930 lowest = cache->chunkId;
3935 if (cache && !cache->locked) {
3936 /* Write it out and free it up */
3939 yaffs_WriteChunkDataToObject(cache->object,
3945 cache->object = NULL;
3948 } while (cache && chunkWritten > 0);
3951 /* Hoosterman, disk full while writing cache out. */
3952 T(YAFFS_TRACE_ERROR,
3953 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3960 /*yaffs_FlushEntireDeviceCache(dev)
3965 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3968 int nCaches = dev->nShortOpCaches;
3971 /* Find a dirty object in the cache and flush it...
3972 * until there are no further dirty objects.
3976 for (i = 0; i < nCaches && !obj; i++) {
3977 if (dev->srCache[i].object &&
3978 dev->srCache[i].dirty)
3979 obj = dev->srCache[i].object;
3983 yaffs_FlushFilesChunkCache(obj);
3990 /* Grab us a cache chunk for use.
3991 * First look for an empty one.
3992 * Then look for the least recently used non-dirty one.
3993 * Then look for the least recently used dirty one...., flush and look again.
3995 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3999 if (dev->nShortOpCaches > 0) {
4000 for (i = 0; i < dev->nShortOpCaches; i++) {
4001 if (!dev->srCache[i].object)
4002 return &dev->srCache[i];
4009 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4011 yaffs_ChunkCache *cache;
4012 yaffs_Object *theObj;
4017 if (dev->nShortOpCaches > 0) {
4018 /* Try find a non-dirty one... */
4020 cache = yaffs_GrabChunkCacheWorker(dev);
4023 /* They were all dirty, find the last recently used object and flush
4024 * its cache, then find again.
4025 * NB what's here is not very accurate, we actually flush the object
4026 * the last recently used page.
4029 /* With locking we can't assume we can use entry zero */
4036 for (i = 0; i < dev->nShortOpCaches; i++) {
4037 if (dev->srCache[i].object &&
4038 !dev->srCache[i].locked &&
4039 (dev->srCache[i].lastUse < usage || !cache)) {
4040 usage = dev->srCache[i].lastUse;
4041 theObj = dev->srCache[i].object;
4042 cache = &dev->srCache[i];
4047 if (!cache || cache->dirty) {
4048 /* Flush and try again */
4049 yaffs_FlushFilesChunkCache(theObj);
4050 cache = yaffs_GrabChunkCacheWorker(dev);
4060 /* Find a cached chunk */
4061 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4064 yaffs_Device *dev = obj->myDev;
4066 if (dev->nShortOpCaches > 0) {
4067 for (i = 0; i < dev->nShortOpCaches; i++) {
4068 if (dev->srCache[i].object == obj &&
4069 dev->srCache[i].chunkId == chunkId) {
4072 return &dev->srCache[i];
4079 /* Mark the chunk for the least recently used algorithym */
4080 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4084 if (dev->nShortOpCaches > 0) {
4085 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4086 /* Reset the cache usages */
4088 for (i = 1; i < dev->nShortOpCaches; i++)
4089 dev->srCache[i].lastUse = 0;
4096 cache->lastUse = dev->srLastUse;
4103 /* Invalidate a single cache page.
4104 * Do this when a whole page gets written,
4105 * ie the short cache for this page is no longer valid.
4107 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4109 if (object->myDev->nShortOpCaches > 0) {
4110 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4113 cache->object = NULL;
4117 /* Invalidate all the cache pages associated with this object
4118 * Do this whenever ther file is deleted or resized.
4120 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4123 yaffs_Device *dev = in->myDev;
4125 if (dev->nShortOpCaches > 0) {
4126 /* Invalidate it. */
4127 for (i = 0; i < dev->nShortOpCaches; i++) {
4128 if (dev->srCache[i].object == in)
4129 dev->srCache[i].object = NULL;
4134 /*--------------------- Checkpointing --------------------*/
4137 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4139 yaffs_CheckpointValidity cp;
4141 memset(&cp, 0, sizeof(cp));
4143 cp.structType = sizeof(cp);
4144 cp.magic = YAFFS_MAGIC;
4145 cp.version = YAFFS_CHECKPOINT_VERSION;
4146 cp.head = (head) ? 1 : 0;
4148 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4152 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4154 yaffs_CheckpointValidity cp;
4157 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4160 ok = (cp.structType == sizeof(cp)) &&
4161 (cp.magic == YAFFS_MAGIC) &&
4162 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4163 (cp.head == ((head) ? 1 : 0));
4167 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4170 cp->nErasedBlocks = dev->nErasedBlocks;
4171 cp->allocationBlock = dev->allocationBlock;
4172 cp->allocationPage = dev->allocationPage;
4173 cp->nFreeChunks = dev->nFreeChunks;
4175 cp->nDeletedFiles = dev->nDeletedFiles;
4176 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4177 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4178 cp->sequenceNumber = dev->sequenceNumber;
4179 cp->oldestDirtySequence = dev->oldestDirtySequence;
4183 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4184 yaffs_CheckpointDevice *cp)
4186 dev->nErasedBlocks = cp->nErasedBlocks;
4187 dev->allocationBlock = cp->allocationBlock;
4188 dev->allocationPage = cp->allocationPage;
4189 dev->nFreeChunks = cp->nFreeChunks;
4191 dev->nDeletedFiles = cp->nDeletedFiles;
4192 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4193 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4194 dev->sequenceNumber = cp->sequenceNumber;
4195 dev->oldestDirtySequence = cp->oldestDirtySequence;
4199 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4201 yaffs_CheckpointDevice cp;
4203 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4207 /* Write device runtime values*/
4208 yaffs_DeviceToCheckpointDevice(&cp, dev);
4209 cp.structType = sizeof(cp);
4211 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4213 /* Write block info */
4215 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4216 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4219 /* Write chunk bits */
4221 nBytes = nBlocks * dev->chunkBitmapStride;
4222 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4228 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4230 yaffs_CheckpointDevice cp;
4232 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4236 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4240 if (cp.structType != sizeof(cp))
4244 yaffs_CheckpointDeviceToDevice(dev, &cp);
4246 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4248 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4252 nBytes = nBlocks * dev->chunkBitmapStride;
4254 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4259 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4263 cp->objectId = obj->objectId;
4264 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4265 cp->hdrChunk = obj->hdrChunk;
4266 cp->variantType = obj->variantType;
4267 cp->deleted = obj->deleted;
4268 cp->softDeleted = obj->softDeleted;
4269 cp->unlinked = obj->unlinked;
4270 cp->fake = obj->fake;
4271 cp->renameAllowed = obj->renameAllowed;
4272 cp->unlinkAllowed = obj->unlinkAllowed;
4273 cp->serial = obj->serial;
4274 cp->nDataChunks = obj->nDataChunks;
4276 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4277 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4278 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4279 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4282 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4285 yaffs_Object *parent;
4287 if (obj->variantType != cp->variantType) {
4288 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4289 TCONT("chunk %d does not match existing object type %d")
4290 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4295 obj->objectId = cp->objectId;
4298 parent = yaffs_FindOrCreateObjectByNumber(
4301 YAFFS_OBJECT_TYPE_DIRECTORY);
4306 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4307 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4308 TCONT(" chunk %d Parent type, %d, not directory")
4310 cp->objectId, cp->parentId, cp->variantType,
4311 cp->hdrChunk, parent->variantType));
4314 yaffs_AddObjectToDirectory(parent, obj);
4317 obj->hdrChunk = cp->hdrChunk;
4318 obj->variantType = cp->variantType;
4319 obj->deleted = cp->deleted;
4320 obj->softDeleted = cp->softDeleted;
4321 obj->unlinked = cp->unlinked;
4322 obj->fake = cp->fake;
4323 obj->renameAllowed = cp->renameAllowed;
4324 obj->unlinkAllowed = cp->unlinkAllowed;
4325 obj->serial = cp->serial;
4326 obj->nDataChunks = cp->nDataChunks;
4328 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4329 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4330 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4331 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4333 if (obj->hdrChunk > 0)
4334 obj->lazyLoaded = 1;
4340 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4341 __u32 level, int chunkOffset)
4344 yaffs_Device *dev = in->myDev;
4346 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4348 if (tnodeSize < sizeof(yaffs_Tnode))
4349 tnodeSize = sizeof(yaffs_Tnode);
4355 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4356 if (tn->internal[i]) {
4357 ok = yaffs_CheckpointTnodeWorker(in,
4360 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4363 } else if (level == 0) {
4364 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4365 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4367 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4375 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4377 __u32 endMarker = ~0;
4380 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4381 ok = yaffs_CheckpointTnodeWorker(obj,
4382 obj->variant.fileVariant.top,
4383 obj->variant.fileVariant.topLevel,
4386 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4393 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4397 yaffs_Device *dev = obj->myDev;
4398 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4401 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4403 if (tnodeSize < sizeof(yaffs_Tnode))
4404 tnodeSize = sizeof(yaffs_Tnode);
4406 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4408 while (ok && (~baseChunk)) {
4410 /* Read level 0 tnode */
4413 tn = yaffs_GetTnodeRaw(dev);
4415 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4420 ok = yaffs_AddOrFindLevel0Tnode(dev,
4426 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4430 T(YAFFS_TRACE_CHECKPOINT, (
4431 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4432 nread, baseChunk, ok));
4438 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4441 yaffs_CheckpointObject cp;
4444 struct ylist_head *lh;
4447 /* Iterate through the objects in each hash entry,
4448 * dumping them to the checkpointing stream.
4451 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4452 ylist_for_each(lh, &dev->objectBucket[i].list) {
4454 obj = ylist_entry(lh, yaffs_Object, hashLink);
4455 if (!obj->deferedFree) {
4456 yaffs_ObjectToCheckpointObject(&cp, obj);
4457 cp.structType = sizeof(cp);
4459 T(YAFFS_TRACE_CHECKPOINT, (
4460 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4461 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, (unsigned) obj));
4463 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4465 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4466 ok = yaffs_WriteCheckpointTnodes(obj);
4472 /* Dump end of list */
4473 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4474 cp.structType = sizeof(cp);
4477 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4482 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4485 yaffs_CheckpointObject cp;
4488 yaffs_Object *hardList = NULL;
4490 while (ok && !done) {
4491 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4492 if (cp.structType != sizeof(cp)) {
4493 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4494 cp.structType, sizeof(cp), ok));
4498 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4499 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4501 if (ok && cp.objectId == ~0)
4504 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4506 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4509 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4510 ok = yaffs_ReadCheckpointTnodes(obj);
4511 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4512 obj->hardLinks.next =
4513 (struct ylist_head *) hardList;
4522 yaffs_HardlinkFixup(dev, hardList);
4527 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4529 __u32 checkpointSum;
4532 yaffs_GetCheckpointSum(dev, &checkpointSum);
4534 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4542 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4544 __u32 checkpointSum0;
4545 __u32 checkpointSum1;
4548 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4550 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4555 if (checkpointSum0 != checkpointSum1)
4562 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4566 if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4567 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4572 ok = yaffs_CheckpointOpen(dev, 1);
4575 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4576 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4579 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4580 ok = yaffs_WriteCheckpointDevice(dev);
4583 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4584 ok = yaffs_WriteCheckpointObjects(dev);
4587 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4588 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4592 ok = yaffs_WriteCheckpointSum(dev);
4594 if (!yaffs_CheckpointClose(dev))
4598 dev->isCheckpointed = 1;
4600 dev->isCheckpointed = 0;
4602 return dev->isCheckpointed;
4605 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4609 if (dev->skipCheckpointRead || !dev->isYaffs2) {
4610 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4615 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4618 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4619 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4622 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4623 ok = yaffs_ReadCheckpointDevice(dev);
4626 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4627 ok = yaffs_ReadCheckpointObjects(dev);
4630 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4631 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4635 ok = yaffs_ReadCheckpointSum(dev);
4636 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4639 if (!yaffs_CheckpointClose(dev))
4643 dev->isCheckpointed = 1;
4645 dev->isCheckpointed = 0;
4651 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4653 if (dev->isCheckpointed ||
4654 dev->blocksInCheckpoint > 0) {
4655 dev->isCheckpointed = 0;
4656 yaffs_CheckpointInvalidateStream(dev);
4657 if (dev->superBlock && dev->markSuperBlockDirty)
4658 dev->markSuperBlockDirty(dev->superBlock);
4663 int yaffs_CheckpointSave(yaffs_Device *dev)
4666 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4668 yaffs_VerifyObjects(dev);
4669 yaffs_VerifyBlocks(dev);
4670 yaffs_VerifyFreeChunks(dev);
4672 if (!dev->isCheckpointed) {
4673 yaffs_InvalidateCheckpoint(dev);
4674 yaffs_WriteCheckpointData(dev);
4677 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4679 return dev->isCheckpointed;
4682 int yaffs_CheckpointRestore(yaffs_Device *dev)
4685 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4687 retval = yaffs_ReadCheckpointData(dev);
4689 if (dev->isCheckpointed) {
4690 yaffs_VerifyObjects(dev);
4691 yaffs_VerifyBlocks(dev);
4692 yaffs_VerifyFreeChunks(dev);
4695 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4700 /*--------------------- File read/write ------------------------
4701 * Read and write have very similar structures.
4702 * In general the read/write has three parts to it
4703 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4704 * Some complete chunks
4705 * An incomplete chunk to end off with
4707 * Curve-balls: the first chunk might also be the last chunk.
4710 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4719 yaffs_ChunkCache *cache;
4726 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4727 /* start = offset % dev->nDataBytesPerChunk; */
4728 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4731 /* OK now check for the curveball where the start and end are in
4734 if ((start + n) < dev->nDataBytesPerChunk)
4737 nToCopy = dev->nDataBytesPerChunk - start;
4739 cache = yaffs_FindChunkCache(in, chunk);
4741 /* If the chunk is already in the cache or it is less than a whole chunk
4742 * or we're using inband tags then use the cache (if there is caching)
4743 * else bypass the cache.
4745 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4746 if (dev->nShortOpCaches > 0) {
4748 /* If we can't find the data in the cache, then load it up. */
4751 cache = yaffs_GrabChunkCache(in->myDev);
4753 cache->chunkId = chunk;
4756 yaffs_ReadChunkDataFromObject(in, chunk,
4762 yaffs_UseChunkCache(dev, cache, 0);
4767 memcpy(buffer, &cache->data[start], nToCopy);
4771 /* Read into the local buffer then copy..*/
4774 yaffs_GetTempBuffer(dev, __LINE__);
4775 yaffs_ReadChunkDataFromObject(in, chunk,
4778 memcpy(buffer, &localBuffer[start], nToCopy);
4781 yaffs_ReleaseTempBuffer(dev, localBuffer,
4787 /* A full chunk. Read directly into the supplied buffer. */
4788 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4802 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4803 int nBytes, int writeThrough)
4812 int startOfWrite = offset;
4813 int chunkWritten = 0;
4821 while (n > 0 && chunkWritten >= 0) {
4822 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4823 /* start = offset % dev->nDataBytesPerChunk; */
4824 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4826 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4827 start >= dev->nDataBytesPerChunk) {
4828 T(YAFFS_TRACE_ERROR, (
4829 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4831 (int)offset, chunk, start));
4835 /* OK now check for the curveball where the start and end are in
4839 if ((start + n) < dev->nDataBytesPerChunk) {
4842 /* Now folks, to calculate how many bytes to write back....
4843 * If we're overwriting and not writing to then end of file then
4844 * we need to write back as much as was there before.
4847 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4849 if (chunkStart > in->variant.fileVariant.fileSize)
4850 nBytesRead = 0; /* Past end of file */
4852 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4854 if (nBytesRead > dev->nDataBytesPerChunk)
4855 nBytesRead = dev->nDataBytesPerChunk;
4859 (start + n)) ? nBytesRead : (start + n);
4861 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4865 nToCopy = dev->nDataBytesPerChunk - start;
4866 nToWriteBack = dev->nDataBytesPerChunk;
4869 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4870 /* An incomplete start or end chunk (or maybe both start and end chunk),
4871 * or we're using inband tags, so we want to use the cache buffers.
4873 if (dev->nShortOpCaches > 0) {
4874 yaffs_ChunkCache *cache;
4875 /* If we can't find the data in the cache, then load the cache */
4876 cache = yaffs_FindChunkCache(in, chunk);
4879 && yaffs_CheckSpaceForAllocation(in->
4881 cache = yaffs_GrabChunkCache(in->myDev);
4883 cache->chunkId = chunk;
4886 yaffs_ReadChunkDataFromObject(in, chunk,
4891 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4892 /* Drop the cache if it was a read cache item and
4893 * no space check has been made for it.
4899 yaffs_UseChunkCache(dev, cache, 1);
4903 memcpy(&cache->data[start], buffer,
4908 cache->nBytes = nToWriteBack;
4912 yaffs_WriteChunkDataToObject
4915 cache->data, cache->nBytes,
4921 chunkWritten = -1; /* fail the write */
4924 /* An incomplete start or end chunk (or maybe both start and end chunk)
4925 * Read into the local buffer then copy, then copy over and write back.
4929 yaffs_GetTempBuffer(dev, __LINE__);
4931 yaffs_ReadChunkDataFromObject(in, chunk,
4936 memcpy(&localBuffer[start], buffer, nToCopy);
4939 yaffs_WriteChunkDataToObject(in, chunk,
4944 yaffs_ReleaseTempBuffer(dev, localBuffer,
4950 /* A full chunk. Write directly from the supplied buffer. */
4955 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4956 dev->nDataBytesPerChunk,
4959 /* Since we've overwritten the cached data, we better invalidate it. */
4960 yaffs_InvalidateChunkCache(in, chunk);
4963 if (chunkWritten >= 0) {
4972 /* Update file object */
4974 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
4975 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4983 /* ---------------------- File resizing stuff ------------------ */
4985 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4988 yaffs_Device *dev = in->myDev;
4989 int oldFileSize = in->variant.fileVariant.fileSize;
4991 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4993 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4994 dev->nDataBytesPerChunk;
4998 /* Delete backwards so that we don't end up with holes if
4999 * power is lost part-way through the operation.
5001 for (i = lastDel; i >= startDel; i--) {
5002 /* NB this could be optimised somewhat,
5003 * eg. could retrieve the tags and write them without
5004 * using yaffs_DeleteChunk
5007 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5010 (dev->internalStartBlock * dev->nChunksPerBlock)
5012 ((dev->internalEndBlock +
5013 1) * dev->nChunksPerBlock)) {
5014 T(YAFFS_TRACE_ALWAYS,
5015 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5019 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5026 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5029 int oldFileSize = in->variant.fileVariant.fileSize;
5030 __u32 newSizeOfPartialChunk;
5033 yaffs_Device *dev = in->myDev;
5035 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5037 yaffs_FlushFilesChunkCache(in);
5038 yaffs_InvalidateWholeChunkCache(in);
5040 yaffs_CheckGarbageCollection(dev);
5042 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5045 if (newSize == oldFileSize)
5048 if (newSize < oldFileSize) {
5050 yaffs_PruneResizedChunks(in, newSize);
5052 if (newSizeOfPartialChunk != 0) {
5053 int lastChunk = 1 + newFullChunks;
5055 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5057 /* Got to read and rewrite the last chunk with its new size and zero pad */
5058 yaffs_ReadChunkDataFromObject(in, lastChunk,
5061 memset(localBuffer + newSizeOfPartialChunk, 0,
5062 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5064 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5065 newSizeOfPartialChunk, 1);
5067 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5070 in->variant.fileVariant.fileSize = newSize;
5072 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5074 /* newsSize > oldFileSize */
5075 in->variant.fileVariant.fileSize = newSize;
5079 /* Write a new object header to reflect the resize.
5080 * show we've shrunk the file, if need be
5081 * Do this only if the file is not in the deleted directories
5082 * and is not shadowed.
5086 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5087 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5088 yaffs_UpdateObjectHeader(in, NULL, 0,
5089 (newSize < oldFileSize) ? 1 : 0, 0);
5094 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5096 YCHAR *alias = NULL;
5097 obj = yaffs_GetEquivalentObject(obj);
5099 switch (obj->variantType) {
5100 case YAFFS_OBJECT_TYPE_FILE:
5101 return obj->variant.fileVariant.fileSize;
5102 case YAFFS_OBJECT_TYPE_SYMLINK:
5103 alias = obj->variant.symLinkVariant.alias;
5106 return yaffs_strlen(alias);
5114 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5118 yaffs_FlushFilesChunkCache(in);
5119 if(dataSync) /* Only sync data */
5123 #ifdef CONFIG_YAFFS_WINCE
5124 yfsd_WinFileTimeNow(in->win_mtime);
5127 in->yst_mtime = Y_CURRENT_TIME;
5132 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5133 0) ? YAFFS_OK : YAFFS_FAIL;
5143 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5146 /* First off, invalidate the file's data in the cache, without flushing. */
5147 yaffs_InvalidateWholeChunkCache(in);
5149 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5150 /* Move to the unlinked directory so we have a record that it was deleted. */
5151 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5155 yaffs_RemoveObjectFromDirectory(in);
5156 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5159 yaffs_FreeObject(in);
5164 /* yaffs_DeleteFile deletes the whole file data
5165 * and the inode associated with the file.
5166 * It does not delete the links associated with the file.
5168 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5172 int immediateDeletion = 0;
5176 immediateDeletion = 1;
5179 immediateDeletion = 1;
5182 if (immediateDeletion) {
5184 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5185 _Y("deleted"), 0, 0);
5186 T(YAFFS_TRACE_TRACING,
5187 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5190 in->myDev->nDeletedFiles++;
5191 if (1 || in->myDev->isYaffs2)
5192 yaffs_ResizeFile(in, 0);
5193 yaffs_SoftDeleteFile(in);
5196 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5197 _Y("unlinked"), 0, 0);
5204 int yaffs_DeleteFile(yaffs_Object *in)
5206 int retVal = YAFFS_OK;
5207 int deleted = in->deleted;
5209 yaffs_ResizeFile(in, 0);
5211 if (in->nDataChunks > 0) {
5212 /* Use soft deletion if there is data in the file.
5213 * That won't be the case if it has been resized to zero.
5216 retVal = yaffs_UnlinkFileIfNeeded(in);
5218 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5221 in->myDev->nDeletedFiles++;
5222 yaffs_SoftDeleteFile(in);
5224 return deleted ? YAFFS_OK : YAFFS_FAIL;
5226 /* The file has no data chunks so we toss it immediately */
5227 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5228 in->variant.fileVariant.top = NULL;
5229 yaffs_DoGenericObjectDeletion(in);
5235 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5237 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5238 !(ylist_empty(&obj->variant.directoryVariant.children));
5241 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5243 /* First check that the directory is empty. */
5244 if (yaffs_IsNonEmptyDirectory(obj))
5247 return yaffs_DoGenericObjectDeletion(obj);
5250 static int yaffs_DeleteSymLink(yaffs_Object *in)
5252 if(in->variant.symLinkVariant.alias)
5253 YFREE(in->variant.symLinkVariant.alias);
5254 in->variant.symLinkVariant.alias=NULL;
5256 return yaffs_DoGenericObjectDeletion(in);
5259 static int yaffs_DeleteHardLink(yaffs_Object *in)
5261 /* remove this hardlink from the list assocaited with the equivalent
5264 ylist_del_init(&in->hardLinks);
5265 return yaffs_DoGenericObjectDeletion(in);
5268 int yaffs_DeleteObject(yaffs_Object *obj)
5271 switch (obj->variantType) {
5272 case YAFFS_OBJECT_TYPE_FILE:
5273 retVal = yaffs_DeleteFile(obj);
5275 case YAFFS_OBJECT_TYPE_DIRECTORY:
5276 return yaffs_DeleteDirectory(obj);
5278 case YAFFS_OBJECT_TYPE_SYMLINK:
5279 retVal = yaffs_DeleteSymLink(obj);
5281 case YAFFS_OBJECT_TYPE_HARDLINK:
5282 retVal = yaffs_DeleteHardLink(obj);
5284 case YAFFS_OBJECT_TYPE_SPECIAL:
5285 retVal = yaffs_DoGenericObjectDeletion(obj);
5287 case YAFFS_OBJECT_TYPE_UNKNOWN:
5289 break; /* should not happen. */
5295 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5298 int immediateDeletion = 0;
5302 immediateDeletion = 1;
5304 if (obj->inUse <= 0)
5305 immediateDeletion = 1;
5309 yaffs_UpdateParent(obj->parent);
5311 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5312 return yaffs_DeleteHardLink(obj);
5313 } else if (!ylist_empty(&obj->hardLinks)) {
5314 /* Curve ball: We're unlinking an object that has a hardlink.
5316 * This problem arises because we are not strictly following
5317 * The Linux link/inode model.
5319 * We can't really delete the object.
5320 * Instead, we do the following:
5321 * - Select a hardlink.
5322 * - Unhook it from the hard links
5323 * - Unhook it from its parent directory (so that the rename can work)
5324 * - Rename the object to the hardlink's name.
5325 * - Delete the hardlink
5330 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5332 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5334 ylist_del_init(&hl->hardLinks);
5335 ylist_del_init(&hl->siblings);
5337 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5339 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5341 if (retVal == YAFFS_OK)
5342 retVal = yaffs_DoGenericObjectDeletion(hl);
5346 } else if (immediateDeletion) {
5347 switch (obj->variantType) {
5348 case YAFFS_OBJECT_TYPE_FILE:
5349 return yaffs_DeleteFile(obj);
5351 case YAFFS_OBJECT_TYPE_DIRECTORY:
5352 return yaffs_DeleteDirectory(obj);
5354 case YAFFS_OBJECT_TYPE_SYMLINK:
5355 return yaffs_DeleteSymLink(obj);
5357 case YAFFS_OBJECT_TYPE_SPECIAL:
5358 return yaffs_DoGenericObjectDeletion(obj);
5360 case YAFFS_OBJECT_TYPE_HARDLINK:
5361 case YAFFS_OBJECT_TYPE_UNKNOWN:
5365 } else if(yaffs_IsNonEmptyDirectory(obj))
5368 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5369 _Y("unlinked"), 0, 0);
5373 static int yaffs_UnlinkObject(yaffs_Object *obj)
5376 if (obj && obj->unlinkAllowed)
5377 return yaffs_UnlinkWorker(obj);
5382 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5386 obj = yaffs_FindObjectByName(dir, name);
5387 return yaffs_UnlinkObject(obj);
5390 /*----------------------- Initialisation Scanning ---------------------- */
5392 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5393 int backwardScanning)
5397 if (!backwardScanning) {
5398 /* Handle YAFFS1 forward scanning case
5399 * For YAFFS1 we always do the deletion
5403 /* Handle YAFFS2 case (backward scanning)
5404 * If the shadowed object exists then ignore.
5406 obj = yaffs_FindObjectByNumber(dev, objId);
5411 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5412 * We put it in unlinked dir to be cleaned up after the scanning
5415 yaffs_FindOrCreateObjectByNumber(dev, objId,
5416 YAFFS_OBJECT_TYPE_FILE);
5419 obj->isShadowed = 1;
5420 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5421 obj->variant.fileVariant.shrinkSize = 0;
5422 obj->valid = 1; /* So that we don't read any other info for this file */
5432 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5439 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5441 in = yaffs_FindObjectByNumber(dev,
5442 hl->variant.hardLinkVariant.
5443 equivalentObjectId);
5446 /* Add the hardlink pointers */
5447 hl->variant.hardLinkVariant.equivalentObject = in;
5448 ylist_add(&hl->hardLinks, &in->hardLinks);
5450 /* Todo Need to report/handle this better.
5451 * Got a problem... hardlink to a non-existant object
5453 hl->variant.hardLinkVariant.equivalentObject = NULL;
5454 YINIT_LIST_HEAD(&hl->hardLinks);
5464 static int ybicmp(const void *a, const void *b)
5466 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5467 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5468 register int ablock = ((yaffs_BlockIndex *)a)->block;
5469 register int bblock = ((yaffs_BlockIndex *)b)->block;
5471 return ablock - bblock;
5477 struct yaffs_ShadowFixerStruct {
5480 struct yaffs_ShadowFixerStruct *next;
5484 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5487 * Sort out state of unlinked and deleted objects after scanning.
5489 struct ylist_head *i;
5490 struct ylist_head *n;
5493 /* Soft delete all the unlinked files */
5494 ylist_for_each_safe(i, n,
5495 &dev->unlinkedDir->variant.directoryVariant.children) {
5497 l = ylist_entry(i, yaffs_Object, siblings);
5498 yaffs_DeleteObject(l);
5502 ylist_for_each_safe(i, n,
5503 &dev->deletedDir->variant.directoryVariant.children) {
5505 l = ylist_entry(i, yaffs_Object, siblings);
5506 yaffs_DeleteObject(l);
5513 * This code iterates through all the objects making sure that they are rooted.
5514 * Any unrooted objects are re-rooted in lost+found.
5515 * An object needs to be in one of:
5516 * - Directly under deleted, unlinked
5517 * - Directly or indirectly under root.
5520 * This code assumes that we don't ever change the current relationships between
5522 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5523 * lostNfound->parent == rootDir
5525 * This fixes the problem where directories might have inadvertently been deleted
5526 * leaving the object "hanging" without being rooted in the directory tree.
5529 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5531 return (obj == dev->deletedDir ||
5532 obj == dev->unlinkedDir||
5533 obj == dev->rootDir);
5536 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5539 yaffs_Object *parent;
5541 struct ylist_head *lh;
5542 struct ylist_head *n;
5547 /* Iterate through the objects in each hash entry,
5548 * looking at each object.
5549 * Make sure it is rooted.
5552 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5553 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5555 obj = ylist_entry(lh, yaffs_Object, hashLink);
5556 parent= obj->parent;
5558 if(yaffs_HasNULLParent(dev,obj)){
5559 /* These directories are not hanging */
5562 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5564 else if(yaffs_HasNULLParent(dev,parent))
5568 * Need to follow the parent chain to see if it is hanging.
5573 while(parent != dev->rootDir &&
5575 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5577 parent = parent->parent;
5580 if(parent != dev->rootDir)
5585 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5587 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5596 * Delete directory contents for cleaning up lost and found.
5598 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5601 struct ylist_head *lh;
5602 struct ylist_head *n;
5604 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5607 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5609 obj = ylist_entry(lh, yaffs_Object, siblings);
5610 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5611 yaffs_DeleteDirectoryContents(obj);
5614 (TSTR("Deleting lost_found object %d" TENDSTR),
5617 /* Need to use UnlinkObject since Delete would not handle
5618 * hardlinked objects correctly.
5620 yaffs_UnlinkObject(obj);
5626 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5628 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5631 static int yaffs_Scan(yaffs_Device *dev)
5633 yaffs_ExtendedTags tags;
5643 yaffs_BlockState state;
5644 yaffs_Object *hardList = NULL;
5645 yaffs_BlockInfo *bi;
5646 __u32 sequenceNumber;
5647 yaffs_ObjectHeader *oh;
5649 yaffs_Object *parent;
5651 int alloc_failed = 0;
5653 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5661 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5662 dev->internalStartBlock, dev->internalEndBlock));
5664 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5666 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5668 /* Scan all the blocks to determine their state */
5669 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5670 bi = yaffs_GetBlockInfo(dev, blk);
5671 yaffs_ClearChunkBits(dev, blk);
5673 bi->softDeletions = 0;
5675 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5677 bi->blockState = state;
5678 bi->sequenceNumber = sequenceNumber;
5680 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5681 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5683 T(YAFFS_TRACE_SCAN_DEBUG,
5684 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5685 state, sequenceNumber));
5687 if (state == YAFFS_BLOCK_STATE_DEAD) {
5688 T(YAFFS_TRACE_BAD_BLOCKS,
5689 (TSTR("block %d is bad" TENDSTR), blk));
5690 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5691 T(YAFFS_TRACE_SCAN_DEBUG,
5692 (TSTR("Block empty " TENDSTR)));
5693 dev->nErasedBlocks++;
5694 dev->nFreeChunks += dev->nChunksPerBlock;
5698 startIterator = dev->internalStartBlock;
5699 endIterator = dev->internalEndBlock;
5701 /* For each block.... */
5702 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5709 blk = blockIterator;
5711 bi = yaffs_GetBlockInfo(dev, blk);
5712 state = bi->blockState;
5716 /* For each chunk in each block that needs scanning....*/
5717 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5718 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5719 /* Read the tags and decide what to do */
5720 chunk = blk * dev->nChunksPerBlock + c;
5722 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5725 /* Let's have a good look at this chunk... */
5727 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5733 /*T((" %d %d deleted\n",blk,c)); */
5734 } else if (!tags.chunkUsed) {
5735 /* An unassigned chunk in the block
5736 * This means that either the block is empty or
5737 * this is the one being allocated from
5741 /* We're looking at the first chunk in the block so the block is unused */
5742 state = YAFFS_BLOCK_STATE_EMPTY;
5743 dev->nErasedBlocks++;
5745 /* this is the block being allocated from */
5748 (" Allocating from %d %d" TENDSTR),
5750 state = YAFFS_BLOCK_STATE_ALLOCATING;
5751 dev->allocationBlock = blk;
5752 dev->allocationPage = c;
5753 dev->allocationBlockFinder = blk;
5754 /* Set it to here to encourage the allocator to go forth from here. */
5758 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5759 } else if (tags.chunkId > 0) {
5760 /* chunkId > 0 so it is a data chunk... */
5761 unsigned int endpos;
5763 yaffs_SetChunkBit(dev, blk, c);
5766 in = yaffs_FindOrCreateObjectByNumber(dev,
5769 YAFFS_OBJECT_TYPE_FILE);
5770 /* PutChunkIntoFile checks for a clash (two data chunks with
5771 * the same chunkId).
5778 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5783 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5786 in->variantType == YAFFS_OBJECT_TYPE_FILE
5787 && in->variant.fileVariant.scannedFileSize <
5789 in->variant.fileVariant.
5790 scannedFileSize = endpos;
5791 if (!dev->useHeaderFileSize) {
5792 in->variant.fileVariant.
5794 in->variant.fileVariant.
5799 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5801 /* chunkId == 0, so it is an ObjectHeader.
5802 * Thus, we read in the object header and make the object
5804 yaffs_SetChunkBit(dev, blk, c);
5807 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5811 oh = (yaffs_ObjectHeader *) chunkData;
5813 in = yaffs_FindObjectByNumber(dev,
5815 if (in && in->variantType != oh->type) {
5816 /* This should not happen, but somehow
5817 * Wev'e ended up with an objectId that has been reused but not yet
5818 * deleted, and worse still it has changed type. Delete the old object.
5821 yaffs_DeleteObject(in);
5826 in = yaffs_FindOrCreateObjectByNumber(dev,
5834 if (in && oh->shadowsObject > 0) {
5836 struct yaffs_ShadowFixerStruct *fixer;
5837 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5839 fixer->next = shadowFixerList;
5840 shadowFixerList = fixer;
5841 fixer->objectId = tags.objectId;
5842 fixer->shadowedId = oh->shadowsObject;
5847 if (in && in->valid) {
5848 /* We have already filled this one. We have a duplicate and need to resolve it. */
5850 unsigned existingSerial = in->serial;
5851 unsigned newSerial = tags.serialNumber;
5853 if (((existingSerial + 1) & 3) == newSerial) {
5854 /* Use new one - destroy the exisiting one */
5855 yaffs_DeleteChunk(dev,
5860 /* Use existing - destroy this one. */
5861 yaffs_DeleteChunk(dev, chunk, 1,
5866 if (in && !in->valid &&
5867 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5868 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5869 /* We only load some info, don't fiddle with directory structure */
5871 in->variantType = oh->type;
5873 in->yst_mode = oh->yst_mode;
5874 #ifdef CONFIG_YAFFS_WINCE
5875 in->win_atime[0] = oh->win_atime[0];
5876 in->win_ctime[0] = oh->win_ctime[0];
5877 in->win_mtime[0] = oh->win_mtime[0];
5878 in->win_atime[1] = oh->win_atime[1];
5879 in->win_ctime[1] = oh->win_ctime[1];
5880 in->win_mtime[1] = oh->win_mtime[1];
5882 in->yst_uid = oh->yst_uid;
5883 in->yst_gid = oh->yst_gid;
5884 in->yst_atime = oh->yst_atime;
5885 in->yst_mtime = oh->yst_mtime;
5886 in->yst_ctime = oh->yst_ctime;
5887 in->yst_rdev = oh->yst_rdev;
5889 in->hdrChunk = chunk;
5890 in->serial = tags.serialNumber;
5892 } else if (in && !in->valid) {
5893 /* we need to load this info */
5896 in->variantType = oh->type;
5898 in->yst_mode = oh->yst_mode;
5899 #ifdef CONFIG_YAFFS_WINCE
5900 in->win_atime[0] = oh->win_atime[0];
5901 in->win_ctime[0] = oh->win_ctime[0];
5902 in->win_mtime[0] = oh->win_mtime[0];
5903 in->win_atime[1] = oh->win_atime[1];
5904 in->win_ctime[1] = oh->win_ctime[1];
5905 in->win_mtime[1] = oh->win_mtime[1];
5907 in->yst_uid = oh->yst_uid;
5908 in->yst_gid = oh->yst_gid;
5909 in->yst_atime = oh->yst_atime;
5910 in->yst_mtime = oh->yst_mtime;
5911 in->yst_ctime = oh->yst_ctime;
5912 in->yst_rdev = oh->yst_rdev;
5914 in->hdrChunk = chunk;
5915 in->serial = tags.serialNumber;
5917 yaffs_SetObjectName(in, oh->name);
5920 /* directory stuff...
5925 yaffs_FindOrCreateObjectByNumber
5926 (dev, oh->parentObjectId,
5927 YAFFS_OBJECT_TYPE_DIRECTORY);
5930 if (parent && parent->variantType ==
5931 YAFFS_OBJECT_TYPE_UNKNOWN) {
5932 /* Set up as a directory */
5933 parent->variantType =
5934 YAFFS_OBJECT_TYPE_DIRECTORY;
5935 YINIT_LIST_HEAD(&parent->variant.
5938 } else if (!parent || parent->variantType !=
5939 YAFFS_OBJECT_TYPE_DIRECTORY) {
5940 /* Hoosterman, another problem....
5941 * We're trying to use a non-directory as a directory
5944 T(YAFFS_TRACE_ERROR,
5946 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5948 parent = dev->lostNFoundDir;
5951 yaffs_AddObjectToDirectory(parent, in);
5953 if (0 && (parent == dev->deletedDir ||
5954 parent == dev->unlinkedDir)) {
5955 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5956 dev->nDeletedFiles++;
5958 /* Note re hardlinks.
5959 * Since we might scan a hardlink before its equivalent object is scanned
5960 * we put them all in a list.
5961 * After scanning is complete, we should have all the objects, so we run through this
5962 * list and fix up all the chains.
5965 switch (in->variantType) {
5966 case YAFFS_OBJECT_TYPE_UNKNOWN:
5967 /* Todo got a problem */
5969 case YAFFS_OBJECT_TYPE_FILE:
5970 if (dev->useHeaderFileSize)
5972 in->variant.fileVariant.
5977 case YAFFS_OBJECT_TYPE_HARDLINK:
5978 in->variant.hardLinkVariant.
5979 equivalentObjectId =
5980 oh->equivalentObjectId;
5981 in->hardLinks.next =
5982 (struct ylist_head *)
5986 case YAFFS_OBJECT_TYPE_DIRECTORY:
5989 case YAFFS_OBJECT_TYPE_SPECIAL:
5992 case YAFFS_OBJECT_TYPE_SYMLINK:
5993 in->variant.symLinkVariant.alias =
5994 yaffs_CloneString(oh->alias);
5995 if (!in->variant.symLinkVariant.alias)
6001 if (parent == dev->deletedDir) {
6002 yaffs_DestroyObject(in);
6003 bi->hasShrinkHeader = 1;
6010 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6011 /* If we got this far while scanning, then the block is fully allocated.*/
6012 state = YAFFS_BLOCK_STATE_FULL;
6015 bi->blockState = state;
6017 /* Now let's see if it was dirty */
6018 if (bi->pagesInUse == 0 &&
6019 !bi->hasShrinkHeader &&
6020 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6021 yaffs_BlockBecameDirty(dev, blk);
6027 /* Ok, we've done all the scanning.
6028 * Fix up the hard link chains.
6029 * We should now have scanned all the objects, now it's time to add these
6033 yaffs_HardlinkFixup(dev, hardList);
6035 /* Fix up any shadowed objects */
6037 struct yaffs_ShadowFixerStruct *fixer;
6040 while (shadowFixerList) {
6041 fixer = shadowFixerList;
6042 shadowFixerList = fixer->next;
6043 /* Complete the rename transaction by deleting the shadowed object
6044 * then setting the object header to unshadowed.
6046 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6048 yaffs_DeleteObject(obj);
6050 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6053 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6059 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6064 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6070 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6073 yaffs_ObjectHeader *oh;
6075 yaffs_ExtendedTags tags;
6077 int alloc_failed = 0;
6085 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6087 in->lazyLoaded ? "not yet" : "already"));
6090 if (in->lazyLoaded && in->hdrChunk > 0) {
6092 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6094 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6095 oh = (yaffs_ObjectHeader *) chunkData;
6097 in->yst_mode = oh->yst_mode;
6098 #ifdef CONFIG_YAFFS_WINCE
6099 in->win_atime[0] = oh->win_atime[0];
6100 in->win_ctime[0] = oh->win_ctime[0];
6101 in->win_mtime[0] = oh->win_mtime[0];
6102 in->win_atime[1] = oh->win_atime[1];
6103 in->win_ctime[1] = oh->win_ctime[1];
6104 in->win_mtime[1] = oh->win_mtime[1];
6106 in->yst_uid = oh->yst_uid;
6107 in->yst_gid = oh->yst_gid;
6108 in->yst_atime = oh->yst_atime;
6109 in->yst_mtime = oh->yst_mtime;
6110 in->yst_ctime = oh->yst_ctime;
6111 in->yst_rdev = oh->yst_rdev;
6114 yaffs_SetObjectName(in, oh->name);
6116 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6117 in->variant.symLinkVariant.alias =
6118 yaffs_CloneString(oh->alias);
6119 if (!in->variant.symLinkVariant.alias)
6120 alloc_failed = 1; /* Not returned to caller */
6123 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6127 static int yaffs_ScanBackwards(yaffs_Device *dev)
6129 yaffs_ExtendedTags tags;
6134 int nBlocksToScan = 0;
6140 yaffs_BlockState state;
6141 yaffs_Object *hardList = NULL;
6142 yaffs_BlockInfo *bi;
6143 __u32 sequenceNumber;
6144 yaffs_ObjectHeader *oh;
6146 yaffs_Object *parent;
6147 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6153 int foundChunksInBlock;
6154 int equivalentObjectId;
6155 int alloc_failed = 0;
6158 yaffs_BlockIndex *blockIndex = NULL;
6159 int altBlockIndex = 0;
6161 if (!dev->isYaffs2) {
6163 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6169 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6170 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6173 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6175 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6178 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6184 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6188 dev->blocksInCheckpoint = 0;
6190 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6192 /* Scan all the blocks to determine their state */
6193 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6194 bi = yaffs_GetBlockInfo(dev, blk);
6195 yaffs_ClearChunkBits(dev, blk);
6197 bi->softDeletions = 0;
6199 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6201 bi->blockState = state;
6202 bi->sequenceNumber = sequenceNumber;
6204 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6205 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6206 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6207 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6209 T(YAFFS_TRACE_SCAN_DEBUG,
6210 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6211 state, sequenceNumber));
6214 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6215 dev->blocksInCheckpoint++;
6217 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6218 T(YAFFS_TRACE_BAD_BLOCKS,
6219 (TSTR("block %d is bad" TENDSTR), blk));
6220 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6221 T(YAFFS_TRACE_SCAN_DEBUG,
6222 (TSTR("Block empty " TENDSTR)));
6223 dev->nErasedBlocks++;
6224 dev->nFreeChunks += dev->nChunksPerBlock;
6225 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6227 /* Determine the highest sequence number */
6228 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6229 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6231 blockIndex[nBlocksToScan].seq = sequenceNumber;
6232 blockIndex[nBlocksToScan].block = blk;
6236 if (sequenceNumber >= dev->sequenceNumber)
6237 dev->sequenceNumber = sequenceNumber;
6239 /* TODO: Nasty sequence number! */
6242 ("Block scanning block %d has bad sequence number %d"
6243 TENDSTR), blk, sequenceNumber));
6250 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6256 /* Sort the blocks */
6257 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6259 /* Use qsort now. */
6260 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6264 /* Dungy old bubble sort... */
6266 yaffs_BlockIndex temp;
6270 for (i = 0; i < nBlocksToScan; i++)
6271 for (j = i + 1; j < nBlocksToScan; j++)
6272 if (blockIndex[i].seq > blockIndex[j].seq) {
6273 temp = blockIndex[j];
6274 blockIndex[j] = blockIndex[i];
6275 blockIndex[i] = temp;
6282 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6284 /* Now scan the blocks looking at the data. */
6286 endIterator = nBlocksToScan - 1;
6287 T(YAFFS_TRACE_SCAN_DEBUG,
6288 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6290 /* For each block.... backwards */
6291 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6293 /* Cooperative multitasking! This loop can run for so
6294 long that watchdog timers expire. */
6297 /* get the block to scan in the correct order */
6298 blk = blockIndex[blockIterator].block;
6300 bi = yaffs_GetBlockInfo(dev, blk);
6303 state = bi->blockState;
6307 /* For each chunk in each block that needs scanning.... */
6308 foundChunksInBlock = 0;
6309 for (c = dev->nChunksPerBlock - 1;
6310 !alloc_failed && c >= 0 &&
6311 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6312 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6313 /* Scan backwards...
6314 * Read the tags and decide what to do
6317 chunk = blk * dev->nChunksPerBlock + c;
6319 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6322 /* Let's have a good look at this chunk... */
6324 if (!tags.chunkUsed) {
6325 /* An unassigned chunk in the block.
6326 * If there are used chunks after this one, then
6327 * it is a chunk that was skipped due to failing the erased
6328 * check. Just skip it so that it can be deleted.
6329 * But, more typically, We get here when this is an unallocated
6330 * chunk and his means that either the block is empty or
6331 * this is the one being allocated from
6334 if (foundChunksInBlock) {
6335 /* This is a chunk that was skipped due to failing the erased check */
6336 } else if (c == 0) {
6337 /* We're looking at the first chunk in the block so the block is unused */
6338 state = YAFFS_BLOCK_STATE_EMPTY;
6339 dev->nErasedBlocks++;
6341 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6342 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6343 if (dev->sequenceNumber == bi->sequenceNumber) {
6344 /* this is the block being allocated from */
6348 (" Allocating from %d %d"
6351 state = YAFFS_BLOCK_STATE_ALLOCATING;
6352 dev->allocationBlock = blk;
6353 dev->allocationPage = c;
6354 dev->allocationBlockFinder = blk;
6356 /* This is a partially written block that is not
6357 * the current allocation block. This block must have
6358 * had a write failure, so set up for retirement.
6361 /* bi->needsRetiring = 1; ??? TODO */
6362 bi->gcPrioritise = 1;
6364 T(YAFFS_TRACE_ALWAYS,
6365 (TSTR("Partially written block %d detected" TENDSTR),
6373 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6375 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6380 } else if (tags.chunkId > 0) {
6381 /* chunkId > 0 so it is a data chunk... */
6382 unsigned int endpos;
6384 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6386 foundChunksInBlock = 1;
6389 yaffs_SetChunkBit(dev, blk, c);
6392 in = yaffs_FindOrCreateObjectByNumber(dev,
6395 YAFFS_OBJECT_TYPE_FILE);
6402 in->variantType == YAFFS_OBJECT_TYPE_FILE
6404 in->variant.fileVariant.shrinkSize) {
6405 /* This has not been invalidated by a resize */
6406 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6411 /* File size is calculated by looking at the data chunks if we have not
6412 * seen an object header yet. Stop this practice once we find an object header.
6416 1) * dev->nDataBytesPerChunk +
6419 if (!in->valid && /* have not got an object header yet */
6420 in->variant.fileVariant.
6421 scannedFileSize < endpos) {
6422 in->variant.fileVariant.
6423 scannedFileSize = endpos;
6424 in->variant.fileVariant.
6426 in->variant.fileVariant.
6431 /* This chunk has been invalidated by a resize, so delete */
6432 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6436 /* chunkId == 0, so it is an ObjectHeader.
6437 * Thus, we read in the object header and make the object
6439 foundChunksInBlock = 1;
6441 yaffs_SetChunkBit(dev, blk, c);
6447 if (tags.extraHeaderInfoAvailable) {
6448 in = yaffs_FindOrCreateObjectByNumber
6449 (dev, tags.objectId,
6450 tags.extraObjectType);
6456 (!in->valid && dev->disableLazyLoad) ||
6457 tags.extraShadows ||
6459 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6460 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6462 /* If we don't have valid info then we need to read the chunk
6463 * TODO In future we can probably defer reading the chunk and
6464 * living with invalid data until needed.
6467 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6472 oh = (yaffs_ObjectHeader *) chunkData;
6474 if (dev->inbandTags) {
6475 /* Fix up the header if they got corrupted by inband tags */
6476 oh->shadowsObject = oh->inbandShadowsObject;
6477 oh->isShrink = oh->inbandIsShrink;
6481 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6489 /* TODO Hoosterman we have a problem! */
6490 T(YAFFS_TRACE_ERROR,
6492 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6493 TENDSTR), tags.objectId, chunk));
6498 /* We have already filled this one.
6499 * We have a duplicate that will be discarded, but
6500 * we first have to suck out resize info if it is a file.
6503 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6505 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6506 (tags.extraHeaderInfoAvailable &&
6507 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6509 (oh) ? oh->fileSize : tags.
6511 __u32 parentObjectId =
6513 parentObjectId : tags.
6514 extraParentObjectId;
6518 (oh) ? oh->isShrink : tags.
6519 extraIsShrinkHeader;
6521 /* If it is deleted (unlinked at start also means deleted)
6522 * we treat the file size as being zeroed at this point.
6524 if (parentObjectId ==
6525 YAFFS_OBJECTID_DELETED
6526 || parentObjectId ==
6527 YAFFS_OBJECTID_UNLINKED) {
6533 in->variant.fileVariant.
6534 shrinkSize > thisSize) {
6535 in->variant.fileVariant.
6541 bi->hasShrinkHeader = 1;
6544 /* Use existing - destroy this one. */
6545 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6549 if (!in->valid && in->variantType !=
6550 (oh ? oh->type : tags.extraObjectType))
6551 T(YAFFS_TRACE_ERROR, (
6552 TSTR("yaffs tragedy: Bad object type, "
6553 TCONT("%d != %d, for object %d at chunk ")
6554 TCONT("%d during scan")
6556 oh->type : tags.extraObjectType,
6557 in->variantType, tags.objectId,
6561 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6563 YAFFS_OBJECTID_LOSTNFOUND)) {
6564 /* We only load some info, don't fiddle with directory structure */
6568 in->variantType = oh->type;
6570 in->yst_mode = oh->yst_mode;
6571 #ifdef CONFIG_YAFFS_WINCE
6572 in->win_atime[0] = oh->win_atime[0];
6573 in->win_ctime[0] = oh->win_ctime[0];
6574 in->win_mtime[0] = oh->win_mtime[0];
6575 in->win_atime[1] = oh->win_atime[1];
6576 in->win_ctime[1] = oh->win_ctime[1];
6577 in->win_mtime[1] = oh->win_mtime[1];
6579 in->yst_uid = oh->yst_uid;
6580 in->yst_gid = oh->yst_gid;
6581 in->yst_atime = oh->yst_atime;
6582 in->yst_mtime = oh->yst_mtime;
6583 in->yst_ctime = oh->yst_ctime;
6584 in->yst_rdev = oh->yst_rdev;
6588 in->variantType = tags.extraObjectType;
6592 in->hdrChunk = chunk;
6594 } else if (!in->valid) {
6595 /* we need to load this info */
6598 in->hdrChunk = chunk;
6601 in->variantType = oh->type;
6603 in->yst_mode = oh->yst_mode;
6604 #ifdef CONFIG_YAFFS_WINCE
6605 in->win_atime[0] = oh->win_atime[0];
6606 in->win_ctime[0] = oh->win_ctime[0];
6607 in->win_mtime[0] = oh->win_mtime[0];
6608 in->win_atime[1] = oh->win_atime[1];
6609 in->win_ctime[1] = oh->win_ctime[1];
6610 in->win_mtime[1] = oh->win_mtime[1];
6612 in->yst_uid = oh->yst_uid;
6613 in->yst_gid = oh->yst_gid;
6614 in->yst_atime = oh->yst_atime;
6615 in->yst_mtime = oh->yst_mtime;
6616 in->yst_ctime = oh->yst_ctime;
6617 in->yst_rdev = oh->yst_rdev;
6620 if (oh->shadowsObject > 0)
6621 yaffs_HandleShadowedObject(dev,
6627 yaffs_SetObjectName(in, oh->name);
6629 yaffs_FindOrCreateObjectByNumber
6630 (dev, oh->parentObjectId,
6631 YAFFS_OBJECT_TYPE_DIRECTORY);
6633 fileSize = oh->fileSize;
6634 isShrink = oh->isShrink;
6635 equivalentObjectId = oh->equivalentObjectId;
6638 in->variantType = tags.extraObjectType;
6640 yaffs_FindOrCreateObjectByNumber
6641 (dev, tags.extraParentObjectId,
6642 YAFFS_OBJECT_TYPE_DIRECTORY);
6643 fileSize = tags.extraFileLength;
6644 isShrink = tags.extraIsShrinkHeader;
6645 equivalentObjectId = tags.extraEquivalentObjectId;
6654 /* directory stuff...
6658 if (parent && parent->variantType ==
6659 YAFFS_OBJECT_TYPE_UNKNOWN) {
6660 /* Set up as a directory */
6661 parent->variantType =
6662 YAFFS_OBJECT_TYPE_DIRECTORY;
6663 YINIT_LIST_HEAD(&parent->variant.
6666 } else if (!parent || parent->variantType !=
6667 YAFFS_OBJECT_TYPE_DIRECTORY) {
6668 /* Hoosterman, another problem....
6669 * We're trying to use a non-directory as a directory
6672 T(YAFFS_TRACE_ERROR,
6674 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6676 parent = dev->lostNFoundDir;
6679 yaffs_AddObjectToDirectory(parent, in);
6681 itsUnlinked = (parent == dev->deletedDir) ||
6682 (parent == dev->unlinkedDir);
6685 /* Mark the block as having a shrinkHeader */
6686 bi->hasShrinkHeader = 1;
6689 /* Note re hardlinks.
6690 * Since we might scan a hardlink before its equivalent object is scanned
6691 * we put them all in a list.
6692 * After scanning is complete, we should have all the objects, so we run
6693 * through this list and fix up all the chains.
6696 switch (in->variantType) {
6697 case YAFFS_OBJECT_TYPE_UNKNOWN:
6698 /* Todo got a problem */
6700 case YAFFS_OBJECT_TYPE_FILE:
6702 if (in->variant.fileVariant.
6703 scannedFileSize < fileSize) {
6704 /* This covers the case where the file size is greater
6705 * than where the data is
6706 * This will happen if the file is resized to be larger
6707 * than its current data extents.
6709 in->variant.fileVariant.fileSize = fileSize;
6710 in->variant.fileVariant.scannedFileSize =
6711 in->variant.fileVariant.fileSize;
6715 in->variant.fileVariant.shrinkSize > fileSize) {
6716 in->variant.fileVariant.shrinkSize = fileSize;
6720 case YAFFS_OBJECT_TYPE_HARDLINK:
6722 in->variant.hardLinkVariant.equivalentObjectId =
6724 in->hardLinks.next =
6725 (struct ylist_head *) hardList;
6729 case YAFFS_OBJECT_TYPE_DIRECTORY:
6732 case YAFFS_OBJECT_TYPE_SPECIAL:
6735 case YAFFS_OBJECT_TYPE_SYMLINK:
6737 in->variant.symLinkVariant.alias =
6738 yaffs_CloneString(oh->alias);
6739 if (!in->variant.symLinkVariant.alias)
6749 } /* End of scanning for each chunk */
6751 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6752 /* If we got this far while scanning, then the block is fully allocated. */
6753 state = YAFFS_BLOCK_STATE_FULL;
6756 bi->blockState = state;
6758 /* Now let's see if it was dirty */
6759 if (bi->pagesInUse == 0 &&
6760 !bi->hasShrinkHeader &&
6761 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6762 yaffs_BlockBecameDirty(dev, blk);
6768 YFREE_ALT(blockIndex);
6772 /* Ok, we've done all the scanning.
6773 * Fix up the hard link chains.
6774 * We should now have scanned all the objects, now it's time to add these
6777 yaffs_HardlinkFixup(dev, hardList);
6780 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6785 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6790 /*------------------------------ Directory Functions ----------------------------- */
6792 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6794 struct ylist_head *lh;
6795 yaffs_Object *listObj;
6800 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6805 if (yaffs_SkipVerification(obj->myDev))
6809 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6814 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6815 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6819 /* Iterate through the objects in each hash entry */
6821 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6823 listObj = ylist_entry(lh, yaffs_Object, siblings);
6824 yaffs_VerifyObject(listObj);
6831 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6836 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6838 struct ylist_head *lh;
6839 yaffs_Object *listObj;
6846 if (yaffs_SkipFullVerification(directory->myDev))
6849 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6850 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6854 /* Iterate through the objects in each hash entry */
6856 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6858 listObj = ylist_entry(lh, yaffs_Object, siblings);
6859 if (listObj->parent != directory) {
6860 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6863 yaffs_VerifyObjectInDirectory(listObj);
6869 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6870 * link (ie. name) is created or deleted in the directory.
6873 * create dir/a : update dir's mtime/ctime
6874 * rm dir/a: update dir's mtime/ctime
6875 * modify dir/a: don't update dir's mtimme/ctime
6878 static void yaffs_UpdateParent(yaffs_Object *obj)
6884 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6886 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6889 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6891 yaffs_Device *dev = obj->myDev;
6892 yaffs_Object *parent;
6894 yaffs_VerifyObjectInDirectory(obj);
6895 parent = obj->parent;
6897 yaffs_VerifyDirectory(parent);
6899 if (dev && dev->removeObjectCallback)
6900 dev->removeObjectCallback(obj);
6903 ylist_del_init(&obj->siblings);
6906 yaffs_VerifyDirectory(parent);
6909 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6913 T(YAFFS_TRACE_ALWAYS,
6915 ("tragedy: Trying to add an object to a null pointer directory"
6920 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6921 T(YAFFS_TRACE_ALWAYS,
6923 ("tragedy: Trying to add an object to a non-directory"
6928 if (obj->siblings.prev == NULL) {
6929 /* Not initialised */
6934 yaffs_VerifyDirectory(directory);
6936 yaffs_RemoveObjectFromDirectory(obj);
6940 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6941 obj->parent = directory;
6943 if (directory == obj->myDev->unlinkedDir
6944 || directory == obj->myDev->deletedDir) {
6946 obj->myDev->nUnlinkedFiles++;
6947 obj->renameAllowed = 0;
6950 yaffs_VerifyDirectory(directory);
6951 yaffs_VerifyObjectInDirectory(obj);
6954 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
6959 struct ylist_head *i;
6960 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6968 T(YAFFS_TRACE_ALWAYS,
6970 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6975 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6976 T(YAFFS_TRACE_ALWAYS,
6978 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6982 sum = yaffs_CalcNameSum(name);
6984 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6986 l = ylist_entry(i, yaffs_Object, siblings);
6988 if (l->parent != directory)
6991 yaffs_CheckObjectDetailsLoaded(l);
6993 /* Special case for lost-n-found */
6994 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6995 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
6997 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
6998 /* LostnFound chunk called Objxxx
7001 yaffs_GetObjectName(l, buffer,
7002 YAFFS_MAX_NAME_LENGTH + 1);
7003 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7014 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7015 int (*fn) (yaffs_Object *))
7017 struct ylist_head *i;
7021 T(YAFFS_TRACE_ALWAYS,
7023 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7028 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7029 T(YAFFS_TRACE_ALWAYS,
7031 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7036 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7038 l = ylist_entry(i, yaffs_Object, siblings);
7049 /* GetEquivalentObject dereferences any hard links to get to the
7053 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7055 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7056 /* We want the object id of the equivalent object, not this one */
7057 obj = obj->variant.hardLinkVariant.equivalentObject;
7058 yaffs_CheckObjectDetailsLoaded(obj);
7063 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7065 memset(name, 0, buffSize * sizeof(YCHAR));
7067 yaffs_CheckObjectDetailsLoaded(obj);
7069 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7070 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7071 } else if (obj->hdrChunk <= 0) {
7073 YCHAR numString[20];
7074 YCHAR *x = &numString[19];
7075 unsigned v = obj->objectId;
7079 *x = '0' + (v % 10);
7082 /* make up a name */
7083 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7084 yaffs_strcat(locName, x);
7085 yaffs_strncpy(name, locName, buffSize - 1);
7088 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7089 else if (obj->shortName[0])
7090 yaffs_strcpy(name, obj->shortName);
7094 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7096 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7098 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7100 if (obj->hdrChunk > 0) {
7101 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7102 obj->hdrChunk, buffer,
7105 yaffs_strncpy(name, oh->name, buffSize - 1);
7107 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7110 return yaffs_strlen(name);
7113 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7115 /* Dereference any hard linking */
7116 obj = yaffs_GetEquivalentObject(obj);
7118 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7119 return obj->variant.fileVariant.fileSize;
7120 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7121 if(!obj->variant.symLinkVariant.alias)
7123 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7125 /* Only a directory should drop through to here */
7126 return obj->myDev->nDataBytesPerChunk;
7130 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7133 struct ylist_head *i;
7136 count++; /* the object itself */
7138 ylist_for_each(i, &obj->hardLinks)
7139 count++; /* add the hard links; */
7144 int yaffs_GetObjectInode(yaffs_Object *obj)
7146 obj = yaffs_GetEquivalentObject(obj);
7148 return obj->objectId;
7151 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7153 obj = yaffs_GetEquivalentObject(obj);
7155 switch (obj->variantType) {
7156 case YAFFS_OBJECT_TYPE_FILE:
7159 case YAFFS_OBJECT_TYPE_DIRECTORY:
7162 case YAFFS_OBJECT_TYPE_SYMLINK:
7165 case YAFFS_OBJECT_TYPE_HARDLINK:
7168 case YAFFS_OBJECT_TYPE_SPECIAL:
7169 if (S_ISFIFO(obj->yst_mode))
7171 if (S_ISCHR(obj->yst_mode))
7173 if (S_ISBLK(obj->yst_mode))
7175 if (S_ISSOCK(obj->yst_mode))
7183 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7185 obj = yaffs_GetEquivalentObject(obj);
7186 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7187 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7189 return yaffs_CloneString(_Y(""));
7192 #ifndef CONFIG_YAFFS_WINCE
7194 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7196 unsigned int valid = attr->ia_valid;
7198 if (valid & ATTR_MODE)
7199 obj->yst_mode = attr->ia_mode;
7200 if (valid & ATTR_UID)
7201 obj->yst_uid = attr->ia_uid;
7202 if (valid & ATTR_GID)
7203 obj->yst_gid = attr->ia_gid;
7205 if (valid & ATTR_ATIME)
7206 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7207 if (valid & ATTR_CTIME)
7208 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7209 if (valid & ATTR_MTIME)
7210 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7212 if (valid & ATTR_SIZE)
7213 yaffs_ResizeFile(obj, attr->ia_size);
7215 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7220 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7222 unsigned int valid = 0;
7224 attr->ia_mode = obj->yst_mode;
7226 attr->ia_uid = obj->yst_uid;
7228 attr->ia_gid = obj->yst_gid;
7231 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7232 valid |= ATTR_ATIME;
7233 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7234 valid |= ATTR_CTIME;
7235 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7236 valid |= ATTR_MTIME;
7238 attr->ia_size = yaffs_GetFileSize(obj);
7241 attr->ia_valid = valid;
7249 int yaffs_DumpObject(yaffs_Object *obj)
7253 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7255 T(YAFFS_TRACE_ALWAYS,
7257 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7258 " chunk %d type %d size %d\n"
7259 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7260 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7261 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7267 /*---------------------------- Initialisation code -------------------------------------- */
7269 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7272 /* Common functions, gotta have */
7273 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7276 #ifdef CONFIG_YAFFS_YAFFS2
7278 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7279 if (dev->writeChunkWithTagsToNAND &&
7280 dev->readChunkWithTagsFromNAND &&
7281 !dev->writeChunkToNAND &&
7282 !dev->readChunkFromNAND &&
7283 dev->markNANDBlockBad && dev->queryNANDBlock)
7287 /* Can use the "spare" style interface for yaffs1 */
7288 if (!dev->isYaffs2 &&
7289 !dev->writeChunkWithTagsToNAND &&
7290 !dev->readChunkWithTagsFromNAND &&
7291 dev->writeChunkToNAND &&
7292 dev->readChunkFromNAND &&
7293 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7300 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7302 /* Initialise the unlinked, deleted, root and lost and found directories */
7304 dev->lostNFoundDir = dev->rootDir = NULL;
7305 dev->unlinkedDir = dev->deletedDir = NULL;
7308 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7311 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7314 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7315 YAFFS_ROOT_MODE | S_IFDIR);
7316 dev->lostNFoundDir =
7317 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7318 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7320 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7321 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7328 int yaffs_GutsInitialise(yaffs_Device *dev)
7330 int init_failed = 0;
7334 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7336 /* Check stuff that must be set */
7339 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7343 dev->internalStartBlock = dev->startBlock;
7344 dev->internalEndBlock = dev->endBlock;
7345 dev->blockOffset = 0;
7346 dev->chunkOffset = 0;
7347 dev->nFreeChunks = 0;
7351 if (dev->startBlock == 0) {
7352 dev->internalStartBlock = dev->startBlock + 1;
7353 dev->internalEndBlock = dev->endBlock + 1;
7354 dev->blockOffset = 1;
7355 dev->chunkOffset = dev->nChunksPerBlock;
7358 /* Check geometry parameters. */
7360 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7361 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7362 (dev->inbandTags && !dev->isYaffs2) ||
7363 dev->nChunksPerBlock < 2 ||
7364 dev->nReservedBlocks < 2 ||
7365 dev->internalStartBlock <= 0 ||
7366 dev->internalEndBlock <= 0 ||
7367 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) { /* otherwise it is too small */
7368 T(YAFFS_TRACE_ALWAYS,
7370 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7371 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7375 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7376 T(YAFFS_TRACE_ALWAYS,
7377 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7381 /* Sort out space for inband tags, if required */
7382 if (dev->inbandTags)
7383 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7385 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7387 /* Got the right mix of functions? */
7388 if (!yaffs_CheckDevFunctions(dev)) {
7389 /* Function missing */
7390 T(YAFFS_TRACE_ALWAYS,
7392 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7397 /* This is really a compilation check. */
7398 if (!yaffs_CheckStructures()) {
7399 T(YAFFS_TRACE_ALWAYS,
7400 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7404 if (dev->isMounted) {
7405 T(YAFFS_TRACE_ALWAYS,
7406 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7410 /* Finished with most checks. One or two more checks happen later on too. */
7414 /* OK now calculate a few things for the device */
7417 * Calculate all the chunk size manipulation numbers:
7419 x = dev->nDataBytesPerChunk;
7420 /* We always use dev->chunkShift and dev->chunkDiv */
7421 dev->chunkShift = Shifts(x);
7422 x >>= dev->chunkShift;
7424 /* We only use chunk mask if chunkDiv is 1 */
7425 dev->chunkMask = (1<<dev->chunkShift) - 1;
7428 * Calculate chunkGroupBits.
7429 * We need to find the next power of 2 > than internalEndBlock
7432 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7436 /* Set up tnode width if wide tnodes are enabled. */
7437 if (!dev->wideTnodesDisabled) {
7438 /* bits must be even so that we end up with 32-bit words */
7442 dev->tnodeWidth = 16;
7444 dev->tnodeWidth = bits;
7446 dev->tnodeWidth = 16;
7448 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7450 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7451 * so if the bitwidth of the
7452 * chunk range we're using is greater than 16 we need
7453 * to figure out chunk shift and chunkGroupSize
7456 if (bits <= dev->tnodeWidth)
7457 dev->chunkGroupBits = 0;
7459 dev->chunkGroupBits = bits - dev->tnodeWidth;
7462 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7464 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7465 /* We have a problem because the soft delete won't work if
7466 * the chunk group size > chunks per block.
7467 * This can be remedied by using larger "virtual blocks".
7469 T(YAFFS_TRACE_ALWAYS,
7470 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7475 /* OK, we've finished verifying the device, lets continue with initialisation */
7477 /* More device initialisation */
7478 dev->garbageCollections = 0;
7479 dev->passiveGarbageCollections = 0;
7480 dev->currentDirtyChecker = 0;
7481 dev->bufferedBlock = -1;
7482 dev->doingBufferedBlockRewrite = 0;
7483 dev->nDeletedFiles = 0;
7484 dev->nBackgroundDeletions = 0;
7485 dev->nUnlinkedFiles = 0;
7487 dev->eccUnfixed = 0;
7488 dev->tagsEccFixed = 0;
7489 dev->tagsEccUnfixed = 0;
7490 dev->nErasureFailures = 0;
7491 dev->nErasedBlocks = 0;
7493 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7495 /* Initialise temporary buffers and caches. */
7496 if (!yaffs_InitialiseTempBuffers(dev))
7499 dev->srCache = NULL;
7500 dev->gcCleanupList = NULL;
7504 dev->nShortOpCaches > 0) {
7507 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7509 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7510 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7512 dev->srCache = YMALLOC(srCacheBytes);
7514 buf = (__u8 *) dev->srCache;
7517 memset(dev->srCache, 0, srCacheBytes);
7519 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7520 dev->srCache[i].object = NULL;
7521 dev->srCache[i].lastUse = 0;
7522 dev->srCache[i].dirty = 0;
7523 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7534 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7535 if (!dev->gcCleanupList)
7540 dev->useHeaderFileSize = 1;
7542 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7545 yaffs_InitialiseTnodes(dev);
7546 yaffs_InitialiseObjects(dev);
7548 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7553 /* Now scan the flash. */
7554 if (dev->isYaffs2) {
7555 if (yaffs_CheckpointRestore(dev)) {
7556 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7557 T(YAFFS_TRACE_ALWAYS,
7558 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7561 /* Clean up the mess caused by an aborted checkpoint load
7562 * and scan backwards.
7564 yaffs_DeinitialiseBlocks(dev);
7565 yaffs_DeinitialiseTnodes(dev);
7566 yaffs_DeinitialiseObjects(dev);
7569 dev->nErasedBlocks = 0;
7570 dev->nFreeChunks = 0;
7571 dev->allocationBlock = -1;
7572 dev->allocationPage = -1;
7573 dev->nDeletedFiles = 0;
7574 dev->nUnlinkedFiles = 0;
7575 dev->nBackgroundDeletions = 0;
7576 dev->oldestDirtySequence = 0;
7578 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7581 yaffs_InitialiseTnodes(dev);
7582 yaffs_InitialiseObjects(dev);
7584 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7587 if (!init_failed && !yaffs_ScanBackwards(dev))
7590 } else if (!yaffs_Scan(dev))
7593 yaffs_StripDeletedObjects(dev);
7594 yaffs_FixHangingObjects(dev);
7595 if(dev->emptyLostAndFound)
7596 yaffs_EmptyLostAndFound(dev);
7600 /* Clean up the mess */
7601 T(YAFFS_TRACE_TRACING,
7602 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7604 yaffs_Deinitialise(dev);
7608 /* Zero out stats */
7609 dev->nPageReads = 0;
7610 dev->nPageWrites = 0;
7611 dev->nBlockErasures = 0;
7613 dev->nRetriedWrites = 0;
7615 dev->nRetiredBlocks = 0;
7617 yaffs_VerifyFreeChunks(dev);
7618 yaffs_VerifyBlocks(dev);
7620 /* Clean up any aborted checkpoint data */
7621 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7622 yaffs_InvalidateCheckpoint(dev);
7624 T(YAFFS_TRACE_TRACING,
7625 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7630 void yaffs_Deinitialise(yaffs_Device *dev)
7632 if (dev->isMounted) {
7635 yaffs_DeinitialiseBlocks(dev);
7636 yaffs_DeinitialiseTnodes(dev);
7637 yaffs_DeinitialiseObjects(dev);
7638 if (dev->nShortOpCaches > 0 &&
7641 for (i = 0; i < dev->nShortOpCaches; i++) {
7642 if (dev->srCache[i].data)
7643 YFREE(dev->srCache[i].data);
7644 dev->srCache[i].data = NULL;
7647 YFREE(dev->srCache);
7648 dev->srCache = NULL;
7651 YFREE(dev->gcCleanupList);
7653 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7654 YFREE(dev->tempBuffer[i].buffer);
7658 if (dev->deinitialiseNAND)
7659 dev->deinitialiseNAND(dev);
7663 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7668 yaffs_BlockInfo *blk;
7670 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7672 blk = yaffs_GetBlockInfo(dev, b);
7674 switch (blk->blockState) {
7675 case YAFFS_BLOCK_STATE_EMPTY:
7676 case YAFFS_BLOCK_STATE_ALLOCATING:
7677 case YAFFS_BLOCK_STATE_COLLECTING:
7678 case YAFFS_BLOCK_STATE_FULL:
7680 (dev->nChunksPerBlock - blk->pagesInUse +
7681 blk->softDeletions);
7691 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7693 /* This is what we report to the outside world */
7696 int nDirtyCacheChunks;
7697 int blocksForCheckpoint;
7701 nFree = dev->nFreeChunks;
7703 nFree = yaffs_CountFreeChunks(dev);
7706 nFree += dev->nDeletedFiles;
7708 /* Now count the number of dirty chunks in the cache and subtract those */
7710 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7711 if (dev->srCache[i].dirty)
7712 nDirtyCacheChunks++;
7715 nFree -= nDirtyCacheChunks;
7717 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7719 /* Now we figure out how much to reserve for the checkpoint and report that... */
7720 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7721 if (blocksForCheckpoint < 0)
7722 blocksForCheckpoint = 0;
7724 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7733 static int yaffs_freeVerificationFailures;
7735 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7740 if (yaffs_SkipVerification(dev))
7743 counted = yaffs_CountFreeChunks(dev);
7745 difference = dev->nFreeChunks - counted;
7748 T(YAFFS_TRACE_ALWAYS,
7749 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7750 dev->nFreeChunks, counted, difference));
7751 yaffs_freeVerificationFailures++;
7755 /*---------------------------------------- YAFFS test code ----------------------*/
7757 #define yaffs_CheckStruct(structure, syze, name) \
7759 if (sizeof(structure) != syze) { \
7760 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7761 name, syze, sizeof(structure))); \
7762 return YAFFS_FAIL; \
7766 static int yaffs_CheckStructures(void)
7768 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7769 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7770 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7771 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7772 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7774 #ifndef CONFIG_YAFFS_WINCE
7775 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");