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.112 2010-03-05 01:49:00 charles Exp $";
18 #include "yaffs_trace.h"
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
25 #include "yaffs_tagscompat.h"
26 #ifndef CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
29 #include "yaffs_nand.h"
31 #include "yaffs_checkptrw.h"
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
37 #define YAFFS_PASSIVE_GC_CHUNKS 2
39 #include "yaffs_ecc.h"
42 /* Robustification (if it ever comes about...) */
43 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
44 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
46 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
48 const yaffs_ExtendedTags *tags);
49 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
50 const yaffs_ExtendedTags *tags);
52 /* Other local prototypes */
53 static void yaffs_UpdateParent(yaffs_Object *obj);
54 static int yaffs_UnlinkObject(yaffs_Object *obj);
55 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
61 yaffs_ExtendedTags *tags,
63 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
64 int chunkInNAND, int inScan);
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
67 yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
70 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
71 int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
75 int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
81 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
84 static int yaffs_UnlinkWorker(yaffs_Object *obj);
86 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
89 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
90 yaffs_BlockInfo **blockUsedPtr);
92 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
94 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
96 static void yaffs_VerifyDirectory(yaffs_Object *directory);
98 static int yaffs_CheckFileSanity(yaffs_Object *in);
100 #define yaffs_CheckFileSanity(in)
103 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
104 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
106 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
108 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
109 yaffs_ExtendedTags *tags);
111 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
113 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
114 yaffs_FileStructure *fStruct,
117 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
118 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
121 yaffs_ExtendedTags *tags);
123 /* Function to calculate chunk and offset */
125 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
131 chunk = (__u32)(addr >> dev->chunkShift);
133 if (dev->chunkDiv == 1) {
134 /* easy power of 2 case */
135 offset = (__u32)(addr & dev->chunkMask);
137 /* Non power-of-2 case */
141 chunk /= dev->chunkDiv;
143 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144 offset = (__u32)(addr - chunkBase);
151 /* Function to return the number of shifts for a power of 2 greater than or
152 * equal to the given number
153 * Note we don't try to cater for all possible numbers and this does not have to
154 * be hellishly efficient.
157 static __u32 ShiftsGE(__u32 x)
162 nShifts = extraBits = 0;
177 /* Function to return the number of shifts to get a 1 in bit 0
180 static __u32 Shifts(__u32 x)
200 * Temporary buffer manipulations.
203 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
206 __u8 *buf = (__u8 *)1;
208 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
210 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
211 dev->tempBuffer[i].line = 0; /* not in use */
212 dev->tempBuffer[i].buffer = buf =
213 YMALLOC_DMA(dev->param.totalBytesPerChunk);
216 return buf ? YAFFS_OK : YAFFS_FAIL;
219 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
224 if (dev->tempInUse > dev->maxTemp)
225 dev->maxTemp = dev->tempInUse;
227 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
228 if (dev->tempBuffer[i].line == 0) {
229 dev->tempBuffer[i].line = lineNo;
230 if ((i + 1) > dev->maxTemp) {
231 dev->maxTemp = i + 1;
232 for (j = 0; j <= i; j++)
233 dev->tempBuffer[j].maxLine =
234 dev->tempBuffer[j].line;
237 return dev->tempBuffer[i].buffer;
241 T(YAFFS_TRACE_BUFFERS,
242 (TSTR("Out of temp buffers at line %d, other held by lines:"),
244 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
245 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
247 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
250 * If we got here then we have to allocate an unmanaged one
254 dev->unmanagedTempAllocations++;
255 return YMALLOC(dev->nDataBytesPerChunk);
259 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
266 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
267 if (dev->tempBuffer[i].buffer == buffer) {
268 dev->tempBuffer[i].line = 0;
274 /* assume it is an unmanaged one. */
275 T(YAFFS_TRACE_BUFFERS,
276 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
279 dev->unmanagedTempDeallocations++;
285 * Determine if we have a managed buffer.
287 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
291 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
292 if (dev->tempBuffer[i].buffer == buffer)
296 for (i = 0; i < dev->param.nShortOpCaches; i++) {
297 if (dev->srCache[i].data == buffer)
301 if (buffer == dev->checkpointBuffer)
304 T(YAFFS_TRACE_ALWAYS,
305 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
312 * Chunk bitmap manipulations
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
317 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
319 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
323 return dev->chunkBits +
324 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
329 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
332 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
338 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
340 __u8 *blkBits = yaffs_BlockBits(dev, blk);
342 memset(blkBits, 0, dev->chunkBitmapStride);
345 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
347 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 yaffs_VerifyChunkBitId(dev, blk, chunk);
351 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
354 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
356 __u8 *blkBits = yaffs_BlockBits(dev, blk);
358 yaffs_VerifyChunkBitId(dev, blk, chunk);
360 blkBits[chunk / 8] |= (1 << (chunk & 7));
363 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
365 __u8 *blkBits = yaffs_BlockBits(dev, blk);
366 yaffs_VerifyChunkBitId(dev, blk, chunk);
368 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
371 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
373 __u8 *blkBits = yaffs_BlockBits(dev, blk);
375 for (i = 0; i < dev->chunkBitmapStride; i++) {
383 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
385 __u8 *blkBits = yaffs_BlockBits(dev, blk);
388 for (i = 0; i < dev->chunkBitmapStride; i++) {
405 static int yaffs_SkipVerification(yaffs_Device *dev)
407 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
410 static int yaffs_SkipFullVerification(yaffs_Device *dev)
412 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
415 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
417 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
420 static const char *blockStateName[] = {
433 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
438 if (yaffs_SkipVerification(dev))
441 /* Report illegal runtime states */
442 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
443 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
445 switch (bi->blockState) {
446 case YAFFS_BLOCK_STATE_UNKNOWN:
447 case YAFFS_BLOCK_STATE_SCANNING:
448 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
449 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
450 n, blockStateName[bi->blockState]));
453 /* Check pages in use and soft deletions are legal */
455 actuallyUsed = bi->pagesInUse - bi->softDeletions;
457 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
458 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
459 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
460 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
461 n, bi->pagesInUse, bi->softDeletions));
464 /* Check chunk bitmap legal */
465 inUse = yaffs_CountChunkBits(dev, n);
466 if (inUse != bi->pagesInUse)
467 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
468 n, bi->pagesInUse, inUse));
470 /* Check that the sequence number is valid.
471 * Ten million is legal, but is very unlikely
473 if (dev->param.isYaffs2 &&
474 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
475 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
476 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
477 n, bi->sequenceNumber));
480 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
483 yaffs_VerifyBlock(dev, bi, n);
485 /* After collection the block should be in the erased state */
486 /* This will need to change if we do partial gc */
488 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
489 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
490 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
495 static void yaffs_VerifyBlocks(yaffs_Device *dev)
498 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
499 int nIllegalBlockStates = 0;
501 if (yaffs_SkipVerification(dev))
504 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
506 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
507 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
508 yaffs_VerifyBlock(dev, bi, i);
510 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
511 nBlocksPerState[bi->blockState]++;
513 nIllegalBlockStates++;
516 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
517 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
519 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
520 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
521 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
523 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
524 T(YAFFS_TRACE_VERIFY,
525 (TSTR("%s %d blocks"TENDSTR),
526 blockStateName[i], nBlocksPerState[i]));
528 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
529 T(YAFFS_TRACE_VERIFY,
530 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
531 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
533 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
534 T(YAFFS_TRACE_VERIFY,
535 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
536 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
538 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
539 T(YAFFS_TRACE_VERIFY,
540 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
541 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
543 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
548 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
549 * case those tests will not be performed.
551 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
553 if (obj && yaffs_SkipVerification(obj->myDev))
556 if (!(tags && obj && oh)) {
557 T(YAFFS_TRACE_VERIFY,
558 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
563 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
564 oh->type > YAFFS_OBJECT_TYPE_MAX)
565 T(YAFFS_TRACE_VERIFY,
566 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
567 tags->objectId, oh->type));
569 if (tags->objectId != obj->objectId)
570 T(YAFFS_TRACE_VERIFY,
571 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
572 tags->objectId, obj->objectId));
576 * Check that the object's parent ids match if parentCheck requested.
578 * Tests do not apply to the root object.
581 if (parentCheck && tags->objectId > 1 && !obj->parent)
582 T(YAFFS_TRACE_VERIFY,
583 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
584 tags->objectId, oh->parentObjectId));
586 if (parentCheck && obj->parent &&
587 oh->parentObjectId != obj->parent->objectId &&
588 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
589 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
590 T(YAFFS_TRACE_VERIFY,
591 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
592 tags->objectId, oh->parentObjectId, obj->parent->objectId));
594 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
595 T(YAFFS_TRACE_VERIFY,
596 (TSTR("Obj %d header name is NULL"TENDSTR),
599 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header name is 0xFF"TENDSTR),
607 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
608 __u32 level, int chunkOffset)
611 yaffs_Device *dev = obj->myDev;
617 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
618 if (tn->internal[i]) {
619 ok = yaffs_VerifyTnodeWorker(obj,
622 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
625 } else if (level == 0) {
626 yaffs_ExtendedTags tags;
627 __u32 objectId = obj->objectId;
629 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
631 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
632 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
635 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
636 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
637 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
638 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
639 objectId, chunkOffset, theChunk,
640 tags.objectId, tags.chunkId));
653 static void yaffs_VerifyFile(yaffs_Object *obj)
655 int requiredTallness;
661 yaffs_ExtendedTags tags;
668 if (yaffs_SkipVerification(obj->myDev))
672 objectId = obj->objectId;
674 /* Check file size is consistent with tnode depth */
675 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
676 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
677 requiredTallness = 0;
679 x >>= YAFFS_TNODES_INTERNAL_BITS;
683 actualTallness = obj->variant.fileVariant.topLevel;
685 /* Check that the chunks in the tnode tree are all correct.
686 * We do this by scanning through the tnode tree and
687 * checking the tags for every chunk match.
690 if (yaffs_SkipNANDVerification(dev))
693 for (i = 1; i <= lastChunk; i++) {
694 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
697 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
699 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
700 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
701 if (tags.objectId != objectId || tags.chunkId != i) {
702 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
703 objectId, i, theChunk,
704 tags.objectId, tags.chunkId));
712 static void yaffs_VerifyHardLink(yaffs_Object *obj)
714 if (obj && yaffs_SkipVerification(obj->myDev))
717 /* Verify sane equivalent object */
720 static void yaffs_VerifySymlink(yaffs_Object *obj)
722 if (obj && yaffs_SkipVerification(obj->myDev))
725 /* Verify symlink string */
728 static void yaffs_VerifySpecial(yaffs_Object *obj)
730 if (obj && yaffs_SkipVerification(obj->myDev))
734 static void yaffs_VerifyObject(yaffs_Object *obj)
743 __u32 chunkShouldNotBeDeleted;
749 if (obj->beingCreated)
754 if (yaffs_SkipVerification(dev))
757 /* Check sane object header chunk */
759 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
760 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
762 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
763 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
764 chunkValid = chunkInRange &&
765 yaffs_CheckChunkBit(dev,
766 obj->hdrChunk / dev->param.nChunksPerBlock,
767 obj->hdrChunk % dev->param.nChunksPerBlock);
768 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
771 (!chunkIdOk || chunkShouldNotBeDeleted)) {
772 T(YAFFS_TRACE_VERIFY,
773 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
774 obj->objectId, obj->hdrChunk,
775 chunkIdOk ? "" : ",out of range",
776 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
779 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
780 yaffs_ExtendedTags tags;
781 yaffs_ObjectHeader *oh;
782 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
784 oh = (yaffs_ObjectHeader *)buffer;
786 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
789 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
791 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
794 /* Verify it has a parent */
795 if (obj && !obj->fake &&
796 (!obj->parent || obj->parent->myDev != dev)) {
797 T(YAFFS_TRACE_VERIFY,
798 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
799 obj->objectId, obj->parent));
802 /* Verify parent is a directory */
803 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
804 T(YAFFS_TRACE_VERIFY,
805 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
806 obj->objectId, obj->parent->variantType));
809 switch (obj->variantType) {
810 case YAFFS_OBJECT_TYPE_FILE:
811 yaffs_VerifyFile(obj);
813 case YAFFS_OBJECT_TYPE_SYMLINK:
814 yaffs_VerifySymlink(obj);
816 case YAFFS_OBJECT_TYPE_DIRECTORY:
817 yaffs_VerifyDirectory(obj);
819 case YAFFS_OBJECT_TYPE_HARDLINK:
820 yaffs_VerifyHardLink(obj);
822 case YAFFS_OBJECT_TYPE_SPECIAL:
823 yaffs_VerifySpecial(obj);
825 case YAFFS_OBJECT_TYPE_UNKNOWN:
827 T(YAFFS_TRACE_VERIFY,
828 (TSTR("Obj %d has illegaltype %d"TENDSTR),
829 obj->objectId, obj->variantType));
834 static void yaffs_VerifyObjects(yaffs_Device *dev)
838 struct ylist_head *lh;
840 if (yaffs_SkipVerification(dev))
843 /* Iterate through the objects in each hash entry */
845 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
846 ylist_for_each(lh, &dev->objectBucket[i].list) {
848 obj = ylist_entry(lh, yaffs_Object, hashLink);
849 yaffs_VerifyObject(obj);
857 * Simple hash function. Needs to have a reasonable spread
860 static Y_INLINE int yaffs_HashFunction(int n)
863 return n % YAFFS_NOBJECT_BUCKETS;
867 * Access functions to useful fake objects.
868 * Note that root might have a presence in NAND if permissions are set.
871 yaffs_Object *yaffs_Root(yaffs_Device *dev)
876 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
878 return dev->lostNFoundDir;
883 * Erased NAND checking functions
886 int yaffs_CheckFF(__u8 *buffer, int nBytes)
888 /* Horrible, slow implementation */
897 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
900 int retval = YAFFS_OK;
901 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
902 yaffs_ExtendedTags tags;
905 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
907 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
910 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
911 T(YAFFS_TRACE_NANDACCESS,
912 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
916 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
923 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
926 yaffs_ExtendedTags *tags)
928 int retval = YAFFS_OK;
929 yaffs_ExtendedTags tempTags;
930 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
933 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
934 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
935 tempTags.objectId != tags->objectId ||
936 tempTags.chunkId != tags->chunkId ||
937 tempTags.byteCount != tags->byteCount)
940 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
945 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
947 yaffs_ExtendedTags *tags,
954 yaffs_InvalidateCheckpoint(dev);
957 yaffs_BlockInfo *bi = 0;
960 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
966 /* First check this chunk is erased, if it needs
967 * checking. The checking policy (unless forced
968 * always on) is as follows:
970 * Check the first page we try to write in a block.
971 * If the check passes then we don't need to check any
972 * more. If the check fails, we check again...
973 * If the block has been erased, we don't need to check.
975 * However, if the block has been prioritised for gc,
976 * then we think there might be something odd about
977 * this block and stop using it.
979 * Rationale: We should only ever see chunks that have
980 * not been erased if there was a partially written
981 * chunk due to power loss. This checking policy should
982 * catch that case with very few checks and thus save a
983 * lot of checks that are most likely not needed.
986 * If an erase check fails or the write fails we skip the
990 /* let's give it a try */
993 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
994 bi->skipErasedCheck = 0;
996 if (!bi->skipErasedCheck) {
997 erasedOk = yaffs_CheckChunkErased(dev, chunk);
998 if (erasedOk != YAFFS_OK) {
1000 (TSTR("**>> yaffs chunk %d was not erased"
1003 /* If not erased, delete this one,
1004 * skip rest of block and
1005 * try another chunk */
1006 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1007 yaffs_SkipRestOfBlock(dev);
1012 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1015 if(!bi->skipErasedCheck)
1016 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1018 if (writeOk != YAFFS_OK) {
1019 /* Clean up aborted write, skip to next block and
1020 * try another chunk */
1021 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1025 bi->skipErasedCheck = 1;
1027 /* Copy the data into the robustification buffer */
1028 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1030 } while (writeOk != YAFFS_OK &&
1031 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1037 T(YAFFS_TRACE_ERROR,
1038 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1041 dev->nRetriedWrites += (attempts - 1);
1048 * Block retiring for handling a broken block.
1051 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1053 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1055 yaffs_InvalidateCheckpoint(dev);
1057 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1058 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1059 T(YAFFS_TRACE_ALWAYS, (TSTR(
1060 "yaffs: Failed to mark bad and erase block %d"
1061 TENDSTR), blockInNAND));
1063 yaffs_ExtendedTags tags;
1064 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1066 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1068 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1069 yaffs_InitialiseTags(&tags);
1070 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1071 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1072 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1073 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1074 TCONT("write bad block marker to block %d")
1075 TENDSTR), blockInNAND));
1077 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1081 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1082 bi->gcPrioritise = 0;
1083 bi->needsRetiring = 0;
1085 dev->nRetiredBlocks++;
1089 * Functions for robustisizing TODO
1093 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1095 const yaffs_ExtendedTags *tags)
1099 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1100 const yaffs_ExtendedTags *tags)
1104 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1106 if (!bi->gcPrioritise) {
1107 bi->gcPrioritise = 1;
1108 dev->hasPendingPrioritisedGCs = 1;
1109 bi->chunkErrorStrikes++;
1111 if (bi->chunkErrorStrikes > 3) {
1112 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1113 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1119 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1122 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1123 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1125 yaffs_HandleChunkError(dev, bi);
1128 /* Was an actual write failure, so mark the block for retirement */
1129 bi->needsRetiring = 1;
1130 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1131 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1134 /* Delete the chunk */
1135 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1136 yaffs_SkipRestOfBlock(dev);
1140 /*---------------- Name handling functions ------------*/
1142 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1147 const YUCHAR *bname = (const YUCHAR *) name;
1149 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1151 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1152 sum += yaffs_toupper(*bname) * i;
1154 sum += (*bname) * i;
1163 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1165 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1166 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1167 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1168 yaffs_strcpy(obj->shortName, name);
1170 obj->shortName[0] = _Y('\0');
1172 obj->sum = yaffs_CalcNameSum(name);
1175 /*-------------------- TNODES -------------------
1177 * List of spare tnodes
1178 * The list is hooked together using the first pointer
1182 /* yaffs_CreateTnodes creates a bunch more tnodes and
1183 * adds them to the tnode free list.
1184 * Don't use this function directly
1186 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1189 /* Calculate the tnode size in bytes for variable width tnode support.
1190 * Must be a multiple of 32-bits */
1191 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1193 if (tnodeSize < sizeof(yaffs_Tnode))
1194 tnodeSize = sizeof(yaffs_Tnode);
1198 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1201 int tnodeSize = yaffs_CalcTnodeSize(dev);
1202 yaffs_Tnode *newTnodes;
1206 yaffs_TnodeList *tnl;
1212 /* make these things */
1214 newTnodes = YMALLOC(nTnodes * tnodeSize);
1215 mem = (__u8 *)newTnodes;
1218 T(YAFFS_TRACE_ERROR,
1219 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1223 /* Hook them into the free list */
1225 for (i = 0; i < nTnodes - 1; i++) {
1226 newTnodes[i].internal[0] = &newTnodes[i + 1];
1227 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1228 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1232 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1233 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1234 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1236 dev->freeTnodes = newTnodes;
1238 /* New hookup for wide tnodes */
1239 for (i = 0; i < nTnodes - 1; i++) {
1240 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1241 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1242 curr->internal[0] = next;
1245 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1246 curr->internal[0] = dev->freeTnodes;
1247 dev->freeTnodes = (yaffs_Tnode *)mem;
1252 dev->nFreeTnodes += nTnodes;
1253 dev->nTnodesCreated += nTnodes;
1255 /* Now add this bunch of tnodes to a list for freeing up.
1256 * NB If we can't add this to the management list it isn't fatal
1257 * but it just means we can't free this bunch of tnodes later.
1260 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1262 T(YAFFS_TRACE_ERROR,
1264 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1267 tnl->tnodes = newTnodes;
1268 tnl->next = dev->allocatedTnodeList;
1269 dev->allocatedTnodeList = tnl;
1272 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1277 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1279 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1281 yaffs_Tnode *tn = NULL;
1283 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1284 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1286 dev->nTnodesCreated++;
1288 /* If there are none left make more */
1289 if (!dev->freeTnodes)
1290 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1292 if (dev->freeTnodes) {
1293 tn = dev->freeTnodes;
1294 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1295 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1296 /* Hoosterman, this thing looks like it isn't in the list */
1297 T(YAFFS_TRACE_ALWAYS,
1298 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1301 dev->freeTnodes = dev->freeTnodes->internal[0];
1305 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1310 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1312 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1313 int tnodeSize = yaffs_CalcTnodeSize(dev);
1316 memset(tn, 0, tnodeSize);
1321 /* FreeTnode frees up a tnode and puts it back on the free list */
1322 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1325 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1327 dev->nTnodesCreated--;
1329 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1330 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1331 /* Hoosterman, this thing looks like it is already in the list */
1332 T(YAFFS_TRACE_ALWAYS,
1333 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1335 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1337 tn->internal[0] = dev->freeTnodes;
1338 dev->freeTnodes = tn;
1342 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1345 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1347 /* Free the list of allocated tnodes */
1348 yaffs_TnodeList *tmp;
1350 while (dev->allocatedTnodeList) {
1351 tmp = dev->allocatedTnodeList->next;
1353 YFREE(dev->allocatedTnodeList->tnodes);
1354 YFREE(dev->allocatedTnodeList);
1355 dev->allocatedTnodeList = tmp;
1359 dev->freeTnodes = NULL;
1360 dev->nFreeTnodes = 0;
1361 dev->nTnodesCreated = 0;
1364 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1366 dev->allocatedTnodeList = NULL;
1367 dev->freeTnodes = NULL;
1368 dev->nFreeTnodes = 0;
1369 dev->nTnodesCreated = 0;
1373 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1376 __u32 *map = (__u32 *)tn;
1382 pos &= YAFFS_TNODES_LEVEL0_MASK;
1383 val >>= dev->chunkGroupBits;
1385 bitInMap = pos * dev->tnodeWidth;
1386 wordInMap = bitInMap / 32;
1387 bitInWord = bitInMap & (32 - 1);
1389 mask = dev->tnodeMask << bitInWord;
1391 map[wordInMap] &= ~mask;
1392 map[wordInMap] |= (mask & (val << bitInWord));
1394 if (dev->tnodeWidth > (32 - bitInWord)) {
1395 bitInWord = (32 - bitInWord);
1397 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1398 map[wordInMap] &= ~mask;
1399 map[wordInMap] |= (mask & (val >> bitInWord));
1403 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1406 __u32 *map = (__u32 *)tn;
1412 pos &= YAFFS_TNODES_LEVEL0_MASK;
1414 bitInMap = pos * dev->tnodeWidth;
1415 wordInMap = bitInMap / 32;
1416 bitInWord = bitInMap & (32 - 1);
1418 val = map[wordInMap] >> bitInWord;
1420 if (dev->tnodeWidth > (32 - bitInWord)) {
1421 bitInWord = (32 - bitInWord);
1423 val |= (map[wordInMap] << bitInWord);
1426 val &= dev->tnodeMask;
1427 val <<= dev->chunkGroupBits;
1432 /* ------------------- End of individual tnode manipulation -----------------*/
1434 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1435 * The look up tree is represented by the top tnode and the number of topLevel
1436 * in the tree. 0 means only the level 0 tnode is in the tree.
1439 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1440 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1441 yaffs_FileStructure *fStruct,
1444 yaffs_Tnode *tn = fStruct->top;
1446 int requiredTallness;
1447 int level = fStruct->topLevel;
1449 /* Check sane level and chunk Id */
1450 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1453 if (chunkId > YAFFS_MAX_CHUNK_ID)
1456 /* First check we're tall enough (ie enough topLevel) */
1458 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1459 requiredTallness = 0;
1461 i >>= YAFFS_TNODES_INTERNAL_BITS;
1465 if (requiredTallness > fStruct->topLevel)
1466 return NULL; /* Not tall enough, so we can't find it */
1468 /* Traverse down to level 0 */
1469 while (level > 0 && tn) {
1470 tn = tn->internal[(chunkId >>
1471 (YAFFS_TNODES_LEVEL0_BITS +
1473 YAFFS_TNODES_INTERNAL_BITS)) &
1474 YAFFS_TNODES_INTERNAL_MASK];
1481 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1482 * This happens in two steps:
1483 * 1. If the tree isn't tall enough, then make it taller.
1484 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1486 * Used when modifying the tree.
1488 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1489 * be plugged into the ttree.
1492 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1493 yaffs_FileStructure *fStruct,
1495 yaffs_Tnode *passedTn)
1497 int requiredTallness;
1505 /* Check sane level and page Id */
1506 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1509 if (chunkId > YAFFS_MAX_CHUNK_ID)
1512 /* First check we're tall enough (ie enough topLevel) */
1514 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1515 requiredTallness = 0;
1517 x >>= YAFFS_TNODES_INTERNAL_BITS;
1522 if (requiredTallness > fStruct->topLevel) {
1523 /* Not tall enough, gotta make the tree taller */
1524 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1526 tn = yaffs_GetTnode(dev);
1529 tn->internal[0] = fStruct->top;
1531 fStruct->topLevel++;
1533 T(YAFFS_TRACE_ERROR,
1534 (TSTR("yaffs: no more tnodes" TENDSTR)));
1540 /* Traverse down to level 0, adding anything we need */
1542 l = fStruct->topLevel;
1546 while (l > 0 && tn) {
1548 (YAFFS_TNODES_LEVEL0_BITS +
1549 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1550 YAFFS_TNODES_INTERNAL_MASK;
1553 if ((l > 1) && !tn->internal[x]) {
1554 /* Add missing non-level-zero tnode */
1555 tn->internal[x] = yaffs_GetTnode(dev);
1556 if(!tn->internal[x])
1558 } else if (l == 1) {
1559 /* Looking from level 1 at level 0 */
1561 /* If we already have one, then release it.*/
1562 if (tn->internal[x])
1563 yaffs_FreeTnode(dev, tn->internal[x]);
1564 tn->internal[x] = passedTn;
1566 } else if (!tn->internal[x]) {
1567 /* Don't have one, none passed in */
1568 tn->internal[x] = yaffs_GetTnode(dev);
1569 if(!tn->internal[x])
1574 tn = tn->internal[x];
1578 /* top is level 0 */
1580 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1581 yaffs_FreeTnode(dev, passedTn);
1588 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1589 yaffs_ExtendedTags *tags, int objectId,
1594 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1595 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1596 theChunk % dev->param.nChunksPerBlock)) {
1598 if(dev->chunkGroupSize == 1)
1601 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1603 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1615 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1616 * chunks and tnodes in the file
1617 * Returns 1 if the tree was deleted.
1618 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1621 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1622 int chunkOffset, int *limit)
1627 yaffs_ExtendedTags tags;
1629 yaffs_Device *dev = in->myDev;
1635 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1637 if (tn->internal[i]) {
1638 if (limit && (*limit) < 0) {
1642 yaffs_DeleteWorker(in,
1650 YAFFS_TNODES_INTERNAL_BITS)
1655 yaffs_FreeTnode(dev,
1658 tn->internal[i] = NULL;
1662 return (allDone) ? 1 : 0;
1663 } else if (level == 0) {
1666 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1668 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1671 chunkInInode = (chunkOffset <<
1672 YAFFS_TNODES_LEVEL0_BITS) + i;
1675 yaffs_FindChunkInGroup(dev,
1681 if (foundChunk > 0) {
1682 yaffs_DeleteChunk(dev,
1687 *limit = *limit - 1;
1694 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1698 return (i < 0) ? 1 : 0;
1708 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1710 yaffs_BlockInfo *theBlock;
1712 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1714 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->param.nChunksPerBlock);
1716 theBlock->softDeletions++;
1721 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1722 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1724 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1727 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1728 __u32 level, int chunkOffset)
1733 yaffs_Device *dev = in->myDev;
1738 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1740 if (tn->internal[i]) {
1742 yaffs_SoftDeleteWorker(in,
1748 YAFFS_TNODES_INTERNAL_BITS)
1751 yaffs_FreeTnode(dev,
1754 tn->internal[i] = NULL;
1756 /* Hoosterman... how could this happen? */
1760 return (allDone) ? 1 : 0;
1761 } else if (level == 0) {
1763 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1764 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1766 /* Note this does not find the real chunk, only the chunk group.
1767 * We make an assumption that a chunk group is not larger than
1770 yaffs_SoftDeleteChunk(dev, theChunk);
1771 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1785 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1788 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1789 if (obj->nDataChunks <= 0) {
1790 /* Empty file with no duplicate object headers, just delete it immediately */
1791 yaffs_FreeTnode(obj->myDev,
1792 obj->variant.fileVariant.top);
1793 obj->variant.fileVariant.top = NULL;
1794 T(YAFFS_TRACE_TRACING,
1795 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1797 yaffs_DoGenericObjectDeletion(obj);
1799 yaffs_SoftDeleteWorker(obj,
1800 obj->variant.fileVariant.top,
1801 obj->variant.fileVariant.
1803 obj->softDeleted = 1;
1808 /* Pruning removes any part of the file structure tree that is beyond the
1809 * bounds of the file (ie that does not point to chunks).
1811 * A file should only get pruned when its size is reduced.
1813 * Before pruning, the chunks must be pulled from the tree and the
1814 * level 0 tnode entries must be zeroed out.
1815 * Could also use this for file deletion, but that's probably better handled
1816 * by a special case.
1818 * This function is recursive. For levels > 0 the function is called again on
1819 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1820 * If there is no data in a subtree then it is pruned.
1823 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1824 __u32 level, int del0)
1833 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1834 if (tn->internal[i]) {
1836 yaffs_PruneWorker(dev, tn->internal[i],
1838 (i == 0) ? del0 : 1);
1841 if (tn->internal[i])
1845 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1846 __u32 *map = (__u32 *)tn;
1848 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1854 if (hasData == 0 && del0) {
1855 /* Free and return NULL */
1857 yaffs_FreeTnode(dev, tn);
1867 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1868 yaffs_FileStructure *fStruct)
1875 if (fStruct->topLevel > 0) {
1877 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1879 /* Now we have a tree with all the non-zero branches NULL but the height
1880 * is the same as it was.
1881 * Let's see if we can trim internal tnodes to shorten the tree.
1882 * We can do this if only the 0th element in the tnode is in use
1883 * (ie all the non-zero are NULL)
1886 while (fStruct->topLevel && !done) {
1890 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1891 if (tn->internal[i])
1896 fStruct->top = tn->internal[0];
1897 fStruct->topLevel--;
1898 yaffs_FreeTnode(dev, tn);
1908 /*-------------------- End of File Structure functions.-------------------*/
1910 /* yaffs_CreateFreeObjects creates a bunch more objects and
1911 * adds them to the object free list.
1913 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1916 yaffs_Object *newObjects;
1917 yaffs_ObjectList *list;
1922 /* make these things */
1923 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1924 list = YMALLOC(sizeof(yaffs_ObjectList));
1926 if (!newObjects || !list) {
1935 T(YAFFS_TRACE_ALLOCATE,
1936 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1940 /* Hook them into the free list */
1941 for (i = 0; i < nObjects - 1; i++) {
1942 newObjects[i].siblings.next =
1943 (struct ylist_head *)(&newObjects[i + 1]);
1946 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1947 dev->freeObjects = newObjects;
1948 dev->nFreeObjects += nObjects;
1949 dev->nObjectsCreated += nObjects;
1951 /* Now add this bunch of Objects to a list for freeing up. */
1953 list->objects = newObjects;
1954 list->next = dev->allocatedObjectList;
1955 dev->allocatedObjectList = list;
1961 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1962 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1964 yaffs_Object *tn = NULL;
1966 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1967 tn = YMALLOC(sizeof(yaffs_Object));
1969 dev->nObjectsCreated++;
1971 /* If there are none left make more */
1972 if (!dev->freeObjects)
1973 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1975 if (dev->freeObjects) {
1976 tn = dev->freeObjects;
1978 (yaffs_Object *) (dev->freeObjects->siblings.next);
1979 dev->nFreeObjects--;
1983 /* Now sweeten it up... */
1985 memset(tn, 0, sizeof(yaffs_Object));
1986 tn->beingCreated = 1;
1990 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1991 YINIT_LIST_HEAD(&(tn->hardLinks));
1992 YINIT_LIST_HEAD(&(tn->hashLink));
1993 YINIT_LIST_HEAD(&tn->siblings);
1996 /* Now make the directory sane */
1998 tn->parent = dev->rootDir;
1999 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2002 /* Add it to the lost and found directory.
2003 * NB Can't put root or lostNFound in lostNFound so
2004 * check if lostNFound exists first
2006 if (dev->lostNFoundDir)
2007 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2009 tn->beingCreated = 0;
2012 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2017 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2022 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2024 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2025 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2026 obj->unlinkAllowed = 0; /* ... or unlink it */
2029 obj->yst_mode = mode;
2031 obj->hdrChunk = 0; /* Not a valid chunk. */
2038 static void yaffs_UnhashObject(yaffs_Object *tn)
2041 yaffs_Device *dev = tn->myDev;
2043 /* If it is still linked into the bucket list, free from the list */
2044 if (!ylist_empty(&tn->hashLink)) {
2045 ylist_del_init(&tn->hashLink);
2046 bucket = yaffs_HashFunction(tn->objectId);
2047 dev->objectBucket[bucket].count--;
2051 /* FreeObject frees up a Object and puts it back on the free list */
2052 static void yaffs_FreeObject(yaffs_Object *tn)
2054 yaffs_Device *dev = tn->myDev;
2056 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2062 if (!ylist_empty(&tn->siblings))
2067 /* We're still hooked up to a cached inode.
2068 * Don't delete now, but mark for later deletion
2070 tn->deferedFree = 1;
2074 yaffs_UnhashObject(tn);
2076 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2078 dev->nObjectsCreated--;
2081 /* Link into the free list. */
2082 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2083 dev->freeObjects = tn;
2084 dev->nFreeObjects++;
2086 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2090 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2092 if (obj->deferedFree)
2093 yaffs_FreeObject(obj);
2097 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2099 /* Free the list of allocated Objects */
2101 yaffs_ObjectList *tmp;
2103 while (dev->allocatedObjectList) {
2104 tmp = dev->allocatedObjectList->next;
2105 YFREE(dev->allocatedObjectList->objects);
2106 YFREE(dev->allocatedObjectList);
2108 dev->allocatedObjectList = tmp;
2111 dev->freeObjects = NULL;
2112 dev->nFreeObjects = 0;
2113 dev->nObjectsCreated = 0;
2116 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2120 dev->allocatedObjectList = NULL;
2121 dev->freeObjects = NULL;
2122 dev->nFreeObjects = 0;
2124 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2125 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2126 dev->objectBucket[i].count = 0;
2130 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2134 int lowest = 999999;
2137 /* Search for the shortest list or one that
2141 for (i = 0; i < 10 && lowest > 4; i++) {
2142 dev->bucketFinder++;
2143 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2144 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2145 lowest = dev->objectBucket[dev->bucketFinder].count;
2146 l = dev->bucketFinder;
2154 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2156 int bucket = yaffs_FindNiceObjectBucket(dev);
2158 /* Now find an object value that has not already been taken
2159 * by scanning the list.
2163 struct ylist_head *i;
2165 __u32 n = (__u32) bucket;
2167 /* yaffs_CheckObjectHashSanity(); */
2171 n += YAFFS_NOBJECT_BUCKETS;
2172 if (1 || dev->objectBucket[bucket].count > 0) {
2173 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2174 /* If there is already one in the list */
2175 if (i && ylist_entry(i, yaffs_Object,
2176 hashLink)->objectId == n) {
2186 static void yaffs_HashObject(yaffs_Object *in)
2188 int bucket = yaffs_HashFunction(in->objectId);
2189 yaffs_Device *dev = in->myDev;
2191 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2192 dev->objectBucket[bucket].count++;
2195 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2197 int bucket = yaffs_HashFunction(number);
2198 struct ylist_head *i;
2201 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2202 /* Look if it is in the list */
2204 in = ylist_entry(i, yaffs_Object, hashLink);
2205 if (in->objectId == number) {
2207 /* Don't tell the VFS about this one if it is defered free */
2208 if (in->deferedFree)
2219 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2220 yaffs_ObjectType type)
2222 yaffs_Object *theObject=NULL;
2223 yaffs_Tnode *tn = NULL;
2226 number = yaffs_CreateNewObjectNumber(dev);
2228 if (type == YAFFS_OBJECT_TYPE_FILE) {
2229 tn = yaffs_GetTnode(dev);
2234 theObject = yaffs_AllocateEmptyObject(dev);
2237 yaffs_FreeTnode(dev,tn);
2243 theObject->fake = 0;
2244 theObject->renameAllowed = 1;
2245 theObject->unlinkAllowed = 1;
2246 theObject->objectId = number;
2247 yaffs_HashObject(theObject);
2248 theObject->variantType = type;
2249 #ifdef CONFIG_YAFFS_WINCE
2250 yfsd_WinFileTimeNow(theObject->win_atime);
2251 theObject->win_ctime[0] = theObject->win_mtime[0] =
2252 theObject->win_atime[0];
2253 theObject->win_ctime[1] = theObject->win_mtime[1] =
2254 theObject->win_atime[1];
2258 theObject->yst_atime = theObject->yst_mtime =
2259 theObject->yst_ctime = Y_CURRENT_TIME;
2262 case YAFFS_OBJECT_TYPE_FILE:
2263 theObject->variant.fileVariant.fileSize = 0;
2264 theObject->variant.fileVariant.scannedFileSize = 0;
2265 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2266 theObject->variant.fileVariant.topLevel = 0;
2267 theObject->variant.fileVariant.top = tn;
2269 case YAFFS_OBJECT_TYPE_DIRECTORY:
2270 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2273 case YAFFS_OBJECT_TYPE_SYMLINK:
2274 case YAFFS_OBJECT_TYPE_HARDLINK:
2275 case YAFFS_OBJECT_TYPE_SPECIAL:
2276 /* No action required */
2278 case YAFFS_OBJECT_TYPE_UNKNOWN:
2279 /* todo this should not happen */
2287 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2289 yaffs_ObjectType type)
2291 yaffs_Object *theObject = NULL;
2294 theObject = yaffs_FindObjectByNumber(dev, number);
2297 theObject = yaffs_CreateNewObject(dev, number, type);
2304 static YCHAR *yaffs_CloneString(const YCHAR *str)
2306 YCHAR *newStr = NULL;
2312 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2313 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2315 yaffs_strncpy(newStr, str,len);
2323 * Mknod (create) a new object.
2324 * equivalentObject only has meaning for a hard link;
2325 * aliasString only has meaning for a symlink.
2326 * rdev only has meaning for devices (a subset of special objects)
2329 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2330 yaffs_Object *parent,
2335 yaffs_Object *equivalentObject,
2336 const YCHAR *aliasString, __u32 rdev)
2341 yaffs_Device *dev = parent->myDev;
2343 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2344 if (yaffs_FindObjectByName(parent, name))
2347 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2348 str = yaffs_CloneString(aliasString);
2353 in = yaffs_CreateNewObject(dev, -1, type);
2368 in->variantType = type;
2370 in->yst_mode = mode;
2372 #ifdef CONFIG_YAFFS_WINCE
2373 yfsd_WinFileTimeNow(in->win_atime);
2374 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2375 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2378 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2380 in->yst_rdev = rdev;
2384 in->nDataChunks = 0;
2386 yaffs_SetObjectName(in, name);
2389 yaffs_AddObjectToDirectory(parent, in);
2391 in->myDev = parent->myDev;
2394 case YAFFS_OBJECT_TYPE_SYMLINK:
2395 in->variant.symLinkVariant.alias = str;
2397 case YAFFS_OBJECT_TYPE_HARDLINK:
2398 in->variant.hardLinkVariant.equivalentObject =
2400 in->variant.hardLinkVariant.equivalentObjectId =
2401 equivalentObject->objectId;
2402 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2404 case YAFFS_OBJECT_TYPE_FILE:
2405 case YAFFS_OBJECT_TYPE_DIRECTORY:
2406 case YAFFS_OBJECT_TYPE_SPECIAL:
2407 case YAFFS_OBJECT_TYPE_UNKNOWN:
2412 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2413 /* Could not create the object header, fail the creation */
2414 yaffs_DeleteObject(in);
2418 yaffs_UpdateParent(parent);
2424 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2425 __u32 mode, __u32 uid, __u32 gid)
2427 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2428 uid, gid, NULL, NULL, 0);
2431 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2432 __u32 mode, __u32 uid, __u32 gid)
2434 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2435 mode, uid, gid, NULL, NULL, 0);
2438 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2439 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2441 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2442 uid, gid, NULL, NULL, rdev);
2445 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2446 __u32 mode, __u32 uid, __u32 gid,
2449 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2450 uid, gid, NULL, alias, 0);
2453 /* yaffs_Link returns the object id of the equivalent object.*/
2454 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2455 yaffs_Object *equivalentObject)
2457 /* Get the real object in case we were fed a hard link as an equivalent object */
2458 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2460 if (yaffs_MknodObject
2461 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2462 equivalentObject, NULL, 0)) {
2463 return equivalentObject;
2470 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2471 const YCHAR *newName, int force, int shadows)
2476 yaffs_Object *existingTarget;
2479 newDir = obj->parent; /* use the old directory */
2481 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2482 T(YAFFS_TRACE_ALWAYS,
2484 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2489 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2490 if (obj->myDev->param.isYaffs2)
2491 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2493 unlinkOp = (newDir == obj->myDev->unlinkedDir
2494 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2496 deleteOp = (newDir == obj->myDev->deletedDir);
2498 existingTarget = yaffs_FindObjectByName(newDir, newName);
2500 /* If the object is a file going into the unlinked directory,
2501 * then it is OK to just stuff it in since duplicate names are allowed.
2502 * else only proceed if the new name does not exist and if we're putting
2503 * it into a directory.
2510 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2511 yaffs_SetObjectName(obj, newName);
2514 yaffs_AddObjectToDirectory(newDir, obj);
2519 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2520 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2527 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2528 yaffs_Object *newDir, const YCHAR *newName)
2530 yaffs_Object *obj = NULL;
2531 yaffs_Object *existingTarget = NULL;
2537 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2539 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2542 dev = oldDir->myDev;
2544 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2545 /* Special case for case insemsitive systems (eg. WinCE).
2546 * While look-up is case insensitive, the name isn't.
2547 * Therefore we might want to change x.txt to X.txt
2549 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2553 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2557 obj = yaffs_FindObjectByName(oldDir, oldName);
2559 if (obj && obj->renameAllowed) {
2561 /* Now do the handling for an existing target, if there is one */
2563 existingTarget = yaffs_FindObjectByName(newDir, newName);
2564 if (existingTarget &&
2565 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2566 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2567 /* There is a target that is a non-empty directory, so we fail */
2568 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2569 } else if (existingTarget && existingTarget != obj) {
2570 /* Nuke the target first, using shadowing,
2571 * but only if it isn't the same object.
2573 * Note we must disable gc otherwise it can mess up the shadowing.
2577 yaffs_ChangeObjectName(obj, newDir, newName, force,
2578 existingTarget->objectId);
2579 existingTarget->isShadowed = 1;
2580 yaffs_UnlinkObject(existingTarget);
2584 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2586 yaffs_UpdateParent(oldDir);
2587 if(newDir != oldDir)
2588 yaffs_UpdateParent(newDir);
2595 /*------------------------- Block Management and Page Allocation ----------------*/
2597 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2599 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2601 dev->blockInfo = NULL;
2602 dev->chunkBits = NULL;
2604 dev->allocationBlock = -1; /* force it to get a new one */
2606 /* If the first allocation strategy fails, thry the alternate one */
2607 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2608 if (!dev->blockInfo) {
2609 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2610 dev->blockInfoAlt = 1;
2612 dev->blockInfoAlt = 0;
2614 if (dev->blockInfo) {
2615 /* Set up dynamic blockinfo stuff. */
2616 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2617 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2618 if (!dev->chunkBits) {
2619 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2620 dev->chunkBitsAlt = 1;
2622 dev->chunkBitsAlt = 0;
2625 if (dev->blockInfo && dev->chunkBits) {
2626 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2627 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2634 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2636 if (dev->blockInfoAlt && dev->blockInfo)
2637 YFREE_ALT(dev->blockInfo);
2638 else if (dev->blockInfo)
2639 YFREE(dev->blockInfo);
2641 dev->blockInfoAlt = 0;
2643 dev->blockInfo = NULL;
2645 if (dev->chunkBitsAlt && dev->chunkBits)
2646 YFREE_ALT(dev->chunkBits);
2647 else if (dev->chunkBits)
2648 YFREE(dev->chunkBits);
2649 dev->chunkBitsAlt = 0;
2650 dev->chunkBits = NULL;
2653 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2654 yaffs_BlockInfo *bi)
2660 if (!dev->param.isYaffs2)
2661 return 1; /* disqualification only applies to yaffs2. */
2663 if (!bi->hasShrinkHeader)
2664 return 1; /* can gc */
2666 /* Find the oldest dirty sequence number if we don't know it and save it
2667 * so we don't have to keep recomputing it.
2669 if (!dev->oldestDirtySequence) {
2670 seq = dev->sequenceNumber;
2672 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2674 b = yaffs_GetBlockInfo(dev, i);
2675 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2676 (b->pagesInUse - b->softDeletions) <
2677 dev->param.nChunksPerBlock && b->sequenceNumber < seq) {
2678 seq = b->sequenceNumber;
2681 dev->oldestDirtySequence = seq;
2684 /* Can't do gc of this block if there are any blocks older than this one that have
2687 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2691 * yaffs_FindRefreshBlock()
2692 * periodically finds the oldest full block by sequence number for refreshing.
2695 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2700 __u32 oldestSequence = 0;
2702 yaffs_BlockInfo *bi;
2705 * If refresh period < 10 then refreshing is disabled.
2707 if(dev->param.refreshPeriod < 10 ||
2708 !dev->param.isYaffs2)
2712 * Fix broken values.
2714 if(dev->refreshSkip > dev->param.refreshPeriod)
2715 dev->refreshSkip = dev->param.refreshPeriod;
2717 if(dev->refreshSkip > 0){
2723 * Refresh skip is now zero.
2724 * We'll do a refresh this time around....
2725 * Update the refresh skip and find the oldest block.
2727 dev->refreshSkip = dev->param.refreshPeriod;
2728 dev->refreshCount++;
2730 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2732 bi = yaffs_GetBlockInfo(dev, b);
2735 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2738 bi->sequenceNumber < oldestSequence){
2740 oldestSequence = bi->sequenceNumber;
2747 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2748 dev->refreshCount, oldest, oldestSequence));
2755 * FindDiretiestBlock is used to select the dirtiest block (or close enough)
2756 * for garbage collection.
2759 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2762 int b = dev->currentDirtyChecker;
2768 int prioritised = 0;
2769 yaffs_BlockInfo *bi;
2770 int pendingPrioritisedExist = 0;
2772 /* First let's see if we need to grab a prioritised block */
2773 if (dev->hasPendingPrioritisedGCs) {
2774 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2776 bi = yaffs_GetBlockInfo(dev, i);
2777 /* yaffs_VerifyBlock(dev,bi,i); */
2779 if (bi->gcPrioritise) {
2780 pendingPrioritisedExist = 1;
2781 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2782 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2783 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2786 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2791 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2792 dev->hasPendingPrioritisedGCs = 0;
2795 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2797 * else (we're doing a leasurely gc), then we only bother to do this if the
2798 * block has only a few pages in use.
2801 dev->nonAggressiveSkip--;
2803 if (!aggressive && (dev->nonAggressiveSkip > 0))
2808 (aggressive) ? dev->param.nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2812 dev->internalEndBlock - dev->internalStartBlock + 1;
2815 dev->internalEndBlock - dev->internalStartBlock + 1;
2816 iterations = iterations / 16;
2817 if (iterations > 200)
2821 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2823 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2824 b = dev->internalStartBlock;
2826 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2827 T(YAFFS_TRACE_ERROR,
2828 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2832 bi = yaffs_GetBlockInfo(dev, b);
2834 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2835 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2836 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2838 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2842 dev->currentDirtyChecker = b;
2846 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2847 dev->param.nChunksPerBlock - pagesInUse, prioritised));
2850 dev->oldestDirtySequence = 0;
2853 dev->nonAggressiveSkip = 4;
2858 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2860 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2864 /* If the block is still healthy erase it and mark as clean.
2865 * If the block has had a data failure, then retire it.
2868 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2869 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2870 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2872 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2874 if (!bi->needsRetiring) {
2875 yaffs_InvalidateCheckpoint(dev);
2876 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2878 dev->nErasureFailures++;
2879 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2880 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2885 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2887 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2888 if (!yaffs_CheckChunkErased
2889 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2890 T(YAFFS_TRACE_ERROR,
2892 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2893 TENDSTR), blockNo, i));
2899 /* Clean it up... */
2900 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2901 bi->sequenceNumber = 0;
2902 dev->nErasedBlocks++;
2904 bi->softDeletions = 0;
2905 bi->hasShrinkHeader = 0;
2906 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2907 bi->gcPrioritise = 0;
2908 yaffs_ClearChunkBits(dev, blockNo);
2910 T(YAFFS_TRACE_ERASE,
2911 (TSTR("Erased block %d" TENDSTR), blockNo));
2913 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2915 yaffs_RetireBlock(dev, blockNo);
2916 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2917 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2921 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2925 yaffs_BlockInfo *bi;
2927 if (dev->nErasedBlocks < 1) {
2928 /* Hoosterman we've got a problem.
2929 * Can't get space to gc
2931 T(YAFFS_TRACE_ERROR,
2932 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2937 /* Find an empty block. */
2939 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2940 dev->allocationBlockFinder++;
2941 if (dev->allocationBlockFinder < dev->internalStartBlock
2942 || dev->allocationBlockFinder > dev->internalEndBlock) {
2943 dev->allocationBlockFinder = dev->internalStartBlock;
2946 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2948 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2949 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2950 dev->sequenceNumber++;
2951 bi->sequenceNumber = dev->sequenceNumber;
2952 dev->nErasedBlocks--;
2953 T(YAFFS_TRACE_ALLOCATE,
2954 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2955 dev->allocationBlockFinder, dev->sequenceNumber,
2956 dev->nErasedBlocks));
2957 return dev->allocationBlockFinder;
2961 T(YAFFS_TRACE_ALWAYS,
2963 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2964 TENDSTR), dev->nErasedBlocks));
2971 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2973 if (!dev->nCheckpointBlocksRequired &&
2974 dev->param.isYaffs2) {
2975 /* Not a valid value so recalculate */
2978 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2979 int tnodeSize = yaffs_CalcTnodeSize(dev);
2981 nBytes += sizeof(yaffs_CheckpointValidity);
2982 nBytes += sizeof(yaffs_CheckpointDevice);
2983 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2984 nBytes += devBlocks * dev->chunkBitmapStride;
2985 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2986 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2987 nBytes += sizeof(yaffs_CheckpointValidity);
2988 nBytes += sizeof(__u32); /* checksum*/
2990 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2992 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
2994 dev->nCheckpointBlocksRequired = nBlocks;
2997 return dev->nCheckpointBlocksRequired;
3001 * Check if there's space to allocate...
3002 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3004 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
3007 int reservedBlocks = dev->param.nReservedBlocks;
3008 int checkpointBlocks;
3010 if (dev->param.isYaffs2) {
3011 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
3012 dev->blocksInCheckpoint;
3013 if (checkpointBlocks < 0)
3014 checkpointBlocks = 0;
3016 checkpointBlocks = 0;
3019 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3021 return (dev->nFreeChunks > reservedChunks);
3024 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3025 yaffs_BlockInfo **blockUsedPtr)
3028 yaffs_BlockInfo *bi;
3030 if (dev->allocationBlock < 0) {
3031 /* Get next block to allocate off */
3032 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3033 dev->allocationPage = 0;
3036 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
3037 /* Not enough space to allocate unless we're allowed to use the reserve. */
3041 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3042 && dev->allocationPage == 0) {
3043 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3046 /* Next page please.... */
3047 if (dev->allocationBlock >= 0) {
3048 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3050 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3051 dev->allocationPage;
3053 yaffs_SetChunkBit(dev, dev->allocationBlock,
3054 dev->allocationPage);
3056 dev->allocationPage++;
3060 /* If the block is full set the state to full */
3061 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3062 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3063 dev->allocationBlock = -1;
3072 T(YAFFS_TRACE_ERROR,
3073 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3078 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3082 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3084 if (dev->allocationBlock > 0)
3085 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3092 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3093 * if we don't want to write to it.
3095 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3097 if(dev->allocationBlock > 0){
3098 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3099 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3100 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3101 dev->allocationBlock = -1;
3107 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3113 int retVal = YAFFS_OK;
3116 int isCheckpointBlock;
3120 int chunksBefore = yaffs_GetErasedChunks(dev);
3123 yaffs_ExtendedTags tags;
3125 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3127 yaffs_Object *object;
3129 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3132 T(YAFFS_TRACE_TRACING,
3133 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3136 bi->hasShrinkHeader,
3139 /*yaffs_VerifyFreeChunks(dev); */
3141 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3142 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3144 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3146 /* Take off the number of soft deleted entries because
3147 * they're going to get really deleted during GC.
3149 if(dev->gcChunk == 0) /* first time through for this block */
3150 dev->nFreeChunks -= bi->softDeletions;
3154 if (isCheckpointBlock ||
3155 !yaffs_StillSomeChunkBits(dev, block)) {
3156 T(YAFFS_TRACE_TRACING,
3158 ("Collecting block %d that has no chunks in use" TENDSTR),
3160 yaffs_BlockBecameDirty(dev, block);
3163 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3165 yaffs_VerifyBlock(dev, bi, block);
3167 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 10;
3168 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3170 for (/* init already done */;
3171 retVal == YAFFS_OK &&
3172 dev->gcChunk < dev->param.nChunksPerBlock &&
3173 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3175 dev->gcChunk++, oldChunk++) {
3176 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3178 /* This page is in use and might need to be copied off */
3184 yaffs_InitialiseTags(&tags);
3186 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3190 yaffs_FindObjectByNumber(dev,
3193 T(YAFFS_TRACE_GC_DETAIL,
3195 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3196 dev->gcChunk, tags.objectId, tags.chunkId,
3199 if (object && !yaffs_SkipVerification(dev)) {
3200 if (tags.chunkId == 0)
3201 matchingChunk = object->hdrChunk;
3202 else if (object->softDeleted)
3203 matchingChunk = oldChunk; /* Defeat the test */
3205 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3207 if (oldChunk != matchingChunk)
3208 T(YAFFS_TRACE_ERROR,
3209 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3210 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3215 T(YAFFS_TRACE_ERROR,
3217 ("page %d in gc has no object: %d %d %d "
3219 tags.objectId, tags.chunkId, tags.byteCount));
3224 object->softDeleted &&
3225 tags.chunkId != 0) {
3226 /* Data chunk in a soft deleted file, throw it away
3227 * It's a soft deleted data chunk,
3228 * No need to copy this, just forget about it and
3229 * fix up the object.
3232 object->nDataChunks--;
3234 if (object->nDataChunks <= 0) {
3235 /* remeber to clean up the object */
3236 dev->gcCleanupList[cleanups] =
3242 /* Todo object && object->deleted && object->nDataChunks == 0 */
3243 /* Deleted object header with no data chunks.
3244 * Can be discarded and the file deleted.
3246 object->hdrChunk = 0;
3247 yaffs_FreeTnode(object->myDev,
3250 object->variant.fileVariant.top = NULL;
3251 yaffs_DoGenericObjectDeletion(object);
3253 } else if (object) {
3254 /* It's either a data chunk in a live file or
3255 * an ObjectHeader, so we're interested in it.
3256 * NB Need to keep the ObjectHeaders of deleted files
3257 * until the whole file has been deleted off
3259 tags.serialNumber++;
3263 if (tags.chunkId == 0) {
3264 /* It is an object Id,
3265 * We need to nuke the shrinkheader flags first
3266 * Also need to clean up shadowing.
3267 * We no longer want the shrinkHeader flag since its work is done
3268 * and if it is left in place it will mess up scanning.
3271 yaffs_ObjectHeader *oh;
3272 oh = (yaffs_ObjectHeader *)buffer;
3274 tags.extraIsShrinkHeader = 0;
3275 oh->shadowsObject = 0;
3276 oh->inbandShadowsObject = 0;
3277 if(object->variantType == YAFFS_OBJECT_TYPE_FILE)
3278 oh->fileSize = object->variant.fileVariant.fileSize;
3279 tags.extraShadows = 0;
3281 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3283 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3286 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3289 retVal = YAFFS_FAIL;
3292 /* Ok, now fix up the Tnodes etc. */
3294 if (tags.chunkId == 0) {
3296 object->hdrChunk = newChunk;
3297 object->serial = tags.serialNumber;
3299 /* It's a data chunk */
3301 ok = yaffs_PutChunkIntoFile
3309 if (retVal == YAFFS_OK)
3310 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3315 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3318 /* Do any required cleanups */
3319 for (i = 0; i < cleanups; i++) {
3320 /* Time to delete the file too */
3322 yaffs_FindObjectByNumber(dev,
3323 dev->gcCleanupList[i]);
3325 yaffs_FreeTnode(dev,
3326 object->variant.fileVariant.
3328 object->variant.fileVariant.top = NULL;
3331 ("yaffs: About to finally delete object %d"
3332 TENDSTR), object->objectId));
3333 yaffs_DoGenericObjectDeletion(object);
3334 object->myDev->nDeletedFiles--;
3341 yaffs_VerifyCollectedBlock(dev, bi, block);
3345 /* If the gc completed then clear the current gcBlock so that we find another. */
3346 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3347 chunksAfter = yaffs_GetErasedChunks(dev);
3348 if (chunksBefore >= chunksAfter) {
3351 ("gc did not increase free chunks before %d after %d"
3352 TENDSTR), chunksBefore, chunksAfter));
3363 /* New garbage collector
3364 * If we're very low on erased blocks then we do aggressive garbage collection
3365 * otherwise we do "leasurely" garbage collection.
3366 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3367 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3369 * The idea is to help clear out space in a more spread-out manner.
3370 * Dunno if it really does anything useful.
3372 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3376 int gcOk = YAFFS_OK;
3379 int checkpointBlockAdjust;
3381 if (dev->isDoingGC) {
3382 /* Bail out so we don't get recursive gc */
3386 /* This loop should pass the first time.
3387 * We'll only see looping here if the erase of the collected block fails.
3393 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3394 if (checkpointBlockAdjust < 0)
3395 checkpointBlockAdjust = 0;
3397 /* If we need a block soon then do aggressive gc.*/
3398 if (dev->nErasedBlocks < (dev->param.nReservedBlocks + checkpointBlockAdjust + 2))
3403 /* If we don't already have a block being gc'd then see if we should start another */
3405 if (dev->gcBlock < 1 && !aggressive) {
3406 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3409 if (dev->gcBlock < 1) {
3410 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3414 block = dev->gcBlock;
3417 dev->garbageCollections++;
3419 dev->passiveGarbageCollections++;
3423 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3424 dev->nErasedBlocks, aggressive));
3426 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3429 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && block > 0) {
3432 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3433 TENDSTR), dev->nErasedBlocks, maxTries, block));
3435 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3439 return aggressive ? gcOk : YAFFS_OK;
3442 /*------------------------- TAGS --------------------------------*/
3444 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3447 return (tags->chunkId == chunkInObject &&
3448 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3453 /*-------------------- Data file manipulation -----------------*/
3455 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3456 yaffs_ExtendedTags *tags)
3458 /*Get the Tnode, then get the level 0 offset chunk offset */
3461 yaffs_ExtendedTags localTags;
3464 yaffs_Device *dev = in->myDev;
3467 /* Passed a NULL, so use our own tags space */
3471 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3474 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3477 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3483 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3484 yaffs_ExtendedTags *tags)
3486 /* Get the Tnode, then get the level 0 offset chunk offset */
3489 yaffs_ExtendedTags localTags;
3491 yaffs_Device *dev = in->myDev;
3495 /* Passed a NULL, so use our own tags space */
3499 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3503 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3506 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3509 /* Delete the entry in the filestructure (if found) */
3511 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3517 #ifdef YAFFS_PARANOID
3519 static int yaffs_CheckFileSanity(yaffs_Object *in)
3527 yaffs_Tags localTags;
3528 yaffs_Tags *tags = &localTags;
3532 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3535 objId = in->objectId;
3536 fSize = in->variant.fileVariant.fileSize;
3538 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3540 for (chunk = 1; chunk <= nChunks; chunk++) {
3541 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3546 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3548 if (yaffs_CheckChunkBits
3549 (dev, theChunk / dev->param.nChunksPerBlock,
3550 theChunk % dev->param.nChunksPerBlock)) {
3552 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3556 (tags, in->objectId, chunk, chunkDeleted)) {
3566 /* T(("No level 0 found for %d\n", chunk)); */
3570 return failed ? YAFFS_FAIL : YAFFS_OK;
3575 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3576 int chunkInNAND, int inScan)
3578 /* NB inScan is zero unless scanning.
3579 * For forward scanning, inScan is > 0;
3580 * for backward scanning inScan is < 0
3582 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3586 yaffs_Device *dev = in->myDev;
3588 yaffs_ExtendedTags existingTags;
3589 yaffs_ExtendedTags newTags;
3590 unsigned existingSerial, newSerial;
3592 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3593 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3594 * If it is not during Scanning then something went wrong!
3597 T(YAFFS_TRACE_ERROR,
3599 ("yaffs tragedy:attempt to put data chunk into a non-file"
3604 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3608 tn = yaffs_AddOrFindLevel0Tnode(dev,
3609 &in->variant.fileVariant,
3616 /* Dummy insert, bail now */
3619 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3622 /* If we're scanning then we need to test for duplicates
3623 * NB This does not need to be efficient since it should only ever
3624 * happen when the power fails during a write, then only one
3625 * chunk should ever be affected.
3627 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3628 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3631 if (existingChunk > 0) {
3632 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3633 * thus we have to do a FindChunkInFile to get the real chunk id.
3635 * We have a duplicate now we need to decide which one to use:
3637 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3638 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3639 * YAFFS1: Get both sets of tags and compare serial numbers.
3643 /* Only do this for forward scanning */
3644 yaffs_ReadChunkWithTagsFromNAND(dev,
3648 /* Do a proper find */
3650 yaffs_FindChunkInFile(in, chunkInInode,
3654 if (existingChunk <= 0) {
3655 /*Hoosterman - how did this happen? */
3657 T(YAFFS_TRACE_ERROR,
3659 ("yaffs tragedy: existing chunk < 0 in scan"
3664 /* NB The deleted flags should be false, otherwise the chunks will
3665 * not be loaded during a scan
3669 newSerial = newTags.serialNumber;
3670 existingSerial = existingTags.serialNumber;
3674 (in->myDev->param.isYaffs2 ||
3675 existingChunk <= 0 ||
3676 ((existingSerial + 1) & 3) == newSerial)) {
3677 /* Forward scanning.
3679 * Delete the old one and drop through to update the tnode
3681 yaffs_DeleteChunk(dev, existingChunk, 1,
3684 /* Backward scanning or we want to use the existing one
3686 * Delete the new one and return early so that the tnode isn't changed
3688 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3696 if (existingChunk == 0)
3699 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3704 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3707 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3709 if (chunkInNAND >= 0)
3710 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3713 T(YAFFS_TRACE_NANDACCESS,
3714 (TSTR("Chunk %d not found zero instead" TENDSTR),
3716 /* get sane (zero) data if you read a hole */
3717 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3723 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3727 yaffs_ExtendedTags tags;
3728 yaffs_BlockInfo *bi;
3734 block = chunkId / dev->param.nChunksPerBlock;
3735 page = chunkId % dev->param.nChunksPerBlock;
3738 if (!yaffs_CheckChunkBit(dev, block, page))
3739 T(YAFFS_TRACE_VERIFY,
3740 (TSTR("Deleting invalid chunk %d"TENDSTR),
3743 bi = yaffs_GetBlockInfo(dev, block);
3745 T(YAFFS_TRACE_DELETION,
3746 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3749 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3751 yaffs_InitialiseTags(&tags);
3753 tags.chunkDeleted = 1;
3755 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3756 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3758 dev->nUnmarkedDeletions++;
3761 /* Pull out of the management area.
3762 * If the whole block became dirty, this will kick off an erasure.
3764 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3765 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3766 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3767 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3770 yaffs_ClearChunkBit(dev, block, page);
3774 if (bi->pagesInUse == 0 &&
3775 !bi->hasShrinkHeader &&
3776 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3777 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3778 yaffs_BlockBecameDirty(dev, block);
3785 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3786 const __u8 *buffer, int nBytes,
3789 /* Find old chunk Need to do this to get serial number
3790 * Write new one and patch into tree.
3791 * Invalidate old tags.
3795 yaffs_ExtendedTags prevTags;
3798 yaffs_ExtendedTags newTags;
3800 yaffs_Device *dev = in->myDev;
3802 yaffs_CheckGarbageCollection(dev);
3804 /* Get the previous chunk at this location in the file if it exists.
3805 * If it does not exist then put a zero into the tree. This creates
3806 * the tnode now, rather than later when it is harder to clean up.
3808 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3809 if(prevChunkId < 1 &&
3810 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
3813 /* Set up new tags */
3814 yaffs_InitialiseTags(&newTags);
3816 newTags.chunkId = chunkInInode;
3817 newTags.objectId = in->objectId;
3818 newTags.serialNumber =
3819 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3820 newTags.byteCount = nBytes;
3822 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
3823 T(YAFFS_TRACE_ERROR,
3824 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3830 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3833 if (newChunkId > 0) {
3834 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3836 if (prevChunkId > 0)
3837 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3839 yaffs_CheckFileSanity(in);
3845 /* UpdateObjectHeader updates the header on NAND for an object.
3846 * If name is not NULL, then that new name is used.
3848 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3849 int isShrink, int shadows)
3852 yaffs_BlockInfo *bi;
3854 yaffs_Device *dev = in->myDev;
3861 yaffs_ExtendedTags newTags;
3862 yaffs_ExtendedTags oldTags;
3863 YCHAR *alias = NULL;
3865 __u8 *buffer = NULL;
3866 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3868 yaffs_ObjectHeader *oh = NULL;
3870 yaffs_strcpy(oldName, _Y("silly old name"));
3874 in == dev->rootDir || /* The rootDir should also be saved */
3877 yaffs_CheckGarbageCollection(dev);
3878 yaffs_CheckObjectDetailsLoaded(in);
3880 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3881 oh = (yaffs_ObjectHeader *) buffer;
3883 prevChunkId = in->hdrChunk;
3885 if (prevChunkId > 0) {
3886 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3889 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3891 memcpy(oldName, oh->name, sizeof(oh->name));
3894 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3896 oh->type = in->variantType;
3897 oh->yst_mode = in->yst_mode;
3898 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3900 #ifdef CONFIG_YAFFS_WINCE
3901 oh->win_atime[0] = in->win_atime[0];
3902 oh->win_ctime[0] = in->win_ctime[0];
3903 oh->win_mtime[0] = in->win_mtime[0];
3904 oh->win_atime[1] = in->win_atime[1];
3905 oh->win_ctime[1] = in->win_ctime[1];
3906 oh->win_mtime[1] = in->win_mtime[1];
3908 oh->yst_uid = in->yst_uid;
3909 oh->yst_gid = in->yst_gid;
3910 oh->yst_atime = in->yst_atime;
3911 oh->yst_mtime = in->yst_mtime;
3912 oh->yst_ctime = in->yst_ctime;
3913 oh->yst_rdev = in->yst_rdev;
3916 oh->parentObjectId = in->parent->objectId;
3918 oh->parentObjectId = 0;
3920 if (name && *name) {
3921 memset(oh->name, 0, sizeof(oh->name));
3922 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3923 } else if (prevChunkId > 0)
3924 memcpy(oh->name, oldName, sizeof(oh->name));
3926 memset(oh->name, 0, sizeof(oh->name));
3928 oh->isShrink = isShrink;
3930 switch (in->variantType) {
3931 case YAFFS_OBJECT_TYPE_UNKNOWN:
3932 /* Should not happen */
3934 case YAFFS_OBJECT_TYPE_FILE:
3936 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3937 || oh->parentObjectId ==
3938 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3939 fileVariant.fileSize;
3941 case YAFFS_OBJECT_TYPE_HARDLINK:
3942 oh->equivalentObjectId =
3943 in->variant.hardLinkVariant.equivalentObjectId;
3945 case YAFFS_OBJECT_TYPE_SPECIAL:
3948 case YAFFS_OBJECT_TYPE_DIRECTORY:
3951 case YAFFS_OBJECT_TYPE_SYMLINK:
3952 alias = in->variant.symLinkVariant.alias;
3954 alias = _Y("no alias");
3955 yaffs_strncpy(oh->alias,
3957 YAFFS_MAX_ALIAS_LENGTH);
3958 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3963 yaffs_InitialiseTags(&newTags);
3965 newTags.chunkId = 0;
3966 newTags.objectId = in->objectId;
3967 newTags.serialNumber = in->serial;
3969 /* Add extra info for file header */
3971 newTags.extraHeaderInfoAvailable = 1;
3972 newTags.extraParentObjectId = oh->parentObjectId;
3973 newTags.extraFileLength = oh->fileSize;
3974 newTags.extraIsShrinkHeader = oh->isShrink;
3975 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3976 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3977 newTags.extraObjectType = in->variantType;
3979 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3981 /* Create new chunk in NAND */
3983 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3984 (prevChunkId > 0) ? 1 : 0);
3986 if (newChunkId >= 0) {
3988 in->hdrChunk = newChunkId;
3990 if (prevChunkId > 0) {
3991 yaffs_DeleteChunk(dev, prevChunkId, 1,
3995 if (!yaffs_ObjectHasCachedWriteData(in))
3998 /* If this was a shrink, then mark the block that the chunk lives on */
4000 bi = yaffs_GetBlockInfo(in->myDev,
4001 newChunkId / in->myDev->param.nChunksPerBlock);
4002 bi->hasShrinkHeader = 1;
4007 retVal = newChunkId;
4012 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4017 /*------------------------ Short Operations Cache ----------------------------------------
4018 * In many situations where there is no high level buffering (eg WinCE) a lot of
4019 * reads might be short sequential reads, and a lot of writes may be short
4020 * sequential writes. eg. scanning/writing a jpeg file.
4021 * In these cases, a short read/write cache can provide a huge perfomance benefit
4022 * with dumb-as-a-rock code.
4023 * In Linux, the page cache provides read buffering aand the short op cache provides write
4026 * There are a limited number (~10) of cache chunks per device so that we don't
4027 * need a very intelligent search.
4030 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4032 yaffs_Device *dev = obj->myDev;
4034 yaffs_ChunkCache *cache;
4035 int nCaches = obj->myDev->param.nShortOpCaches;
4037 for (i = 0; i < nCaches; i++) {
4038 cache = &dev->srCache[i];
4039 if (cache->object == obj &&
4048 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4050 yaffs_Device *dev = obj->myDev;
4051 int lowest = -99; /* Stop compiler whining. */
4053 yaffs_ChunkCache *cache;
4054 int chunkWritten = 0;
4055 int nCaches = obj->myDev->param.nShortOpCaches;
4061 /* Find the dirty cache for this object with the lowest chunk id. */
4062 for (i = 0; i < nCaches; i++) {
4063 if (dev->srCache[i].object == obj &&
4064 dev->srCache[i].dirty) {
4066 || dev->srCache[i].chunkId <
4068 cache = &dev->srCache[i];
4069 lowest = cache->chunkId;
4074 if (cache && !cache->locked) {
4075 /* Write it out and free it up */
4078 yaffs_WriteChunkDataToObject(cache->object,
4084 cache->object = NULL;
4087 } while (cache && chunkWritten > 0);
4090 /* Hoosterman, disk full while writing cache out. */
4091 T(YAFFS_TRACE_ERROR,
4092 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4099 /*yaffs_FlushEntireDeviceCache(dev)
4104 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4107 int nCaches = dev->param.nShortOpCaches;
4110 /* Find a dirty object in the cache and flush it...
4111 * until there are no further dirty objects.
4115 for (i = 0; i < nCaches && !obj; i++) {
4116 if (dev->srCache[i].object &&
4117 dev->srCache[i].dirty)
4118 obj = dev->srCache[i].object;
4122 yaffs_FlushFilesChunkCache(obj);
4129 /* Grab us a cache chunk for use.
4130 * First look for an empty one.
4131 * Then look for the least recently used non-dirty one.
4132 * Then look for the least recently used dirty one...., flush and look again.
4134 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4138 if (dev->param.nShortOpCaches > 0) {
4139 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4140 if (!dev->srCache[i].object)
4141 return &dev->srCache[i];
4148 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4150 yaffs_ChunkCache *cache;
4151 yaffs_Object *theObj;
4156 if (dev->param.nShortOpCaches > 0) {
4157 /* Try find a non-dirty one... */
4159 cache = yaffs_GrabChunkCacheWorker(dev);
4162 /* They were all dirty, find the last recently used object and flush
4163 * its cache, then find again.
4164 * NB what's here is not very accurate, we actually flush the object
4165 * the last recently used page.
4168 /* With locking we can't assume we can use entry zero */
4175 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4176 if (dev->srCache[i].object &&
4177 !dev->srCache[i].locked &&
4178 (dev->srCache[i].lastUse < usage || !cache)) {
4179 usage = dev->srCache[i].lastUse;
4180 theObj = dev->srCache[i].object;
4181 cache = &dev->srCache[i];
4186 if (!cache || cache->dirty) {
4187 /* Flush and try again */
4188 yaffs_FlushFilesChunkCache(theObj);
4189 cache = yaffs_GrabChunkCacheWorker(dev);
4199 /* Find a cached chunk */
4200 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4203 yaffs_Device *dev = obj->myDev;
4205 if (dev->param.nShortOpCaches > 0) {
4206 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4207 if (dev->srCache[i].object == obj &&
4208 dev->srCache[i].chunkId == chunkId) {
4211 return &dev->srCache[i];
4218 /* Mark the chunk for the least recently used algorithym */
4219 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4223 if (dev->param.nShortOpCaches > 0) {
4224 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4225 /* Reset the cache usages */
4227 for (i = 1; i < dev->param.nShortOpCaches; i++)
4228 dev->srCache[i].lastUse = 0;
4235 cache->lastUse = dev->srLastUse;
4242 /* Invalidate a single cache page.
4243 * Do this when a whole page gets written,
4244 * ie the short cache for this page is no longer valid.
4246 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4248 if (object->myDev->param.nShortOpCaches > 0) {
4249 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4252 cache->object = NULL;
4256 /* Invalidate all the cache pages associated with this object
4257 * Do this whenever ther file is deleted or resized.
4259 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4262 yaffs_Device *dev = in->myDev;
4264 if (dev->param.nShortOpCaches > 0) {
4265 /* Invalidate it. */
4266 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4267 if (dev->srCache[i].object == in)
4268 dev->srCache[i].object = NULL;
4273 /*--------------------- Checkpointing --------------------*/
4276 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4278 yaffs_CheckpointValidity cp;
4280 memset(&cp, 0, sizeof(cp));
4282 cp.structType = sizeof(cp);
4283 cp.magic = YAFFS_MAGIC;
4284 cp.version = YAFFS_CHECKPOINT_VERSION;
4285 cp.head = (head) ? 1 : 0;
4287 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4291 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4293 yaffs_CheckpointValidity cp;
4296 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4299 ok = (cp.structType == sizeof(cp)) &&
4300 (cp.magic == YAFFS_MAGIC) &&
4301 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4302 (cp.head == ((head) ? 1 : 0));
4306 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4309 cp->nErasedBlocks = dev->nErasedBlocks;
4310 cp->allocationBlock = dev->allocationBlock;
4311 cp->allocationPage = dev->allocationPage;
4312 cp->nFreeChunks = dev->nFreeChunks;
4314 cp->nDeletedFiles = dev->nDeletedFiles;
4315 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4316 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4317 cp->sequenceNumber = dev->sequenceNumber;
4321 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4322 yaffs_CheckpointDevice *cp)
4324 dev->nErasedBlocks = cp->nErasedBlocks;
4325 dev->allocationBlock = cp->allocationBlock;
4326 dev->allocationPage = cp->allocationPage;
4327 dev->nFreeChunks = cp->nFreeChunks;
4329 dev->nDeletedFiles = cp->nDeletedFiles;
4330 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4331 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4332 dev->sequenceNumber = cp->sequenceNumber;
4336 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4338 yaffs_CheckpointDevice cp;
4340 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4344 /* Write device runtime values*/
4345 yaffs_DeviceToCheckpointDevice(&cp, dev);
4346 cp.structType = sizeof(cp);
4348 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4350 /* Write block info */
4352 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4353 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4356 /* Write chunk bits */
4358 nBytes = nBlocks * dev->chunkBitmapStride;
4359 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4365 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4367 yaffs_CheckpointDevice cp;
4369 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4373 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4377 if (cp.structType != sizeof(cp))
4381 yaffs_CheckpointDeviceToDevice(dev, &cp);
4383 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4385 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4389 nBytes = nBlocks * dev->chunkBitmapStride;
4391 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4396 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4400 cp->objectId = obj->objectId;
4401 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4402 cp->hdrChunk = obj->hdrChunk;
4403 cp->variantType = obj->variantType;
4404 cp->deleted = obj->deleted;
4405 cp->softDeleted = obj->softDeleted;
4406 cp->unlinked = obj->unlinked;
4407 cp->fake = obj->fake;
4408 cp->renameAllowed = obj->renameAllowed;
4409 cp->unlinkAllowed = obj->unlinkAllowed;
4410 cp->serial = obj->serial;
4411 cp->nDataChunks = obj->nDataChunks;
4413 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4414 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4415 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4416 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4419 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4422 yaffs_Object *parent;
4424 if (obj->variantType != cp->variantType) {
4425 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4426 TCONT("chunk %d does not match existing object type %d")
4427 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4432 obj->objectId = cp->objectId;
4435 parent = yaffs_FindOrCreateObjectByNumber(
4438 YAFFS_OBJECT_TYPE_DIRECTORY);
4443 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4444 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4445 TCONT(" chunk %d Parent type, %d, not directory")
4447 cp->objectId, cp->parentId, cp->variantType,
4448 cp->hdrChunk, parent->variantType));
4451 yaffs_AddObjectToDirectory(parent, obj);
4454 obj->hdrChunk = cp->hdrChunk;
4455 obj->variantType = cp->variantType;
4456 obj->deleted = cp->deleted;
4457 obj->softDeleted = cp->softDeleted;
4458 obj->unlinked = cp->unlinked;
4459 obj->fake = cp->fake;
4460 obj->renameAllowed = cp->renameAllowed;
4461 obj->unlinkAllowed = cp->unlinkAllowed;
4462 obj->serial = cp->serial;
4463 obj->nDataChunks = cp->nDataChunks;
4465 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4466 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4467 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4468 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4470 if (obj->hdrChunk > 0)
4471 obj->lazyLoaded = 1;
4477 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4478 __u32 level, int chunkOffset)
4481 yaffs_Device *dev = in->myDev;
4483 int tnodeSize = yaffs_CalcTnodeSize(dev);
4488 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4489 if (tn->internal[i]) {
4490 ok = yaffs_CheckpointTnodeWorker(in,
4493 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4496 } else if (level == 0) {
4497 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4498 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4500 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4508 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4510 __u32 endMarker = ~0;
4513 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4514 ok = yaffs_CheckpointTnodeWorker(obj,
4515 obj->variant.fileVariant.top,
4516 obj->variant.fileVariant.topLevel,
4519 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4526 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4530 yaffs_Device *dev = obj->myDev;
4531 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4534 int tnodeSize = yaffs_CalcTnodeSize(dev);
4536 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4538 while (ok && (~baseChunk)) {
4540 /* Read level 0 tnode */
4543 tn = yaffs_GetTnodeRaw(dev);
4545 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4550 ok = yaffs_AddOrFindLevel0Tnode(dev,
4556 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4560 T(YAFFS_TRACE_CHECKPOINT, (
4561 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4562 nread, baseChunk, ok));
4568 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4571 yaffs_CheckpointObject cp;
4574 struct ylist_head *lh;
4577 /* Iterate through the objects in each hash entry,
4578 * dumping them to the checkpointing stream.
4581 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4582 ylist_for_each(lh, &dev->objectBucket[i].list) {
4584 obj = ylist_entry(lh, yaffs_Object, hashLink);
4585 if (!obj->deferedFree) {
4586 yaffs_ObjectToCheckpointObject(&cp, obj);
4587 cp.structType = sizeof(cp);
4589 T(YAFFS_TRACE_CHECKPOINT, (
4590 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4591 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4593 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4595 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4596 ok = yaffs_WriteCheckpointTnodes(obj);
4602 /* Dump end of list */
4603 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4604 cp.structType = sizeof(cp);
4607 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4612 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4615 yaffs_CheckpointObject cp;
4618 yaffs_Object *hardList = NULL;
4620 while (ok && !done) {
4621 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4622 if (cp.structType != sizeof(cp)) {
4623 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4624 cp.structType, (int)sizeof(cp), ok));
4628 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4629 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4631 if (ok && cp.objectId == ~0)
4634 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4636 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4639 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4640 ok = yaffs_ReadCheckpointTnodes(obj);
4641 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4642 obj->hardLinks.next =
4643 (struct ylist_head *) hardList;
4652 yaffs_HardlinkFixup(dev, hardList);
4657 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4659 __u32 checkpointSum;
4662 yaffs_GetCheckpointSum(dev, &checkpointSum);
4664 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4672 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4674 __u32 checkpointSum0;
4675 __u32 checkpointSum1;
4678 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4680 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4685 if (checkpointSum0 != checkpointSum1)
4692 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4696 if (dev->param.skipCheckpointWrite || !dev->param.isYaffs2) {
4697 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4702 ok = yaffs_CheckpointOpen(dev, 1);
4705 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4706 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4709 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4710 ok = yaffs_WriteCheckpointDevice(dev);
4713 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4714 ok = yaffs_WriteCheckpointObjects(dev);
4717 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4718 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4722 ok = yaffs_WriteCheckpointSum(dev);
4724 if (!yaffs_CheckpointClose(dev))
4728 dev->isCheckpointed = 1;
4730 dev->isCheckpointed = 0;
4732 return dev->isCheckpointed;
4735 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4739 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4740 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4745 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4748 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4749 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4752 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4753 ok = yaffs_ReadCheckpointDevice(dev);
4756 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4757 ok = yaffs_ReadCheckpointObjects(dev);
4760 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4761 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4765 ok = yaffs_ReadCheckpointSum(dev);
4766 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4769 if (!yaffs_CheckpointClose(dev))
4773 dev->isCheckpointed = 1;
4775 dev->isCheckpointed = 0;
4781 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4783 if (dev->isCheckpointed ||
4784 dev->blocksInCheckpoint > 0) {
4785 dev->isCheckpointed = 0;
4786 yaffs_CheckpointInvalidateStream(dev);
4787 if (dev->param.markSuperBlockDirty)
4788 dev->param.markSuperBlockDirty(dev);
4793 int yaffs_CheckpointSave(yaffs_Device *dev)
4796 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4798 yaffs_VerifyObjects(dev);
4799 yaffs_VerifyBlocks(dev);
4800 yaffs_VerifyFreeChunks(dev);
4802 if (!dev->isCheckpointed) {
4803 yaffs_InvalidateCheckpoint(dev);
4804 yaffs_WriteCheckpointData(dev);
4807 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4809 return dev->isCheckpointed;
4812 int yaffs_CheckpointRestore(yaffs_Device *dev)
4815 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4817 retval = yaffs_ReadCheckpointData(dev);
4819 if (dev->isCheckpointed) {
4820 yaffs_VerifyObjects(dev);
4821 yaffs_VerifyBlocks(dev);
4822 yaffs_VerifyFreeChunks(dev);
4825 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4830 /*--------------------- File read/write ------------------------
4831 * Read and write have very similar structures.
4832 * In general the read/write has three parts to it
4833 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4834 * Some complete chunks
4835 * An incomplete chunk to end off with
4837 * Curve-balls: the first chunk might also be the last chunk.
4840 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4849 yaffs_ChunkCache *cache;
4856 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4857 /* start = offset % dev->nDataBytesPerChunk; */
4858 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4861 /* OK now check for the curveball where the start and end are in
4864 if ((start + n) < dev->nDataBytesPerChunk)
4867 nToCopy = dev->nDataBytesPerChunk - start;
4869 cache = yaffs_FindChunkCache(in, chunk);
4871 /* If the chunk is already in the cache or it is less than a whole chunk
4872 * or we're using inband tags then use the cache (if there is caching)
4873 * else bypass the cache.
4875 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
4876 if (dev->param.nShortOpCaches > 0) {
4878 /* If we can't find the data in the cache, then load it up. */
4881 cache = yaffs_GrabChunkCache(in->myDev);
4883 cache->chunkId = chunk;
4886 yaffs_ReadChunkDataFromObject(in, chunk,
4892 yaffs_UseChunkCache(dev, cache, 0);
4897 memcpy(buffer, &cache->data[start], nToCopy);
4901 /* Read into the local buffer then copy..*/
4904 yaffs_GetTempBuffer(dev, __LINE__);
4905 yaffs_ReadChunkDataFromObject(in, chunk,
4908 memcpy(buffer, &localBuffer[start], nToCopy);
4911 yaffs_ReleaseTempBuffer(dev, localBuffer,
4917 /* A full chunk. Read directly into the supplied buffer. */
4918 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4932 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4933 int nBytes, int writeThrough)
4942 int startOfWrite = offset;
4943 int chunkWritten = 0;
4951 while (n > 0 && chunkWritten >= 0) {
4952 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4953 /* start = offset % dev->nDataBytesPerChunk; */
4954 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4956 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4957 start >= dev->nDataBytesPerChunk) {
4958 T(YAFFS_TRACE_ERROR, (
4959 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4961 (int)offset, chunk, start));
4965 /* OK now check for the curveball where the start and end are in
4969 if ((start + n) < dev->nDataBytesPerChunk) {
4972 /* Now folks, to calculate how many bytes to write back....
4973 * If we're overwriting and not writing to then end of file then
4974 * we need to write back as much as was there before.
4977 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4979 if (chunkStart > in->variant.fileVariant.fileSize)
4980 nBytesRead = 0; /* Past end of file */
4982 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4984 if (nBytesRead > dev->nDataBytesPerChunk)
4985 nBytesRead = dev->nDataBytesPerChunk;
4989 (start + n)) ? nBytesRead : (start + n);
4991 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4995 nToCopy = dev->nDataBytesPerChunk - start;
4996 nToWriteBack = dev->nDataBytesPerChunk;
4999 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5000 /* An incomplete start or end chunk (or maybe both start and end chunk),
5001 * or we're using inband tags, so we want to use the cache buffers.
5003 if (dev->param.nShortOpCaches > 0) {
5004 yaffs_ChunkCache *cache;
5005 /* If we can't find the data in the cache, then load the cache */
5006 cache = yaffs_FindChunkCache(in, chunk);
5009 && yaffs_CheckSpaceForAllocation(in->
5011 cache = yaffs_GrabChunkCache(in->myDev);
5013 cache->chunkId = chunk;
5016 yaffs_ReadChunkDataFromObject(in, chunk,
5021 !yaffs_CheckSpaceForAllocation(in->myDev)) {
5022 /* Drop the cache if it was a read cache item and
5023 * no space check has been made for it.
5029 yaffs_UseChunkCache(dev, cache, 1);
5033 memcpy(&cache->data[start], buffer,
5038 cache->nBytes = nToWriteBack;
5042 yaffs_WriteChunkDataToObject
5045 cache->data, cache->nBytes,
5051 chunkWritten = -1; /* fail the write */
5054 /* An incomplete start or end chunk (or maybe both start and end chunk)
5055 * Read into the local buffer then copy, then copy over and write back.
5059 yaffs_GetTempBuffer(dev, __LINE__);
5061 yaffs_ReadChunkDataFromObject(in, chunk,
5066 memcpy(&localBuffer[start], buffer, nToCopy);
5069 yaffs_WriteChunkDataToObject(in, chunk,
5074 yaffs_ReleaseTempBuffer(dev, localBuffer,
5080 /* A full chunk. Write directly from the supplied buffer. */
5085 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5086 dev->nDataBytesPerChunk,
5089 /* Since we've overwritten the cached data, we better invalidate it. */
5090 yaffs_InvalidateChunkCache(in, chunk);
5093 if (chunkWritten >= 0) {
5102 /* Update file object */
5104 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5105 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5113 /* ---------------------- File resizing stuff ------------------ */
5115 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5118 yaffs_Device *dev = in->myDev;
5119 int oldFileSize = in->variant.fileVariant.fileSize;
5121 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5123 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5124 dev->nDataBytesPerChunk;
5128 /* Delete backwards so that we don't end up with holes if
5129 * power is lost part-way through the operation.
5131 for (i = lastDel; i >= startDel; i--) {
5132 /* NB this could be optimised somewhat,
5133 * eg. could retrieve the tags and write them without
5134 * using yaffs_DeleteChunk
5137 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5140 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5142 ((dev->internalEndBlock +
5143 1) * dev->param.nChunksPerBlock)) {
5144 T(YAFFS_TRACE_ALWAYS,
5145 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5149 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5156 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5159 int oldFileSize = in->variant.fileVariant.fileSize;
5160 __u32 newSizeOfPartialChunk;
5163 yaffs_Device *dev = in->myDev;
5165 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5167 yaffs_FlushFilesChunkCache(in);
5168 yaffs_InvalidateWholeChunkCache(in);
5170 yaffs_CheckGarbageCollection(dev);
5172 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5175 if (newSize == oldFileSize)
5178 if (newSize < oldFileSize) {
5180 yaffs_PruneResizedChunks(in, newSize);
5182 if (newSizeOfPartialChunk != 0) {
5183 int lastChunk = 1 + newFullChunks;
5185 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5187 /* Got to read and rewrite the last chunk with its new size and zero pad */
5188 yaffs_ReadChunkDataFromObject(in, lastChunk,
5191 memset(localBuffer + newSizeOfPartialChunk, 0,
5192 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5194 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5195 newSizeOfPartialChunk, 1);
5197 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5200 in->variant.fileVariant.fileSize = newSize;
5202 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5204 /* newsSize > oldFileSize */
5205 in->variant.fileVariant.fileSize = newSize;
5208 /* Write a new object header to reflect the resize.
5209 * show we've shrunk the file, if need be
5210 * Do this only if the file is not in the deleted directories
5211 * and is not shadowed.
5215 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5216 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5217 yaffs_UpdateObjectHeader(in, NULL, 0,
5218 (newSize < oldFileSize) ? 1 : 0, 0);
5223 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5225 YCHAR *alias = NULL;
5226 obj = yaffs_GetEquivalentObject(obj);
5228 switch (obj->variantType) {
5229 case YAFFS_OBJECT_TYPE_FILE:
5230 return obj->variant.fileVariant.fileSize;
5231 case YAFFS_OBJECT_TYPE_SYMLINK:
5232 alias = obj->variant.symLinkVariant.alias;
5235 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5243 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5247 yaffs_FlushFilesChunkCache(in);
5248 if(dataSync) /* Only sync data */
5252 #ifdef CONFIG_YAFFS_WINCE
5253 yfsd_WinFileTimeNow(in->win_mtime);
5256 in->yst_mtime = Y_CURRENT_TIME;
5261 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5262 0) ? YAFFS_OK : YAFFS_FAIL;
5272 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5275 /* First off, invalidate the file's data in the cache, without flushing. */
5276 yaffs_InvalidateWholeChunkCache(in);
5278 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5279 /* Move to the unlinked directory so we have a record that it was deleted. */
5280 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5284 yaffs_RemoveObjectFromDirectory(in);
5285 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5288 yaffs_FreeObject(in);
5293 /* yaffs_DeleteFile deletes the whole file data
5294 * and the inode associated with the file.
5295 * It does not delete the links associated with the file.
5297 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5301 int immediateDeletion = 0;
5304 immediateDeletion = 1;
5306 if (immediateDeletion) {
5308 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5309 _Y("deleted"), 0, 0);
5310 T(YAFFS_TRACE_TRACING,
5311 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5314 in->myDev->nDeletedFiles++;
5315 if (1 || in->myDev->param.isYaffs2)
5316 yaffs_ResizeFile(in, 0);
5317 yaffs_SoftDeleteFile(in);
5320 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5321 _Y("unlinked"), 0, 0);
5328 int yaffs_DeleteFile(yaffs_Object *in)
5330 int retVal = YAFFS_OK;
5331 int deleted = in->deleted;
5333 yaffs_ResizeFile(in, 0);
5335 if (in->nDataChunks > 0) {
5336 /* Use soft deletion if there is data in the file.
5337 * That won't be the case if it has been resized to zero.
5340 retVal = yaffs_UnlinkFileIfNeeded(in);
5342 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5345 in->myDev->nDeletedFiles++;
5346 yaffs_SoftDeleteFile(in);
5348 return deleted ? YAFFS_OK : YAFFS_FAIL;
5350 /* The file has no data chunks so we toss it immediately */
5351 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5352 in->variant.fileVariant.top = NULL;
5353 yaffs_DoGenericObjectDeletion(in);
5359 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5361 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5362 !(ylist_empty(&obj->variant.directoryVariant.children));
5365 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5367 /* First check that the directory is empty. */
5368 if (yaffs_IsNonEmptyDirectory(obj))
5371 return yaffs_DoGenericObjectDeletion(obj);
5374 static int yaffs_DeleteSymLink(yaffs_Object *in)
5376 if(in->variant.symLinkVariant.alias)
5377 YFREE(in->variant.symLinkVariant.alias);
5378 in->variant.symLinkVariant.alias=NULL;
5380 return yaffs_DoGenericObjectDeletion(in);
5383 static int yaffs_DeleteHardLink(yaffs_Object *in)
5385 /* remove this hardlink from the list assocaited with the equivalent
5388 ylist_del_init(&in->hardLinks);
5389 return yaffs_DoGenericObjectDeletion(in);
5392 int yaffs_DeleteObject(yaffs_Object *obj)
5395 switch (obj->variantType) {
5396 case YAFFS_OBJECT_TYPE_FILE:
5397 retVal = yaffs_DeleteFile(obj);
5399 case YAFFS_OBJECT_TYPE_DIRECTORY:
5400 return yaffs_DeleteDirectory(obj);
5402 case YAFFS_OBJECT_TYPE_SYMLINK:
5403 retVal = yaffs_DeleteSymLink(obj);
5405 case YAFFS_OBJECT_TYPE_HARDLINK:
5406 retVal = yaffs_DeleteHardLink(obj);
5408 case YAFFS_OBJECT_TYPE_SPECIAL:
5409 retVal = yaffs_DoGenericObjectDeletion(obj);
5411 case YAFFS_OBJECT_TYPE_UNKNOWN:
5413 break; /* should not happen. */
5419 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5422 int immediateDeletion = 0;
5425 immediateDeletion = 1;
5428 yaffs_UpdateParent(obj->parent);
5430 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5431 return yaffs_DeleteHardLink(obj);
5432 } else if (!ylist_empty(&obj->hardLinks)) {
5433 /* Curve ball: We're unlinking an object that has a hardlink.
5435 * This problem arises because we are not strictly following
5436 * The Linux link/inode model.
5438 * We can't really delete the object.
5439 * Instead, we do the following:
5440 * - Select a hardlink.
5441 * - Unhook it from the hard links
5442 * - Move it from its parent directory (so that the rename can work)
5443 * - Rename the object to the hardlink's name.
5444 * - Delete the hardlink
5448 yaffs_Object *parent;
5450 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5452 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5454 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5455 parent = hl->parent;
5457 ylist_del_init(&hl->hardLinks);
5459 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5461 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5463 if (retVal == YAFFS_OK)
5464 retVal = yaffs_DoGenericObjectDeletion(hl);
5468 } else if (immediateDeletion) {
5469 switch (obj->variantType) {
5470 case YAFFS_OBJECT_TYPE_FILE:
5471 return yaffs_DeleteFile(obj);
5473 case YAFFS_OBJECT_TYPE_DIRECTORY:
5474 return yaffs_DeleteDirectory(obj);
5476 case YAFFS_OBJECT_TYPE_SYMLINK:
5477 return yaffs_DeleteSymLink(obj);
5479 case YAFFS_OBJECT_TYPE_SPECIAL:
5480 return yaffs_DoGenericObjectDeletion(obj);
5482 case YAFFS_OBJECT_TYPE_HARDLINK:
5483 case YAFFS_OBJECT_TYPE_UNKNOWN:
5487 } else if(yaffs_IsNonEmptyDirectory(obj))
5490 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5491 _Y("unlinked"), 0, 0);
5495 static int yaffs_UnlinkObject(yaffs_Object *obj)
5498 if (obj && obj->unlinkAllowed)
5499 return yaffs_UnlinkWorker(obj);
5504 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5508 obj = yaffs_FindObjectByName(dir, name);
5509 return yaffs_UnlinkObject(obj);
5512 /*----------------------- Initialisation Scanning ---------------------- */
5514 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5515 int backwardScanning)
5519 if (!backwardScanning) {
5520 /* Handle YAFFS1 forward scanning case
5521 * For YAFFS1 we always do the deletion
5525 /* Handle YAFFS2 case (backward scanning)
5526 * If the shadowed object exists then ignore.
5528 obj = yaffs_FindObjectByNumber(dev, objId);
5533 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5534 * We put it in unlinked dir to be cleaned up after the scanning
5537 yaffs_FindOrCreateObjectByNumber(dev, objId,
5538 YAFFS_OBJECT_TYPE_FILE);
5541 obj->isShadowed = 1;
5542 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5543 obj->variant.fileVariant.shrinkSize = 0;
5544 obj->valid = 1; /* So that we don't read any other info for this file */
5554 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5561 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5563 in = yaffs_FindObjectByNumber(dev,
5564 hl->variant.hardLinkVariant.
5565 equivalentObjectId);
5568 /* Add the hardlink pointers */
5569 hl->variant.hardLinkVariant.equivalentObject = in;
5570 ylist_add(&hl->hardLinks, &in->hardLinks);
5572 /* Todo Need to report/handle this better.
5573 * Got a problem... hardlink to a non-existant object
5575 hl->variant.hardLinkVariant.equivalentObject = NULL;
5576 YINIT_LIST_HEAD(&hl->hardLinks);
5586 static int ybicmp(const void *a, const void *b)
5588 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5589 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5590 register int ablock = ((yaffs_BlockIndex *)a)->block;
5591 register int bblock = ((yaffs_BlockIndex *)b)->block;
5593 return ablock - bblock;
5599 struct yaffs_ShadowFixerStruct {
5602 struct yaffs_ShadowFixerStruct *next;
5606 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5609 * Sort out state of unlinked and deleted objects after scanning.
5611 struct ylist_head *i;
5612 struct ylist_head *n;
5615 /* Soft delete all the unlinked files */
5616 ylist_for_each_safe(i, n,
5617 &dev->unlinkedDir->variant.directoryVariant.children) {
5619 l = ylist_entry(i, yaffs_Object, siblings);
5620 yaffs_DeleteObject(l);
5624 ylist_for_each_safe(i, n,
5625 &dev->deletedDir->variant.directoryVariant.children) {
5627 l = ylist_entry(i, yaffs_Object, siblings);
5628 yaffs_DeleteObject(l);
5635 * This code iterates through all the objects making sure that they are rooted.
5636 * Any unrooted objects are re-rooted in lost+found.
5637 * An object needs to be in one of:
5638 * - Directly under deleted, unlinked
5639 * - Directly or indirectly under root.
5642 * This code assumes that we don't ever change the current relationships between
5644 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5645 * lostNfound->parent == rootDir
5647 * This fixes the problem where directories might have inadvertently been deleted
5648 * leaving the object "hanging" without being rooted in the directory tree.
5651 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5653 return (obj == dev->deletedDir ||
5654 obj == dev->unlinkedDir||
5655 obj == dev->rootDir);
5658 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5661 yaffs_Object *parent;
5663 struct ylist_head *lh;
5664 struct ylist_head *n;
5669 /* Iterate through the objects in each hash entry,
5670 * looking at each object.
5671 * Make sure it is rooted.
5674 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5675 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5677 obj = ylist_entry(lh, yaffs_Object, hashLink);
5678 parent= obj->parent;
5680 if(yaffs_HasNULLParent(dev,obj)){
5681 /* These directories are not hanging */
5684 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5686 else if(yaffs_HasNULLParent(dev,parent))
5690 * Need to follow the parent chain to see if it is hanging.
5695 while(parent != dev->rootDir &&
5697 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5699 parent = parent->parent;
5702 if(parent != dev->rootDir)
5707 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5709 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5718 * Delete directory contents for cleaning up lost and found.
5720 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5723 struct ylist_head *lh;
5724 struct ylist_head *n;
5726 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5729 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5731 obj = ylist_entry(lh, yaffs_Object, siblings);
5732 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5733 yaffs_DeleteDirectoryContents(obj);
5736 (TSTR("Deleting lost_found object %d" TENDSTR),
5739 /* Need to use UnlinkObject since Delete would not handle
5740 * hardlinked objects correctly.
5742 yaffs_UnlinkObject(obj);
5748 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5750 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5753 static int yaffs_Scan(yaffs_Device *dev)
5755 yaffs_ExtendedTags tags;
5765 yaffs_BlockState state;
5766 yaffs_Object *hardList = NULL;
5767 yaffs_BlockInfo *bi;
5768 __u32 sequenceNumber;
5769 yaffs_ObjectHeader *oh;
5771 yaffs_Object *parent;
5773 int alloc_failed = 0;
5775 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5783 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5784 dev->internalStartBlock, dev->internalEndBlock));
5786 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5788 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5790 /* Scan all the blocks to determine their state */
5791 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5792 bi = yaffs_GetBlockInfo(dev, blk);
5793 yaffs_ClearChunkBits(dev, blk);
5795 bi->softDeletions = 0;
5797 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5799 bi->blockState = state;
5800 bi->sequenceNumber = sequenceNumber;
5802 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5803 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5805 T(YAFFS_TRACE_SCAN_DEBUG,
5806 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5807 state, sequenceNumber));
5809 if (state == YAFFS_BLOCK_STATE_DEAD) {
5810 T(YAFFS_TRACE_BAD_BLOCKS,
5811 (TSTR("block %d is bad" TENDSTR), blk));
5812 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5813 T(YAFFS_TRACE_SCAN_DEBUG,
5814 (TSTR("Block empty " TENDSTR)));
5815 dev->nErasedBlocks++;
5816 dev->nFreeChunks += dev->param.nChunksPerBlock;
5820 startIterator = dev->internalStartBlock;
5821 endIterator = dev->internalEndBlock;
5823 /* For each block.... */
5824 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5831 blk = blockIterator;
5833 bi = yaffs_GetBlockInfo(dev, blk);
5834 state = bi->blockState;
5838 /* For each chunk in each block that needs scanning....*/
5839 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
5840 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5841 /* Read the tags and decide what to do */
5842 chunk = blk * dev->param.nChunksPerBlock + c;
5844 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5847 /* Let's have a good look at this chunk... */
5849 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5855 /*T((" %d %d deleted\n",blk,c)); */
5856 } else if (!tags.chunkUsed) {
5857 /* An unassigned chunk in the block
5858 * This means that either the block is empty or
5859 * this is the one being allocated from
5863 /* We're looking at the first chunk in the block so the block is unused */
5864 state = YAFFS_BLOCK_STATE_EMPTY;
5865 dev->nErasedBlocks++;
5867 /* this is the block being allocated from */
5870 (" Allocating from %d %d" TENDSTR),
5872 state = YAFFS_BLOCK_STATE_ALLOCATING;
5873 dev->allocationBlock = blk;
5874 dev->allocationPage = c;
5875 dev->allocationBlockFinder = blk;
5876 /* Set block finder here to encourage the allocator to go forth from here. */
5880 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
5881 } else if (tags.chunkId > 0) {
5882 /* chunkId > 0 so it is a data chunk... */
5883 unsigned int endpos;
5885 yaffs_SetChunkBit(dev, blk, c);
5888 in = yaffs_FindOrCreateObjectByNumber(dev,
5891 YAFFS_OBJECT_TYPE_FILE);
5892 /* PutChunkIntoFile checks for a clash (two data chunks with
5893 * the same chunkId).
5900 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5905 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5908 in->variantType == YAFFS_OBJECT_TYPE_FILE
5909 && in->variant.fileVariant.scannedFileSize <
5911 in->variant.fileVariant.
5912 scannedFileSize = endpos;
5913 if (!dev->param.useHeaderFileSize) {
5914 in->variant.fileVariant.
5916 in->variant.fileVariant.
5921 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5923 /* chunkId == 0, so it is an ObjectHeader.
5924 * Thus, we read in the object header and make the object
5926 yaffs_SetChunkBit(dev, blk, c);
5929 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5933 oh = (yaffs_ObjectHeader *) chunkData;
5935 in = yaffs_FindObjectByNumber(dev,
5937 if (in && in->variantType != oh->type) {
5938 /* This should not happen, but somehow
5939 * Wev'e ended up with an objectId that has been reused but not yet
5940 * deleted, and worse still it has changed type. Delete the old object.
5943 yaffs_DeleteObject(in);
5948 in = yaffs_FindOrCreateObjectByNumber(dev,
5956 if (in && oh->shadowsObject > 0) {
5958 struct yaffs_ShadowFixerStruct *fixer;
5959 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5961 fixer->next = shadowFixerList;
5962 shadowFixerList = fixer;
5963 fixer->objectId = tags.objectId;
5964 fixer->shadowedId = oh->shadowsObject;
5969 if (in && in->valid) {
5970 /* We have already filled this one. We have a duplicate and need to resolve it. */
5972 unsigned existingSerial = in->serial;
5973 unsigned newSerial = tags.serialNumber;
5975 if (((existingSerial + 1) & 3) == newSerial) {
5976 /* Use new one - destroy the exisiting one */
5977 yaffs_DeleteChunk(dev,
5982 /* Use existing - destroy this one. */
5983 yaffs_DeleteChunk(dev, chunk, 1,
5988 if (in && !in->valid &&
5989 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5990 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5991 /* We only load some info, don't fiddle with directory structure */
5993 in->variantType = oh->type;
5995 in->yst_mode = oh->yst_mode;
5996 #ifdef CONFIG_YAFFS_WINCE
5997 in->win_atime[0] = oh->win_atime[0];
5998 in->win_ctime[0] = oh->win_ctime[0];
5999 in->win_mtime[0] = oh->win_mtime[0];
6000 in->win_atime[1] = oh->win_atime[1];
6001 in->win_ctime[1] = oh->win_ctime[1];
6002 in->win_mtime[1] = oh->win_mtime[1];
6004 in->yst_uid = oh->yst_uid;
6005 in->yst_gid = oh->yst_gid;
6006 in->yst_atime = oh->yst_atime;
6007 in->yst_mtime = oh->yst_mtime;
6008 in->yst_ctime = oh->yst_ctime;
6009 in->yst_rdev = oh->yst_rdev;
6011 in->hdrChunk = chunk;
6012 in->serial = tags.serialNumber;
6014 } else if (in && !in->valid) {
6015 /* we need to load this info */
6018 in->variantType = oh->type;
6020 in->yst_mode = oh->yst_mode;
6021 #ifdef CONFIG_YAFFS_WINCE
6022 in->win_atime[0] = oh->win_atime[0];
6023 in->win_ctime[0] = oh->win_ctime[0];
6024 in->win_mtime[0] = oh->win_mtime[0];
6025 in->win_atime[1] = oh->win_atime[1];
6026 in->win_ctime[1] = oh->win_ctime[1];
6027 in->win_mtime[1] = oh->win_mtime[1];
6029 in->yst_uid = oh->yst_uid;
6030 in->yst_gid = oh->yst_gid;
6031 in->yst_atime = oh->yst_atime;
6032 in->yst_mtime = oh->yst_mtime;
6033 in->yst_ctime = oh->yst_ctime;
6034 in->yst_rdev = oh->yst_rdev;
6036 in->hdrChunk = chunk;
6037 in->serial = tags.serialNumber;
6039 yaffs_SetObjectName(in, oh->name);
6042 /* directory stuff...
6047 yaffs_FindOrCreateObjectByNumber
6048 (dev, oh->parentObjectId,
6049 YAFFS_OBJECT_TYPE_DIRECTORY);
6052 if (parent && parent->variantType ==
6053 YAFFS_OBJECT_TYPE_UNKNOWN) {
6054 /* Set up as a directory */
6055 parent->variantType =
6056 YAFFS_OBJECT_TYPE_DIRECTORY;
6057 YINIT_LIST_HEAD(&parent->variant.
6060 } else if (!parent || parent->variantType !=
6061 YAFFS_OBJECT_TYPE_DIRECTORY) {
6062 /* Hoosterman, another problem....
6063 * We're trying to use a non-directory as a directory
6066 T(YAFFS_TRACE_ERROR,
6068 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6070 parent = dev->lostNFoundDir;
6073 yaffs_AddObjectToDirectory(parent, in);
6075 if (0 && (parent == dev->deletedDir ||
6076 parent == dev->unlinkedDir)) {
6077 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6078 dev->nDeletedFiles++;
6080 /* Note re hardlinks.
6081 * Since we might scan a hardlink before its equivalent object is scanned
6082 * we put them all in a list.
6083 * After scanning is complete, we should have all the objects, so we run through this
6084 * list and fix up all the chains.
6087 switch (in->variantType) {
6088 case YAFFS_OBJECT_TYPE_UNKNOWN:
6089 /* Todo got a problem */
6091 case YAFFS_OBJECT_TYPE_FILE:
6092 if (dev->param.useHeaderFileSize)
6094 in->variant.fileVariant.
6099 case YAFFS_OBJECT_TYPE_HARDLINK:
6100 in->variant.hardLinkVariant.
6101 equivalentObjectId =
6102 oh->equivalentObjectId;
6103 in->hardLinks.next =
6104 (struct ylist_head *)
6108 case YAFFS_OBJECT_TYPE_DIRECTORY:
6111 case YAFFS_OBJECT_TYPE_SPECIAL:
6114 case YAFFS_OBJECT_TYPE_SYMLINK:
6115 in->variant.symLinkVariant.alias =
6116 yaffs_CloneString(oh->alias);
6117 if (!in->variant.symLinkVariant.alias)
6126 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6127 /* If we got this far while scanning, then the block is fully allocated.*/
6128 state = YAFFS_BLOCK_STATE_FULL;
6131 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6132 /* If the block was partially allocated then treat it as fully allocated.*/
6133 state = YAFFS_BLOCK_STATE_FULL;
6134 dev->allocationBlock = -1;
6137 bi->blockState = state;
6139 /* Now let's see if it was dirty */
6140 if (bi->pagesInUse == 0 &&
6141 !bi->hasShrinkHeader &&
6142 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6143 yaffs_BlockBecameDirty(dev, blk);
6149 /* Ok, we've done all the scanning.
6150 * Fix up the hard link chains.
6151 * We should now have scanned all the objects, now it's time to add these
6155 yaffs_HardlinkFixup(dev, hardList);
6157 /* Fix up any shadowed objects */
6159 struct yaffs_ShadowFixerStruct *fixer;
6162 while (shadowFixerList) {
6163 fixer = shadowFixerList;
6164 shadowFixerList = fixer->next;
6165 /* Complete the rename transaction by deleting the shadowed object
6166 * then setting the object header to unshadowed.
6168 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6170 yaffs_DeleteObject(obj);
6172 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6175 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6181 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6186 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6192 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6195 yaffs_ObjectHeader *oh;
6197 yaffs_ExtendedTags tags;
6199 int alloc_failed = 0;
6207 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6209 in->lazyLoaded ? "not yet" : "already"));
6212 if (in->lazyLoaded && in->hdrChunk > 0) {
6214 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6216 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6217 oh = (yaffs_ObjectHeader *) chunkData;
6219 in->yst_mode = oh->yst_mode;
6220 #ifdef CONFIG_YAFFS_WINCE
6221 in->win_atime[0] = oh->win_atime[0];
6222 in->win_ctime[0] = oh->win_ctime[0];
6223 in->win_mtime[0] = oh->win_mtime[0];
6224 in->win_atime[1] = oh->win_atime[1];
6225 in->win_ctime[1] = oh->win_ctime[1];
6226 in->win_mtime[1] = oh->win_mtime[1];
6228 in->yst_uid = oh->yst_uid;
6229 in->yst_gid = oh->yst_gid;
6230 in->yst_atime = oh->yst_atime;
6231 in->yst_mtime = oh->yst_mtime;
6232 in->yst_ctime = oh->yst_ctime;
6233 in->yst_rdev = oh->yst_rdev;
6236 yaffs_SetObjectName(in, oh->name);
6238 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6239 in->variant.symLinkVariant.alias =
6240 yaffs_CloneString(oh->alias);
6241 if (!in->variant.symLinkVariant.alias)
6242 alloc_failed = 1; /* Not returned to caller */
6245 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6249 static int yaffs_ScanBackwards(yaffs_Device *dev)
6251 yaffs_ExtendedTags tags;
6256 int nBlocksToScan = 0;
6262 yaffs_BlockState state;
6263 yaffs_Object *hardList = NULL;
6264 yaffs_BlockInfo *bi;
6265 __u32 sequenceNumber;
6266 yaffs_ObjectHeader *oh;
6268 yaffs_Object *parent;
6269 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6275 int foundChunksInBlock;
6276 int equivalentObjectId;
6277 int alloc_failed = 0;
6280 yaffs_BlockIndex *blockIndex = NULL;
6281 int altBlockIndex = 0;
6283 if (!dev->param.isYaffs2) {
6285 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6291 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6292 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6295 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6297 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6300 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6306 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6310 dev->blocksInCheckpoint = 0;
6312 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6314 /* Scan all the blocks to determine their state */
6315 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6316 bi = yaffs_GetBlockInfo(dev, blk);
6317 yaffs_ClearChunkBits(dev, blk);
6319 bi->softDeletions = 0;
6321 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6323 bi->blockState = state;
6324 bi->sequenceNumber = sequenceNumber;
6326 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6327 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6328 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6329 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6331 T(YAFFS_TRACE_SCAN_DEBUG,
6332 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6333 state, sequenceNumber));
6336 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6337 dev->blocksInCheckpoint++;
6339 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6340 T(YAFFS_TRACE_BAD_BLOCKS,
6341 (TSTR("block %d is bad" TENDSTR), blk));
6342 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6343 T(YAFFS_TRACE_SCAN_DEBUG,
6344 (TSTR("Block empty " TENDSTR)));
6345 dev->nErasedBlocks++;
6346 dev->nFreeChunks += dev->param.nChunksPerBlock;
6347 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6349 /* Determine the highest sequence number */
6350 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6351 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6353 blockIndex[nBlocksToScan].seq = sequenceNumber;
6354 blockIndex[nBlocksToScan].block = blk;
6358 if (sequenceNumber >= dev->sequenceNumber)
6359 dev->sequenceNumber = sequenceNumber;
6361 /* TODO: Nasty sequence number! */
6364 ("Block scanning block %d has bad sequence number %d"
6365 TENDSTR), blk, sequenceNumber));
6372 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6378 /* Sort the blocks */
6379 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6381 /* Use qsort now. */
6382 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6386 /* Dungy old bubble sort... */
6388 yaffs_BlockIndex temp;
6392 for (i = 0; i < nBlocksToScan; i++)
6393 for (j = i + 1; j < nBlocksToScan; j++)
6394 if (blockIndex[i].seq > blockIndex[j].seq) {
6395 temp = blockIndex[j];
6396 blockIndex[j] = blockIndex[i];
6397 blockIndex[i] = temp;
6404 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6406 /* Now scan the blocks looking at the data. */
6408 endIterator = nBlocksToScan - 1;
6409 T(YAFFS_TRACE_SCAN_DEBUG,
6410 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6412 /* For each block.... backwards */
6413 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6415 /* Cooperative multitasking! This loop can run for so
6416 long that watchdog timers expire. */
6419 /* get the block to scan in the correct order */
6420 blk = blockIndex[blockIterator].block;
6422 bi = yaffs_GetBlockInfo(dev, blk);
6425 state = bi->blockState;
6429 /* For each chunk in each block that needs scanning.... */
6430 foundChunksInBlock = 0;
6431 for (c = dev->param.nChunksPerBlock - 1;
6432 !alloc_failed && c >= 0 &&
6433 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6434 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6435 /* Scan backwards...
6436 * Read the tags and decide what to do
6439 chunk = blk * dev->param.nChunksPerBlock + c;
6441 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6444 /* Let's have a good look at this chunk... */
6446 if (!tags.chunkUsed) {
6447 /* An unassigned chunk in the block.
6448 * If there are used chunks after this one, then
6449 * it is a chunk that was skipped due to failing the erased
6450 * check. Just skip it so that it can be deleted.
6451 * But, more typically, We get here when this is an unallocated
6452 * chunk and his means that either the block is empty or
6453 * this is the one being allocated from
6456 if (foundChunksInBlock) {
6457 /* This is a chunk that was skipped due to failing the erased check */
6458 } else if (c == 0) {
6459 /* We're looking at the first chunk in the block so the block is unused */
6460 state = YAFFS_BLOCK_STATE_EMPTY;
6461 dev->nErasedBlocks++;
6463 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6464 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6465 if (dev->sequenceNumber == bi->sequenceNumber) {
6466 /* this is the block being allocated from */
6470 (" Allocating from %d %d"
6473 state = YAFFS_BLOCK_STATE_ALLOCATING;
6474 dev->allocationBlock = blk;
6475 dev->allocationPage = c;
6476 dev->allocationBlockFinder = blk;
6478 /* This is a partially written block that is not
6479 * the current allocation block.
6482 T(YAFFS_TRACE_ALWAYS,
6483 (TSTR("Partially written block %d detected" TENDSTR),
6491 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6493 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6498 } else if (tags.chunkId > 0) {
6499 /* chunkId > 0 so it is a data chunk... */
6500 unsigned int endpos;
6502 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6504 foundChunksInBlock = 1;
6507 yaffs_SetChunkBit(dev, blk, c);
6510 in = yaffs_FindOrCreateObjectByNumber(dev,
6513 YAFFS_OBJECT_TYPE_FILE);
6520 in->variantType == YAFFS_OBJECT_TYPE_FILE
6521 && chunkBase < in->variant.fileVariant.shrinkSize) {
6522 /* This has not been invalidated by a resize */
6523 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6527 /* File size is calculated by looking at the data chunks if we have not
6528 * seen an object header yet. Stop this practice once we find an object header.
6530 endpos = chunkBase + tags.byteCount;
6532 if (!in->valid && /* have not got an object header yet */
6533 in->variant.fileVariant.scannedFileSize < endpos) {
6534 in->variant.fileVariant.scannedFileSize = endpos;
6535 in->variant.fileVariant.fileSize = endpos;
6539 /* This chunk has been invalidated by a resize, or a past file deletion
6540 * so delete the chunk*/
6541 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6545 /* chunkId == 0, so it is an ObjectHeader.
6546 * Thus, we read in the object header and make the object
6548 foundChunksInBlock = 1;
6550 yaffs_SetChunkBit(dev, blk, c);
6556 if (tags.extraHeaderInfoAvailable) {
6557 in = yaffs_FindOrCreateObjectByNumber(dev,
6559 tags.extraObjectType);
6565 (!in->valid && dev->param.disableLazyLoad) ||
6566 tags.extraShadows ||
6568 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6569 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6571 /* If we don't have valid info then we need to read the chunk
6572 * TODO In future we can probably defer reading the chunk and
6573 * living with invalid data until needed.
6576 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6581 oh = (yaffs_ObjectHeader *) chunkData;
6583 if (dev->param.inbandTags) {
6584 /* Fix up the header if they got corrupted by inband tags */
6585 oh->shadowsObject = oh->inbandShadowsObject;
6586 oh->isShrink = oh->inbandIsShrink;
6590 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6598 /* TODO Hoosterman we have a problem! */
6599 T(YAFFS_TRACE_ERROR,
6601 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6602 TENDSTR), tags.objectId, chunk));
6607 /* We have already filled this one.
6608 * We have a duplicate that will be discarded, but
6609 * we first have to suck out resize info if it is a file.
6612 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6614 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6615 (tags.extraHeaderInfoAvailable &&
6616 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6618 (oh) ? oh->fileSize : tags.
6620 __u32 parentObjectId =
6622 parentObjectId : tags.
6623 extraParentObjectId;
6627 (oh) ? oh->isShrink : tags.
6628 extraIsShrinkHeader;
6630 /* If it is deleted (unlinked at start also means deleted)
6631 * we treat the file size as being zeroed at this point.
6633 if (parentObjectId ==
6634 YAFFS_OBJECTID_DELETED
6635 || parentObjectId ==
6636 YAFFS_OBJECTID_UNLINKED) {
6641 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6642 in->variant.fileVariant.shrinkSize = thisSize;
6645 bi->hasShrinkHeader = 1;
6648 /* Use existing - destroy this one. */
6649 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6653 if (!in->valid && in->variantType !=
6654 (oh ? oh->type : tags.extraObjectType))
6655 T(YAFFS_TRACE_ERROR, (
6656 TSTR("yaffs tragedy: Bad object type, "
6657 TCONT("%d != %d, for object %d at chunk ")
6658 TCONT("%d during scan")
6660 oh->type : tags.extraObjectType,
6661 in->variantType, tags.objectId,
6665 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6667 YAFFS_OBJECTID_LOSTNFOUND)) {
6668 /* We only load some info, don't fiddle with directory structure */
6672 in->variantType = oh->type;
6674 in->yst_mode = oh->yst_mode;
6675 #ifdef CONFIG_YAFFS_WINCE
6676 in->win_atime[0] = oh->win_atime[0];
6677 in->win_ctime[0] = oh->win_ctime[0];
6678 in->win_mtime[0] = oh->win_mtime[0];
6679 in->win_atime[1] = oh->win_atime[1];
6680 in->win_ctime[1] = oh->win_ctime[1];
6681 in->win_mtime[1] = oh->win_mtime[1];
6683 in->yst_uid = oh->yst_uid;
6684 in->yst_gid = oh->yst_gid;
6685 in->yst_atime = oh->yst_atime;
6686 in->yst_mtime = oh->yst_mtime;
6687 in->yst_ctime = oh->yst_ctime;
6688 in->yst_rdev = oh->yst_rdev;
6692 in->variantType = tags.extraObjectType;
6696 in->hdrChunk = chunk;
6698 } else if (!in->valid) {
6699 /* we need to load this info */
6702 in->hdrChunk = chunk;
6705 in->variantType = oh->type;
6707 in->yst_mode = oh->yst_mode;
6708 #ifdef CONFIG_YAFFS_WINCE
6709 in->win_atime[0] = oh->win_atime[0];
6710 in->win_ctime[0] = oh->win_ctime[0];
6711 in->win_mtime[0] = oh->win_mtime[0];
6712 in->win_atime[1] = oh->win_atime[1];
6713 in->win_ctime[1] = oh->win_ctime[1];
6714 in->win_mtime[1] = oh->win_mtime[1];
6716 in->yst_uid = oh->yst_uid;
6717 in->yst_gid = oh->yst_gid;
6718 in->yst_atime = oh->yst_atime;
6719 in->yst_mtime = oh->yst_mtime;
6720 in->yst_ctime = oh->yst_ctime;
6721 in->yst_rdev = oh->yst_rdev;
6724 if (oh->shadowsObject > 0)
6725 yaffs_HandleShadowedObject(dev,
6732 yaffs_SetObjectName(in, oh->name);
6734 yaffs_FindOrCreateObjectByNumber
6735 (dev, oh->parentObjectId,
6736 YAFFS_OBJECT_TYPE_DIRECTORY);
6738 fileSize = oh->fileSize;
6739 isShrink = oh->isShrink;
6740 equivalentObjectId = oh->equivalentObjectId;
6743 in->variantType = tags.extraObjectType;
6745 yaffs_FindOrCreateObjectByNumber
6746 (dev, tags.extraParentObjectId,
6747 YAFFS_OBJECT_TYPE_DIRECTORY);
6748 fileSize = tags.extraFileLength;
6749 isShrink = tags.extraIsShrinkHeader;
6750 equivalentObjectId = tags.extraEquivalentObjectId;
6759 /* directory stuff...
6763 if (parent && parent->variantType ==
6764 YAFFS_OBJECT_TYPE_UNKNOWN) {
6765 /* Set up as a directory */
6766 parent->variantType =
6767 YAFFS_OBJECT_TYPE_DIRECTORY;
6768 YINIT_LIST_HEAD(&parent->variant.
6771 } else if (!parent || parent->variantType !=
6772 YAFFS_OBJECT_TYPE_DIRECTORY) {
6773 /* Hoosterman, another problem....
6774 * We're trying to use a non-directory as a directory
6777 T(YAFFS_TRACE_ERROR,
6779 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6781 parent = dev->lostNFoundDir;
6784 yaffs_AddObjectToDirectory(parent, in);
6786 itsUnlinked = (parent == dev->deletedDir) ||
6787 (parent == dev->unlinkedDir);
6790 /* Mark the block as having a shrinkHeader */
6791 bi->hasShrinkHeader = 1;
6794 /* Note re hardlinks.
6795 * Since we might scan a hardlink before its equivalent object is scanned
6796 * we put them all in a list.
6797 * After scanning is complete, we should have all the objects, so we run
6798 * through this list and fix up all the chains.
6801 switch (in->variantType) {
6802 case YAFFS_OBJECT_TYPE_UNKNOWN:
6803 /* Todo got a problem */
6805 case YAFFS_OBJECT_TYPE_FILE:
6807 if (in->variant.fileVariant.
6808 scannedFileSize < fileSize) {
6809 /* This covers the case where the file size is greater
6810 * than where the data is
6811 * This will happen if the file is resized to be larger
6812 * than its current data extents.
6814 in->variant.fileVariant.fileSize = fileSize;
6815 in->variant.fileVariant.scannedFileSize = fileSize;
6818 if (in->variant.fileVariant.shrinkSize > fileSize)
6819 in->variant.fileVariant.shrinkSize = fileSize;
6823 case YAFFS_OBJECT_TYPE_HARDLINK:
6825 in->variant.hardLinkVariant.equivalentObjectId =
6827 in->hardLinks.next =
6828 (struct ylist_head *) hardList;
6832 case YAFFS_OBJECT_TYPE_DIRECTORY:
6835 case YAFFS_OBJECT_TYPE_SPECIAL:
6838 case YAFFS_OBJECT_TYPE_SYMLINK:
6840 in->variant.symLinkVariant.alias =
6841 yaffs_CloneString(oh->alias);
6842 if (!in->variant.symLinkVariant.alias)
6852 } /* End of scanning for each chunk */
6854 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6855 /* If we got this far while scanning, then the block is fully allocated. */
6856 state = YAFFS_BLOCK_STATE_FULL;
6860 bi->blockState = state;
6862 /* Now let's see if it was dirty */
6863 if (bi->pagesInUse == 0 &&
6864 !bi->hasShrinkHeader &&
6865 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6866 yaffs_BlockBecameDirty(dev, blk);
6871 yaffs_SkipRestOfBlock(dev);
6874 YFREE_ALT(blockIndex);
6878 /* Ok, we've done all the scanning.
6879 * Fix up the hard link chains.
6880 * We should now have scanned all the objects, now it's time to add these
6883 yaffs_HardlinkFixup(dev, hardList);
6886 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6891 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6896 /*------------------------------ Directory Functions ----------------------------- */
6898 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6900 struct ylist_head *lh;
6901 yaffs_Object *listObj;
6906 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6911 if (yaffs_SkipVerification(obj->myDev))
6915 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6920 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6921 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6925 /* Iterate through the objects in each hash entry */
6927 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6929 listObj = ylist_entry(lh, yaffs_Object, siblings);
6930 yaffs_VerifyObject(listObj);
6937 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6942 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6944 struct ylist_head *lh;
6945 yaffs_Object *listObj;
6952 if (yaffs_SkipFullVerification(directory->myDev))
6955 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6956 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6960 /* Iterate through the objects in each hash entry */
6962 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6964 listObj = ylist_entry(lh, yaffs_Object, siblings);
6965 if (listObj->parent != directory) {
6966 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6969 yaffs_VerifyObjectInDirectory(listObj);
6975 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6976 * link (ie. name) is created or deleted in the directory.
6979 * create dir/a : update dir's mtime/ctime
6980 * rm dir/a: update dir's mtime/ctime
6981 * modify dir/a: don't update dir's mtimme/ctime
6984 static void yaffs_UpdateParent(yaffs_Object *obj)
6990 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6992 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6995 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6997 yaffs_Device *dev = obj->myDev;
6998 yaffs_Object *parent;
7000 yaffs_VerifyObjectInDirectory(obj);
7001 parent = obj->parent;
7003 yaffs_VerifyDirectory(parent);
7005 if (dev && dev->param.removeObjectCallback)
7006 dev->param.removeObjectCallback(obj);
7009 ylist_del_init(&obj->siblings);
7012 yaffs_VerifyDirectory(parent);
7015 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7019 T(YAFFS_TRACE_ALWAYS,
7021 ("tragedy: Trying to add an object to a null pointer directory"
7026 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7027 T(YAFFS_TRACE_ALWAYS,
7029 ("tragedy: Trying to add an object to a non-directory"
7034 if (obj->siblings.prev == NULL) {
7035 /* Not initialised */
7040 yaffs_VerifyDirectory(directory);
7042 yaffs_RemoveObjectFromDirectory(obj);
7046 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7047 obj->parent = directory;
7049 if (directory == obj->myDev->unlinkedDir
7050 || directory == obj->myDev->deletedDir) {
7052 obj->myDev->nUnlinkedFiles++;
7053 obj->renameAllowed = 0;
7056 yaffs_VerifyDirectory(directory);
7057 yaffs_VerifyObjectInDirectory(obj);
7060 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7065 struct ylist_head *i;
7066 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7074 T(YAFFS_TRACE_ALWAYS,
7076 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7081 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7082 T(YAFFS_TRACE_ALWAYS,
7084 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7088 sum = yaffs_CalcNameSum(name);
7090 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7092 l = ylist_entry(i, yaffs_Object, siblings);
7094 if (l->parent != directory)
7097 yaffs_CheckObjectDetailsLoaded(l);
7099 /* Special case for lost-n-found */
7100 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7101 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7103 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7104 /* LostnFound chunk called Objxxx
7107 yaffs_GetObjectName(l, buffer,
7108 YAFFS_MAX_NAME_LENGTH + 1);
7109 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7120 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7121 int (*fn) (yaffs_Object *))
7123 struct ylist_head *i;
7127 T(YAFFS_TRACE_ALWAYS,
7129 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7134 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7135 T(YAFFS_TRACE_ALWAYS,
7137 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7142 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7144 l = ylist_entry(i, yaffs_Object, siblings);
7155 /* GetEquivalentObject dereferences any hard links to get to the
7159 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7161 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7162 /* We want the object id of the equivalent object, not this one */
7163 obj = obj->variant.hardLinkVariant.equivalentObject;
7164 yaffs_CheckObjectDetailsLoaded(obj);
7169 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7171 memset(name, 0, buffSize * sizeof(YCHAR));
7173 yaffs_CheckObjectDetailsLoaded(obj);
7175 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7176 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7177 } else if (obj->hdrChunk <= 0) {
7179 YCHAR numString[20];
7180 YCHAR *x = &numString[19];
7181 unsigned v = obj->objectId;
7185 *x = '0' + (v % 10);
7188 /* make up a name */
7189 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7190 yaffs_strcat(locName, x);
7191 yaffs_strncpy(name, locName, buffSize - 1);
7194 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7195 else if (obj->shortName[0])
7196 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7200 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7202 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7204 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7206 if (obj->hdrChunk > 0) {
7207 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7208 obj->hdrChunk, buffer,
7211 yaffs_strncpy(name, oh->name, buffSize - 1);
7214 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7217 return yaffs_strnlen(name,buffSize-1);
7220 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7222 /* Dereference any hard linking */
7223 obj = yaffs_GetEquivalentObject(obj);
7225 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7226 return obj->variant.fileVariant.fileSize;
7227 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7228 if(!obj->variant.symLinkVariant.alias)
7230 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7232 /* Only a directory should drop through to here */
7233 return obj->myDev->nDataBytesPerChunk;
7237 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7240 struct ylist_head *i;
7243 count++; /* the object itself */
7245 ylist_for_each(i, &obj->hardLinks)
7246 count++; /* add the hard links; */
7251 int yaffs_GetObjectInode(yaffs_Object *obj)
7253 obj = yaffs_GetEquivalentObject(obj);
7255 return obj->objectId;
7258 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7260 obj = yaffs_GetEquivalentObject(obj);
7262 switch (obj->variantType) {
7263 case YAFFS_OBJECT_TYPE_FILE:
7266 case YAFFS_OBJECT_TYPE_DIRECTORY:
7269 case YAFFS_OBJECT_TYPE_SYMLINK:
7272 case YAFFS_OBJECT_TYPE_HARDLINK:
7275 case YAFFS_OBJECT_TYPE_SPECIAL:
7276 if (S_ISFIFO(obj->yst_mode))
7278 if (S_ISCHR(obj->yst_mode))
7280 if (S_ISBLK(obj->yst_mode))
7282 if (S_ISSOCK(obj->yst_mode))
7290 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7292 obj = yaffs_GetEquivalentObject(obj);
7293 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7294 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7296 return yaffs_CloneString(_Y(""));
7299 #ifndef CONFIG_YAFFS_WINCE
7301 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7303 unsigned int valid = attr->ia_valid;
7305 if (valid & ATTR_MODE)
7306 obj->yst_mode = attr->ia_mode;
7307 if (valid & ATTR_UID)
7308 obj->yst_uid = attr->ia_uid;
7309 if (valid & ATTR_GID)
7310 obj->yst_gid = attr->ia_gid;
7312 if (valid & ATTR_ATIME)
7313 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7314 if (valid & ATTR_CTIME)
7315 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7316 if (valid & ATTR_MTIME)
7317 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7319 if (valid & ATTR_SIZE)
7320 yaffs_ResizeFile(obj, attr->ia_size);
7322 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7327 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7329 unsigned int valid = 0;
7331 attr->ia_mode = obj->yst_mode;
7333 attr->ia_uid = obj->yst_uid;
7335 attr->ia_gid = obj->yst_gid;
7338 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7339 valid |= ATTR_ATIME;
7340 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7341 valid |= ATTR_CTIME;
7342 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7343 valid |= ATTR_MTIME;
7345 attr->ia_size = yaffs_GetFileSize(obj);
7348 attr->ia_valid = valid;
7356 int yaffs_DumpObject(yaffs_Object *obj)
7360 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7362 T(YAFFS_TRACE_ALWAYS,
7364 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7365 " chunk %d type %d size %d\n"
7366 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7367 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7368 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7374 /*---------------------------- Initialisation code -------------------------------------- */
7376 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7379 /* Common functions, gotta have */
7380 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7383 #ifdef CONFIG_YAFFS_YAFFS2
7385 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7386 if (dev->param.writeChunkWithTagsToNAND &&
7387 dev->param.readChunkWithTagsFromNAND &&
7388 !dev->param.writeChunkToNAND &&
7389 !dev->param.readChunkFromNAND &&
7390 dev->param.markNANDBlockBad &&
7391 dev->param.queryNANDBlock)
7395 /* Can use the "spare" style interface for yaffs1 */
7396 if (!dev->param.isYaffs2 &&
7397 !dev->param.writeChunkWithTagsToNAND &&
7398 !dev->param.readChunkWithTagsFromNAND &&
7399 dev->param.writeChunkToNAND &&
7400 dev->param.readChunkFromNAND &&
7401 !dev->param.markNANDBlockBad &&
7402 !dev->param.queryNANDBlock)
7409 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7411 /* Initialise the unlinked, deleted, root and lost and found directories */
7413 dev->lostNFoundDir = dev->rootDir = NULL;
7414 dev->unlinkedDir = dev->deletedDir = NULL;
7417 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7420 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7423 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7424 YAFFS_ROOT_MODE | S_IFDIR);
7425 dev->lostNFoundDir =
7426 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7427 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7429 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7430 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7437 int yaffs_GutsInitialise(yaffs_Device *dev)
7439 int init_failed = 0;
7443 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7445 /* Check stuff that must be set */
7448 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7452 dev->internalStartBlock = dev->param.startBlock;
7453 dev->internalEndBlock = dev->param.endBlock;
7454 dev->blockOffset = 0;
7455 dev->chunkOffset = 0;
7456 dev->nFreeChunks = 0;
7460 if (dev->param.startBlock == 0) {
7461 dev->internalStartBlock = dev->param.startBlock + 1;
7462 dev->internalEndBlock = dev->param.endBlock + 1;
7463 dev->blockOffset = 1;
7464 dev->chunkOffset = dev->param.nChunksPerBlock;
7467 /* Check geometry parameters. */
7469 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7470 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7471 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7472 dev->param.nChunksPerBlock < 2 ||
7473 dev->param.nReservedBlocks < 2 ||
7474 dev->internalStartBlock <= 0 ||
7475 dev->internalEndBlock <= 0 ||
7476 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7477 T(YAFFS_TRACE_ALWAYS,
7479 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7480 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7484 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7485 T(YAFFS_TRACE_ALWAYS,
7486 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7490 /* Sort out space for inband tags, if required */
7491 if (dev->param.inbandTags)
7492 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7494 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7496 /* Got the right mix of functions? */
7497 if (!yaffs_CheckDevFunctions(dev)) {
7498 /* Function missing */
7499 T(YAFFS_TRACE_ALWAYS,
7501 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7506 /* This is really a compilation check. */
7507 if (!yaffs_CheckStructures()) {
7508 T(YAFFS_TRACE_ALWAYS,
7509 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7513 if (dev->isMounted) {
7514 T(YAFFS_TRACE_ALWAYS,
7515 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7519 /* Finished with most checks. One or two more checks happen later on too. */
7523 /* OK now calculate a few things for the device */
7526 * Calculate all the chunk size manipulation numbers:
7528 x = dev->nDataBytesPerChunk;
7529 /* We always use dev->chunkShift and dev->chunkDiv */
7530 dev->chunkShift = Shifts(x);
7531 x >>= dev->chunkShift;
7533 /* We only use chunk mask if chunkDiv is 1 */
7534 dev->chunkMask = (1<<dev->chunkShift) - 1;
7537 * Calculate chunkGroupBits.
7538 * We need to find the next power of 2 > than internalEndBlock
7541 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7545 /* Set up tnode width if wide tnodes are enabled. */
7546 if (!dev->param.wideTnodesDisabled) {
7547 /* bits must be even so that we end up with 32-bit words */
7551 dev->tnodeWidth = 16;
7553 dev->tnodeWidth = bits;
7555 dev->tnodeWidth = 16;
7557 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7559 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7560 * so if the bitwidth of the
7561 * chunk range we're using is greater than 16 we need
7562 * to figure out chunk shift and chunkGroupSize
7565 if (bits <= dev->tnodeWidth)
7566 dev->chunkGroupBits = 0;
7568 dev->chunkGroupBits = bits - dev->tnodeWidth;
7571 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7573 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7574 /* We have a problem because the soft delete won't work if
7575 * the chunk group size > chunks per block.
7576 * This can be remedied by using larger "virtual blocks".
7578 T(YAFFS_TRACE_ALWAYS,
7579 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7584 /* OK, we've finished verifying the device, lets continue with initialisation */
7586 /* More device initialisation */
7587 dev->garbageCollections = 0;
7588 dev->passiveGarbageCollections = 0;
7589 dev->currentDirtyChecker = 0;
7590 dev->bufferedBlock = -1;
7591 dev->doingBufferedBlockRewrite = 0;
7592 dev->nDeletedFiles = 0;
7593 dev->nBackgroundDeletions = 0;
7594 dev->nUnlinkedFiles = 0;
7596 dev->eccUnfixed = 0;
7597 dev->tagsEccFixed = 0;
7598 dev->tagsEccUnfixed = 0;
7599 dev->nErasureFailures = 0;
7600 dev->nErasedBlocks = 0;
7602 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7603 dev->oldestDirtySequence = 0;
7605 /* Initialise temporary buffers and caches. */
7606 if (!yaffs_InitialiseTempBuffers(dev))
7609 dev->srCache = NULL;
7610 dev->gcCleanupList = NULL;
7614 dev->param.nShortOpCaches > 0) {
7617 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7619 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7620 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7622 dev->srCache = YMALLOC(srCacheBytes);
7624 buf = (__u8 *) dev->srCache;
7627 memset(dev->srCache, 0, srCacheBytes);
7629 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7630 dev->srCache[i].object = NULL;
7631 dev->srCache[i].lastUse = 0;
7632 dev->srCache[i].dirty = 0;
7633 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7644 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7645 if (!dev->gcCleanupList)
7649 if (dev->param.isYaffs2)
7650 dev->param.useHeaderFileSize = 1;
7652 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7655 yaffs_InitialiseTnodes(dev);
7656 yaffs_InitialiseObjects(dev);
7658 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7663 /* Now scan the flash. */
7664 if (dev->param.isYaffs2) {
7665 if (yaffs_CheckpointRestore(dev)) {
7666 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7667 T(YAFFS_TRACE_ALWAYS,
7668 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7671 /* Clean up the mess caused by an aborted checkpoint load
7672 * and scan backwards.
7674 yaffs_DeinitialiseBlocks(dev);
7675 yaffs_DeinitialiseTnodes(dev);
7676 yaffs_DeinitialiseObjects(dev);
7679 dev->nErasedBlocks = 0;
7680 dev->nFreeChunks = 0;
7681 dev->allocationBlock = -1;
7682 dev->allocationPage = -1;
7683 dev->nDeletedFiles = 0;
7684 dev->nUnlinkedFiles = 0;
7685 dev->nBackgroundDeletions = 0;
7687 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7690 yaffs_InitialiseTnodes(dev);
7691 yaffs_InitialiseObjects(dev);
7693 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7696 if (!init_failed && !yaffs_ScanBackwards(dev))
7699 } else if (!yaffs_Scan(dev))
7702 yaffs_StripDeletedObjects(dev);
7703 yaffs_FixHangingObjects(dev);
7704 if(dev->param.emptyLostAndFound)
7705 yaffs_EmptyLostAndFound(dev);
7709 /* Clean up the mess */
7710 T(YAFFS_TRACE_TRACING,
7711 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7713 yaffs_Deinitialise(dev);
7717 /* Zero out stats */
7718 dev->nPageReads = 0;
7719 dev->nPageWrites = 0;
7720 dev->nBlockErasures = 0;
7722 dev->nRetriedWrites = 0;
7724 dev->nRetiredBlocks = 0;
7726 yaffs_VerifyFreeChunks(dev);
7727 yaffs_VerifyBlocks(dev);
7729 /* Clean up any aborted checkpoint data */
7730 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7731 yaffs_InvalidateCheckpoint(dev);
7733 T(YAFFS_TRACE_TRACING,
7734 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7739 void yaffs_Deinitialise(yaffs_Device *dev)
7741 if (dev->isMounted) {
7744 yaffs_DeinitialiseBlocks(dev);
7745 yaffs_DeinitialiseTnodes(dev);
7746 yaffs_DeinitialiseObjects(dev);
7747 if (dev->param.nShortOpCaches > 0 &&
7750 for (i = 0; i < dev->param.nShortOpCaches; i++) {
7751 if (dev->srCache[i].data)
7752 YFREE(dev->srCache[i].data);
7753 dev->srCache[i].data = NULL;
7756 YFREE(dev->srCache);
7757 dev->srCache = NULL;
7760 YFREE(dev->gcCleanupList);
7762 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7763 YFREE(dev->tempBuffer[i].buffer);
7767 if (dev->param.deinitialiseNAND)
7768 dev->param.deinitialiseNAND(dev);
7772 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7777 yaffs_BlockInfo *blk;
7779 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7781 blk = yaffs_GetBlockInfo(dev, b);
7783 switch (blk->blockState) {
7784 case YAFFS_BLOCK_STATE_EMPTY:
7785 case YAFFS_BLOCK_STATE_ALLOCATING:
7786 case YAFFS_BLOCK_STATE_COLLECTING:
7787 case YAFFS_BLOCK_STATE_FULL:
7789 (dev->param.nChunksPerBlock - blk->pagesInUse +
7790 blk->softDeletions);
7800 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7802 /* This is what we report to the outside world */
7805 int nDirtyCacheChunks;
7806 int blocksForCheckpoint;
7810 nFree = dev->nFreeChunks;
7812 nFree = yaffs_CountFreeChunks(dev);
7815 nFree += dev->nDeletedFiles;
7817 /* Now count the number of dirty chunks in the cache and subtract those */
7819 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
7820 if (dev->srCache[i].dirty)
7821 nDirtyCacheChunks++;
7824 nFree -= nDirtyCacheChunks;
7826 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
7828 /* Now we figure out how much to reserve for the checkpoint and report that... */
7829 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7830 if (blocksForCheckpoint < 0)
7831 blocksForCheckpoint = 0;
7833 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
7842 static int yaffs_freeVerificationFailures;
7844 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7849 if (yaffs_SkipVerification(dev))
7852 counted = yaffs_CountFreeChunks(dev);
7854 difference = dev->nFreeChunks - counted;
7857 T(YAFFS_TRACE_ALWAYS,
7858 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7859 dev->nFreeChunks, counted, difference));
7860 yaffs_freeVerificationFailures++;
7864 /*---------------------------------------- YAFFS test code ----------------------*/
7866 #define yaffs_CheckStruct(structure, syze, name) \
7868 if (sizeof(structure) != syze) { \
7869 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7870 name, syze, (int) sizeof(structure))); \
7871 return YAFFS_FAIL; \
7875 static int yaffs_CheckStructures(void)
7877 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7878 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7879 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7880 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7881 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
7883 #ifndef CONFIG_YAFFS_WINCE
7884 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");