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.81 2009-03-06 17:20:51 wookey Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
38 #include "yaffs_ecc.h"
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
45 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
47 const yaffs_ExtendedTags *tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
49 const yaffs_ExtendedTags *tags);
51 /* Other local prototypes */
52 static int yaffs_UnlinkObject(yaffs_Object *obj);
53 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
55 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
57 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
59 yaffs_ExtendedTags *tags,
61 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
62 int chunkInNAND, int inScan);
64 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
65 yaffs_ObjectType type);
66 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
68 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
69 int force, int isShrink, int shadows);
70 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
71 static int yaffs_CheckStructures(void);
72 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
73 int chunkOffset, int *limit);
74 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
76 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
79 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
82 static int yaffs_UnlinkWorker(yaffs_Object *obj);
84 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
87 loff_t yaffs_GetFileSize(yaffs_Object *obj);
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,
118 /* Function to calculate chunk and offset */
120 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
126 chunk = (__u32)(addr >> dev->chunkShift);
128 if (dev->chunkDiv == 1) {
129 /* easy power of 2 case */
130 offset = (__u32)(addr & dev->chunkMask);
132 /* Non power-of-2 case */
136 chunk /= dev->chunkDiv;
138 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
139 offset = (__u32)(addr - chunkBase);
146 /* Function to return the number of shifts for a power of 2 greater than or
147 * equal to the given number
148 * Note we don't try to cater for all possible numbers and this does not have to
149 * be hellishly efficient.
152 static __u32 ShiftsGE(__u32 x)
157 nShifts = extraBits = 0;
172 /* Function to return the number of shifts to get a 1 in bit 0
175 static __u32 Shifts(__u32 x)
195 * Temporary buffer manipulations.
198 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
201 __u8 *buf = (__u8 *)1;
203 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
205 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
206 dev->tempBuffer[i].line = 0; /* not in use */
207 dev->tempBuffer[i].buffer = buf =
208 YMALLOC_DMA(dev->totalBytesPerChunk);
211 return buf ? YAFFS_OK : YAFFS_FAIL;
214 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
219 if (dev->tempInUse > dev->maxTemp)
220 dev->maxTemp = dev->tempInUse;
222 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
223 if (dev->tempBuffer[i].line == 0) {
224 dev->tempBuffer[i].line = lineNo;
225 if ((i + 1) > dev->maxTemp) {
226 dev->maxTemp = i + 1;
227 for (j = 0; j <= i; j++)
228 dev->tempBuffer[j].maxLine =
229 dev->tempBuffer[j].line;
232 return dev->tempBuffer[i].buffer;
236 T(YAFFS_TRACE_BUFFERS,
237 (TSTR("Out of temp buffers at line %d, other held by lines:"),
239 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
240 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
242 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
245 * If we got here then we have to allocate an unmanaged one
249 dev->unmanagedTempAllocations++;
250 return YMALLOC(dev->nDataBytesPerChunk);
254 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
261 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
262 if (dev->tempBuffer[i].buffer == buffer) {
263 dev->tempBuffer[i].line = 0;
269 /* assume it is an unmanaged one. */
270 T(YAFFS_TRACE_BUFFERS,
271 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
274 dev->unmanagedTempDeallocations++;
280 * Determine if we have a managed buffer.
282 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
286 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
287 if (dev->tempBuffer[i].buffer == buffer)
291 for (i = 0; i < dev->nShortOpCaches; i++) {
292 if (dev->srCache[i].data == buffer)
296 if (buffer == dev->checkpointBuffer)
299 T(YAFFS_TRACE_ALWAYS,
300 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
307 * Chunk bitmap manipulations
310 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
312 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
314 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
318 return dev->chunkBits +
319 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
322 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
324 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
325 chunk < 0 || chunk >= dev->nChunksPerBlock) {
327 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
333 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
335 __u8 *blkBits = yaffs_BlockBits(dev, blk);
337 memset(blkBits, 0, dev->chunkBitmapStride);
340 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
342 __u8 *blkBits = yaffs_BlockBits(dev, blk);
344 yaffs_VerifyChunkBitId(dev, blk, chunk);
346 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
349 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
351 __u8 *blkBits = yaffs_BlockBits(dev, blk);
353 yaffs_VerifyChunkBitId(dev, blk, chunk);
355 blkBits[chunk / 8] |= (1 << (chunk & 7));
358 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
360 __u8 *blkBits = yaffs_BlockBits(dev, blk);
361 yaffs_VerifyChunkBitId(dev, blk, chunk);
363 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
366 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
368 __u8 *blkBits = yaffs_BlockBits(dev, blk);
370 for (i = 0; i < dev->chunkBitmapStride; i++) {
378 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
380 __u8 *blkBits = yaffs_BlockBits(dev, blk);
383 for (i = 0; i < dev->chunkBitmapStride; i++) {
400 static int yaffs_SkipVerification(yaffs_Device *dev)
402 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
405 static int yaffs_SkipFullVerification(yaffs_Device *dev)
407 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
410 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
412 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
415 static const char *blockStateName[] = {
428 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
433 if (yaffs_SkipVerification(dev))
436 /* Report illegal runtime states */
437 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
438 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
440 switch (bi->blockState) {
441 case YAFFS_BLOCK_STATE_UNKNOWN:
442 case YAFFS_BLOCK_STATE_SCANNING:
443 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
444 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
445 n, blockStateName[bi->blockState]));
448 /* Check pages in use and soft deletions are legal */
450 actuallyUsed = bi->pagesInUse - bi->softDeletions;
452 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
453 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
454 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
455 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
456 n, bi->pagesInUse, bi->softDeletions));
459 /* Check chunk bitmap legal */
460 inUse = yaffs_CountChunkBits(dev, n);
461 if (inUse != bi->pagesInUse)
462 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
463 n, bi->pagesInUse, inUse));
465 /* Check that the sequence number is valid.
466 * Ten million is legal, but is very unlikely
469 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
470 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
471 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
472 n, bi->sequenceNumber));
475 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
478 yaffs_VerifyBlock(dev, bi, n);
480 /* After collection the block should be in the erased state */
481 /* This will need to change if we do partial gc */
483 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
484 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
485 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
490 static void yaffs_VerifyBlocks(yaffs_Device *dev)
493 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
494 int nIllegalBlockStates = 0;
496 if (yaffs_SkipVerification(dev))
499 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
501 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
502 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
503 yaffs_VerifyBlock(dev, bi, i);
505 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
506 nBlocksPerState[bi->blockState]++;
508 nIllegalBlockStates++;
511 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
512 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
514 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
515 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
516 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
518 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
519 T(YAFFS_TRACE_VERIFY,
520 (TSTR("%s %d blocks"TENDSTR),
521 blockStateName[i], nBlocksPerState[i]));
523 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
524 T(YAFFS_TRACE_VERIFY,
525 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
526 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
528 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
529 T(YAFFS_TRACE_VERIFY,
530 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
531 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
533 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
534 T(YAFFS_TRACE_VERIFY,
535 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
536 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
538 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
543 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
544 * case those tests will not be performed.
546 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
548 if (obj && yaffs_SkipVerification(obj->myDev))
551 if (!(tags && obj && oh)) {
552 T(YAFFS_TRACE_VERIFY,
553 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
554 (__u32)tags, (__u32)obj, (__u32)oh));
558 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
559 oh->type > YAFFS_OBJECT_TYPE_MAX)
560 T(YAFFS_TRACE_VERIFY,
561 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
562 tags->objectId, oh->type));
564 if (tags->objectId != obj->objectId)
565 T(YAFFS_TRACE_VERIFY,
566 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
567 tags->objectId, obj->objectId));
571 * Check that the object's parent ids match if parentCheck requested.
573 * Tests do not apply to the root object.
576 if (parentCheck && tags->objectId > 1 && !obj->parent)
577 T(YAFFS_TRACE_VERIFY,
578 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
579 tags->objectId, oh->parentObjectId));
581 if (parentCheck && obj->parent &&
582 oh->parentObjectId != obj->parent->objectId &&
583 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
584 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
585 T(YAFFS_TRACE_VERIFY,
586 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
587 tags->objectId, oh->parentObjectId, obj->parent->objectId));
589 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
590 T(YAFFS_TRACE_VERIFY,
591 (TSTR("Obj %d header name is NULL"TENDSTR),
594 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
595 T(YAFFS_TRACE_VERIFY,
596 (TSTR("Obj %d header name is 0xFF"TENDSTR),
602 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
603 __u32 level, int chunkOffset)
606 yaffs_Device *dev = obj->myDev;
612 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
613 if (tn->internal[i]) {
614 ok = yaffs_VerifyTnodeWorker(obj,
617 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
620 } else if (level == 0) {
621 yaffs_ExtendedTags tags;
622 __u32 objectId = obj->objectId;
624 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
626 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
627 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
630 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
631 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
632 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
633 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
634 objectId, chunkOffset, theChunk,
635 tags.objectId, tags.chunkId));
648 static void yaffs_VerifyFile(yaffs_Object *obj)
650 int requiredTallness;
656 yaffs_ExtendedTags tags;
663 if (yaffs_SkipVerification(obj->myDev))
667 objectId = obj->objectId;
669 /* Check file size is consistent with tnode depth */
670 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
671 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
672 requiredTallness = 0;
674 x >>= YAFFS_TNODES_INTERNAL_BITS;
678 actualTallness = obj->variant.fileVariant.topLevel;
680 if (requiredTallness > actualTallness)
681 T(YAFFS_TRACE_VERIFY,
682 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
683 obj->objectId, actualTallness, requiredTallness));
686 /* Check that the chunks in the tnode tree are all correct.
687 * We do this by scanning through the tnode tree and
688 * checking the tags for every chunk match.
691 if (yaffs_SkipNANDVerification(dev))
694 for (i = 1; i <= lastChunk; i++) {
695 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
698 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
700 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
701 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
702 if (tags.objectId != objectId || tags.chunkId != i) {
703 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
704 objectId, i, theChunk,
705 tags.objectId, tags.chunkId));
713 static void yaffs_VerifyHardLink(yaffs_Object *obj)
715 if (obj && yaffs_SkipVerification(obj->myDev))
718 /* Verify sane equivalent object */
721 static void yaffs_VerifySymlink(yaffs_Object *obj)
723 if (obj && yaffs_SkipVerification(obj->myDev))
726 /* Verify symlink string */
729 static void yaffs_VerifySpecial(yaffs_Object *obj)
731 if (obj && yaffs_SkipVerification(obj->myDev))
735 static void yaffs_VerifyObject(yaffs_Object *obj)
744 __u32 chunkShouldNotBeDeleted;
750 if (obj->beingCreated)
755 if (yaffs_SkipVerification(dev))
758 /* Check sane object header chunk */
760 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
761 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
763 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
764 chunkIdOk = chunkInRange || obj->hdrChunk == 0;
765 chunkValid = chunkInRange &&
766 yaffs_CheckChunkBit(dev,
767 obj->hdrChunk / dev->nChunksPerBlock,
768 obj->hdrChunk % dev->nChunksPerBlock);
769 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
772 (!chunkIdOk || chunkShouldNotBeDeleted)) {
773 T(YAFFS_TRACE_VERIFY,
774 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
775 obj->objectId, obj->hdrChunk,
776 chunkIdOk ? "" : ",out of range",
777 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
780 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
781 yaffs_ExtendedTags tags;
782 yaffs_ObjectHeader *oh;
783 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
785 oh = (yaffs_ObjectHeader *)buffer;
787 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
790 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
792 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
795 /* Verify it has a parent */
796 if (obj && !obj->fake &&
797 (!obj->parent || obj->parent->myDev != dev)) {
798 T(YAFFS_TRACE_VERIFY,
799 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
800 obj->objectId, obj->parent));
803 /* Verify parent is a directory */
804 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
805 T(YAFFS_TRACE_VERIFY,
806 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
807 obj->objectId, obj->parent->variantType));
810 switch (obj->variantType) {
811 case YAFFS_OBJECT_TYPE_FILE:
812 yaffs_VerifyFile(obj);
814 case YAFFS_OBJECT_TYPE_SYMLINK:
815 yaffs_VerifySymlink(obj);
817 case YAFFS_OBJECT_TYPE_DIRECTORY:
818 yaffs_VerifyDirectory(obj);
820 case YAFFS_OBJECT_TYPE_HARDLINK:
821 yaffs_VerifyHardLink(obj);
823 case YAFFS_OBJECT_TYPE_SPECIAL:
824 yaffs_VerifySpecial(obj);
826 case YAFFS_OBJECT_TYPE_UNKNOWN:
828 T(YAFFS_TRACE_VERIFY,
829 (TSTR("Obj %d has illegaltype %d"TENDSTR),
830 obj->objectId, obj->variantType));
835 static void yaffs_VerifyObjects(yaffs_Device *dev)
839 struct ylist_head *lh;
841 if (yaffs_SkipVerification(dev))
844 /* Iterate through the objects in each hash entry */
846 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
847 ylist_for_each(lh, &dev->objectBucket[i].list) {
849 obj = ylist_entry(lh, yaffs_Object, hashLink);
850 yaffs_VerifyObject(obj);
858 * Simple hash function. Needs to have a reasonable spread
861 static Y_INLINE int yaffs_HashFunction(int n)
864 return n % YAFFS_NOBJECT_BUCKETS;
868 * Access functions to useful fake objects.
869 * Note that root might have a presence in NAND if permissions are set.
872 yaffs_Object *yaffs_Root(yaffs_Device *dev)
877 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
879 return dev->lostNFoundDir;
884 * Erased NAND checking functions
887 int yaffs_CheckFF(__u8 *buffer, int nBytes)
889 /* Horrible, slow implementation */
898 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
901 int retval = YAFFS_OK;
902 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
903 yaffs_ExtendedTags tags;
906 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
908 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
911 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
912 T(YAFFS_TRACE_NANDACCESS,
913 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
917 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
923 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
925 yaffs_ExtendedTags *tags,
932 yaffs_InvalidateCheckpoint(dev);
935 yaffs_BlockInfo *bi = 0;
938 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
944 /* First check this chunk is erased, if it needs
945 * checking. The checking policy (unless forced
946 * always on) is as follows:
948 * Check the first page we try to write in a block.
949 * If the check passes then we don't need to check any
950 * more. If the check fails, we check again...
951 * If the block has been erased, we don't need to check.
953 * However, if the block has been prioritised for gc,
954 * then we think there might be something odd about
955 * this block and stop using it.
957 * Rationale: We should only ever see chunks that have
958 * not been erased if there was a partially written
959 * chunk due to power loss. This checking policy should
960 * catch that case with very few checks and thus save a
961 * lot of checks that are most likely not needed.
963 if (bi->gcPrioritise) {
964 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
965 /* try another chunk */
969 /* let's give it a try */
972 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
973 bi->skipErasedCheck = 0;
975 if (!bi->skipErasedCheck) {
976 erasedOk = yaffs_CheckChunkErased(dev, chunk);
977 if (erasedOk != YAFFS_OK) {
979 (TSTR ("**>> yaffs chunk %d was not erased"
982 /* try another chunk */
985 bi->skipErasedCheck = 1;
988 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
990 if (writeOk != YAFFS_OK) {
991 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
992 /* try another chunk */
996 /* Copy the data into the robustification buffer */
997 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
999 } while (writeOk != YAFFS_OK &&
1000 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1006 T(YAFFS_TRACE_ERROR,
1007 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1010 dev->nRetriedWrites += (attempts - 1);
1017 * Block retiring for handling a broken block.
1020 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1022 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1024 yaffs_InvalidateCheckpoint(dev);
1026 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1027 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1028 T(YAFFS_TRACE_ALWAYS, (TSTR(
1029 "yaffs: Failed to mark bad and erase block %d"
1030 TENDSTR), blockInNAND));
1032 yaffs_ExtendedTags tags;
1033 int chunkId = blockInNAND * dev->nChunksPerBlock;
1035 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1037 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1038 yaffs_InitialiseTags(&tags);
1039 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1040 if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1041 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1042 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1043 TCONT("write bad block marker to block %d")
1044 TENDSTR), blockInNAND));
1046 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1050 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1051 bi->gcPrioritise = 0;
1052 bi->needsRetiring = 0;
1054 dev->nRetiredBlocks++;
1058 * Functions for robustisizing TODO
1062 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1064 const yaffs_ExtendedTags *tags)
1068 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1069 const yaffs_ExtendedTags *tags)
1073 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1075 if (!bi->gcPrioritise) {
1076 bi->gcPrioritise = 1;
1077 dev->hasPendingPrioritisedGCs = 1;
1078 bi->chunkErrorStrikes++;
1080 if (bi->chunkErrorStrikes > 3) {
1081 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1082 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1088 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1091 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1092 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1094 yaffs_HandleChunkError(dev, bi);
1097 /* Was an actual write failure, so mark the block for retirement */
1098 bi->needsRetiring = 1;
1099 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1100 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1103 /* Delete the chunk */
1104 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1108 /*---------------- Name handling functions ------------*/
1110 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1115 const YUCHAR *bname = (const YUCHAR *) name;
1117 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1119 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1120 sum += yaffs_toupper(*bname) * i;
1122 sum += (*bname) * i;
1131 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1133 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1134 memset(obj->shortName, 0, sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1135 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1136 yaffs_strcpy(obj->shortName, name);
1138 obj->shortName[0] = _Y('\0');
1141 obj->sum = yaffs_CalcNameSum(name);
1144 /*-------------------- TNODES -------------------
1146 * List of spare tnodes
1147 * The list is hooked together using the first pointer
1151 /* yaffs_CreateTnodes creates a bunch more tnodes and
1152 * adds them to the tnode free list.
1153 * Don't use this function directly
1156 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1160 yaffs_Tnode *newTnodes;
1164 yaffs_TnodeList *tnl;
1169 /* Calculate the tnode size in bytes for variable width tnode support.
1170 * Must be a multiple of 32-bits */
1171 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1173 if (tnodeSize < sizeof(yaffs_Tnode))
1174 tnodeSize = sizeof(yaffs_Tnode);
1176 /* make these things */
1178 newTnodes = YMALLOC(nTnodes * tnodeSize);
1179 mem = (__u8 *)newTnodes;
1182 T(YAFFS_TRACE_ERROR,
1183 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1187 /* Hook them into the free list */
1189 for (i = 0; i < nTnodes - 1; i++) {
1190 newTnodes[i].internal[0] = &newTnodes[i + 1];
1191 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1192 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1196 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1197 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1198 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1200 dev->freeTnodes = newTnodes;
1202 /* New hookup for wide tnodes */
1203 for (i = 0; i < nTnodes - 1; i++) {
1204 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1205 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1206 curr->internal[0] = next;
1209 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1210 curr->internal[0] = dev->freeTnodes;
1211 dev->freeTnodes = (yaffs_Tnode *)mem;
1216 dev->nFreeTnodes += nTnodes;
1217 dev->nTnodesCreated += nTnodes;
1219 /* Now add this bunch of tnodes to a list for freeing up.
1220 * NB If we can't add this to the management list it isn't fatal
1221 * but it just means we can't free this bunch of tnodes later.
1224 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1226 T(YAFFS_TRACE_ERROR,
1228 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1231 tnl->tnodes = newTnodes;
1232 tnl->next = dev->allocatedTnodeList;
1233 dev->allocatedTnodeList = tnl;
1236 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1241 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1243 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1245 yaffs_Tnode *tn = NULL;
1247 /* If there are none left make more */
1248 if (!dev->freeTnodes) {
1249 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1252 if (dev->freeTnodes) {
1253 tn = dev->freeTnodes;
1254 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1255 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1256 /* Hoosterman, this thing looks like it isn't in the list */
1257 T(YAFFS_TRACE_ALWAYS,
1258 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1261 dev->freeTnodes = dev->freeTnodes->internal[0];
1265 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1270 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1272 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1273 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1275 if (tnodeSize < sizeof(yaffs_Tnode))
1276 tnodeSize = sizeof(yaffs_Tnode);
1279 memset(tn, 0, tnodeSize);
1284 /* FreeTnode frees up a tnode and puts it back on the free list */
1285 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1288 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1289 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1290 /* Hoosterman, this thing looks like it is already in the list */
1291 T(YAFFS_TRACE_ALWAYS,
1292 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1294 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1296 tn->internal[0] = dev->freeTnodes;
1297 dev->freeTnodes = tn;
1300 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1303 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1305 /* Free the list of allocated tnodes */
1306 yaffs_TnodeList *tmp;
1308 while (dev->allocatedTnodeList) {
1309 tmp = dev->allocatedTnodeList->next;
1311 YFREE(dev->allocatedTnodeList->tnodes);
1312 YFREE(dev->allocatedTnodeList);
1313 dev->allocatedTnodeList = tmp;
1317 dev->freeTnodes = NULL;
1318 dev->nFreeTnodes = 0;
1321 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1323 dev->allocatedTnodeList = NULL;
1324 dev->freeTnodes = NULL;
1325 dev->nFreeTnodes = 0;
1326 dev->nTnodesCreated = 0;
1330 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1333 __u32 *map = (__u32 *)tn;
1339 pos &= YAFFS_TNODES_LEVEL0_MASK;
1340 val >>= dev->chunkGroupBits;
1342 bitInMap = pos * dev->tnodeWidth;
1343 wordInMap = bitInMap / 32;
1344 bitInWord = bitInMap & (32 - 1);
1346 mask = dev->tnodeMask << bitInWord;
1348 map[wordInMap] &= ~mask;
1349 map[wordInMap] |= (mask & (val << bitInWord));
1351 if (dev->tnodeWidth > (32 - bitInWord)) {
1352 bitInWord = (32 - bitInWord);
1354 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1355 map[wordInMap] &= ~mask;
1356 map[wordInMap] |= (mask & (val >> bitInWord));
1360 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1363 __u32 *map = (__u32 *)tn;
1369 pos &= YAFFS_TNODES_LEVEL0_MASK;
1371 bitInMap = pos * dev->tnodeWidth;
1372 wordInMap = bitInMap / 32;
1373 bitInWord = bitInMap & (32 - 1);
1375 val = map[wordInMap] >> bitInWord;
1377 if (dev->tnodeWidth > (32 - bitInWord)) {
1378 bitInWord = (32 - bitInWord);
1380 val |= (map[wordInMap] << bitInWord);
1383 val &= dev->tnodeMask;
1384 val <<= dev->chunkGroupBits;
1389 /* ------------------- End of individual tnode manipulation -----------------*/
1391 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1392 * The look up tree is represented by the top tnode and the number of topLevel
1393 * in the tree. 0 means only the level 0 tnode is in the tree.
1396 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1397 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1398 yaffs_FileStructure *fStruct,
1401 yaffs_Tnode *tn = fStruct->top;
1403 int requiredTallness;
1404 int level = fStruct->topLevel;
1406 /* Check sane level and chunk Id */
1407 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1411 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1415 /* First check we're tall enough (ie enough topLevel) */
1417 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1418 requiredTallness = 0;
1420 i >>= YAFFS_TNODES_INTERNAL_BITS;
1424 if (requiredTallness > fStruct->topLevel) {
1425 /* Not tall enough, so we can't find it, return NULL. */
1429 /* Traverse down to level 0 */
1430 while (level > 0 && tn) {
1431 tn = tn->internal[(chunkId >>
1432 (YAFFS_TNODES_LEVEL0_BITS +
1434 YAFFS_TNODES_INTERNAL_BITS)) &
1435 YAFFS_TNODES_INTERNAL_MASK];
1442 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1443 * This happens in two steps:
1444 * 1. If the tree isn't tall enough, then make it taller.
1445 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1447 * Used when modifying the tree.
1449 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1450 * be plugged into the ttree.
1453 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1454 yaffs_FileStructure *fStruct,
1456 yaffs_Tnode *passedTn)
1458 int requiredTallness;
1466 /* Check sane level and page Id */
1467 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1471 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1475 /* First check we're tall enough (ie enough topLevel) */
1477 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1478 requiredTallness = 0;
1480 x >>= YAFFS_TNODES_INTERNAL_BITS;
1485 if (requiredTallness > fStruct->topLevel) {
1486 /* Not tall enough, gotta make the tree taller */
1487 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1489 tn = yaffs_GetTnode(dev);
1492 tn->internal[0] = fStruct->top;
1495 T(YAFFS_TRACE_ERROR,
1496 (TSTR("yaffs: no more tnodes" TENDSTR)));
1500 fStruct->topLevel = requiredTallness;
1503 /* Traverse down to level 0, adding anything we need */
1505 l = fStruct->topLevel;
1509 while (l > 0 && tn) {
1511 (YAFFS_TNODES_LEVEL0_BITS +
1512 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1513 YAFFS_TNODES_INTERNAL_MASK;
1516 if ((l > 1) && !tn->internal[x]) {
1517 /* Add missing non-level-zero tnode */
1518 tn->internal[x] = yaffs_GetTnode(dev);
1520 } else if (l == 1) {
1521 /* Looking from level 1 at level 0 */
1523 /* If we already have one, then release it.*/
1524 if (tn->internal[x])
1525 yaffs_FreeTnode(dev, tn->internal[x]);
1526 tn->internal[x] = passedTn;
1528 } else if (!tn->internal[x]) {
1529 /* Don't have one, none passed in */
1530 tn->internal[x] = yaffs_GetTnode(dev);
1534 tn = tn->internal[x];
1538 /* top is level 0 */
1540 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1541 yaffs_FreeTnode(dev, passedTn);
1548 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1549 yaffs_ExtendedTags *tags, int objectId,
1554 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1555 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1556 theChunk % dev->nChunksPerBlock)) {
1557 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1559 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1570 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1571 * chunks and tnodes in the file
1572 * Returns 1 if the tree was deleted.
1573 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1576 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1577 int chunkOffset, int *limit)
1582 yaffs_ExtendedTags tags;
1584 yaffs_Device *dev = in->myDev;
1590 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1592 if (tn->internal[i]) {
1593 if (limit && (*limit) < 0) {
1597 yaffs_DeleteWorker(in,
1605 YAFFS_TNODES_INTERNAL_BITS)
1610 yaffs_FreeTnode(dev,
1613 tn->internal[i] = NULL;
1617 return (allDone) ? 1 : 0;
1618 } else if (level == 0) {
1621 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1623 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1626 chunkInInode = (chunkOffset <<
1627 YAFFS_TNODES_LEVEL0_BITS) + i;
1630 yaffs_FindChunkInGroup(dev,
1636 if (foundChunk > 0) {
1637 yaffs_DeleteChunk(dev,
1642 *limit = *limit - 1;
1650 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1654 return (i < 0) ? 1 : 0;
1664 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1666 yaffs_BlockInfo *theBlock;
1668 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1670 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1672 theBlock->softDeletions++;
1677 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1678 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1680 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1683 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1684 __u32 level, int chunkOffset)
1689 yaffs_Device *dev = in->myDev;
1694 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1696 if (tn->internal[i]) {
1698 yaffs_SoftDeleteWorker(in,
1704 YAFFS_TNODES_INTERNAL_BITS)
1707 yaffs_FreeTnode(dev,
1710 tn->internal[i] = NULL;
1712 /* Hoosterman... how could this happen? */
1716 return (allDone) ? 1 : 0;
1717 } else if (level == 0) {
1719 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1720 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1722 /* Note this does not find the real chunk, only the chunk group.
1723 * We make an assumption that a chunk group is not larger than
1726 yaffs_SoftDeleteChunk(dev, theChunk);
1727 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1741 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1744 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1745 if (obj->nDataChunks <= 0) {
1746 /* Empty file with no duplicate object headers, just delete it immediately */
1747 yaffs_FreeTnode(obj->myDev,
1748 obj->variant.fileVariant.top);
1749 obj->variant.fileVariant.top = NULL;
1750 T(YAFFS_TRACE_TRACING,
1751 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1753 yaffs_DoGenericObjectDeletion(obj);
1755 yaffs_SoftDeleteWorker(obj,
1756 obj->variant.fileVariant.top,
1757 obj->variant.fileVariant.
1759 obj->softDeleted = 1;
1764 /* Pruning removes any part of the file structure tree that is beyond the
1765 * bounds of the file (ie that does not point to chunks).
1767 * A file should only get pruned when its size is reduced.
1769 * Before pruning, the chunks must be pulled from the tree and the
1770 * level 0 tnode entries must be zeroed out.
1771 * Could also use this for file deletion, but that's probably better handled
1772 * by a special case.
1775 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1776 __u32 level, int del0)
1784 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1785 if (tn->internal[i] && level > 0) {
1787 yaffs_PruneWorker(dev, tn->internal[i],
1789 (i == 0) ? del0 : 1);
1792 if (tn->internal[i]) {
1797 if (hasData == 0 && del0) {
1798 /* Free and return NULL */
1800 yaffs_FreeTnode(dev, tn);
1810 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1811 yaffs_FileStructure *fStruct)
1818 if (fStruct->topLevel > 0) {
1820 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1822 /* Now we have a tree with all the non-zero branches NULL but the height
1823 * is the same as it was.
1824 * Let's see if we can trim internal tnodes to shorten the tree.
1825 * We can do this if only the 0th element in the tnode is in use
1826 * (ie all the non-zero are NULL)
1829 while (fStruct->topLevel && !done) {
1833 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1834 if (tn->internal[i]) {
1840 fStruct->top = tn->internal[0];
1841 fStruct->topLevel--;
1842 yaffs_FreeTnode(dev, tn);
1852 /*-------------------- End of File Structure functions.-------------------*/
1854 /* yaffs_CreateFreeObjects creates a bunch more objects and
1855 * adds them to the object free list.
1857 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1860 yaffs_Object *newObjects;
1861 yaffs_ObjectList *list;
1866 /* make these things */
1867 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1868 list = YMALLOC(sizeof(yaffs_ObjectList));
1870 if (!newObjects || !list) {
1875 T(YAFFS_TRACE_ALLOCATE,
1876 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1880 /* Hook them into the free list */
1881 for (i = 0; i < nObjects - 1; i++) {
1882 newObjects[i].siblings.next =
1883 (struct ylist_head *)(&newObjects[i + 1]);
1886 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1887 dev->freeObjects = newObjects;
1888 dev->nFreeObjects += nObjects;
1889 dev->nObjectsCreated += nObjects;
1891 /* Now add this bunch of Objects to a list for freeing up. */
1893 list->objects = newObjects;
1894 list->next = dev->allocatedObjectList;
1895 dev->allocatedObjectList = list;
1901 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1902 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1904 yaffs_Object *tn = NULL;
1906 #ifdef VALGRIND_TEST
1907 tn = YMALLOC(sizeof(yaffs_Object));
1909 /* If there are none left make more */
1910 if (!dev->freeObjects) {
1911 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1914 if (dev->freeObjects) {
1915 tn = dev->freeObjects;
1917 (yaffs_Object *) (dev->freeObjects->siblings.next);
1918 dev->nFreeObjects--;
1922 /* Now sweeten it up... */
1924 memset(tn, 0, sizeof(yaffs_Object));
1925 tn->beingCreated = 1;
1929 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1930 YINIT_LIST_HEAD(&(tn->hardLinks));
1931 YINIT_LIST_HEAD(&(tn->hashLink));
1932 YINIT_LIST_HEAD(&tn->siblings);
1935 /* Now make the directory sane */
1937 tn->parent = dev->rootDir;
1938 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1941 /* Add it to the lost and found directory.
1942 * NB Can't put root or lostNFound in lostNFound so
1943 * check if lostNFound exists first
1945 if (dev->lostNFoundDir) {
1946 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1949 tn->beingCreated = 0;
1952 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1957 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1962 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1964 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1965 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1966 obj->unlinkAllowed = 0; /* ... or unlink it */
1969 obj->yst_mode = mode;
1971 obj->hdrChunk = 0; /* Not a valid chunk. */
1978 static void yaffs_UnhashObject(yaffs_Object *tn)
1981 yaffs_Device *dev = tn->myDev;
1983 /* If it is still linked into the bucket list, free from the list */
1984 if (!ylist_empty(&tn->hashLink)) {
1985 ylist_del_init(&tn->hashLink);
1986 bucket = yaffs_HashFunction(tn->objectId);
1987 dev->objectBucket[bucket].count--;
1991 /* FreeObject frees up a Object and puts it back on the free list */
1992 static void yaffs_FreeObject(yaffs_Object *tn)
1994 yaffs_Device *dev = tn->myDev;
1997 T(YAFFS_TRACE_OS,(TSTR("FreeObject %p inode %p"TENDSTR),tn,tn->myInode));
2002 if (!ylist_empty(&tn->siblings))
2008 /* We're still hooked up to a cached inode.
2009 * Don't delete now, but mark for later deletion
2011 tn->deferedFree = 1;
2016 yaffs_UnhashObject(tn);
2018 #ifdef VALGRIND_TEST
2021 /* Link into the free list. */
2022 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2023 dev->freeObjects = tn;
2024 dev->nFreeObjects++;
2026 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2031 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2033 if (obj->deferedFree) {
2034 yaffs_FreeObject(obj);
2040 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2042 /* Free the list of allocated Objects */
2044 yaffs_ObjectList *tmp;
2046 while (dev->allocatedObjectList) {
2047 tmp = dev->allocatedObjectList->next;
2048 YFREE(dev->allocatedObjectList->objects);
2049 YFREE(dev->allocatedObjectList);
2051 dev->allocatedObjectList = tmp;
2054 dev->freeObjects = NULL;
2055 dev->nFreeObjects = 0;
2058 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2062 dev->allocatedObjectList = NULL;
2063 dev->freeObjects = NULL;
2064 dev->nFreeObjects = 0;
2066 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2067 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2068 dev->objectBucket[i].count = 0;
2072 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2077 int lowest = 999999;
2079 /* First let's see if we can find one that's empty. */
2081 for (i = 0; i < 10 && lowest > 0; i++) {
2083 x %= YAFFS_NOBJECT_BUCKETS;
2084 if (dev->objectBucket[x].count < lowest) {
2085 lowest = dev->objectBucket[x].count;
2091 /* If we didn't find an empty list, then try
2092 * looking a bit further for a short one
2095 for (i = 0; i < 10 && lowest > 3; i++) {
2097 x %= YAFFS_NOBJECT_BUCKETS;
2098 if (dev->objectBucket[x].count < lowest) {
2099 lowest = dev->objectBucket[x].count;
2108 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2110 int bucket = yaffs_FindNiceObjectBucket(dev);
2112 /* Now find an object value that has not already been taken
2113 * by scanning the list.
2117 struct ylist_head *i;
2119 __u32 n = (__u32) bucket;
2121 /* yaffs_CheckObjectHashSanity(); */
2125 n += YAFFS_NOBJECT_BUCKETS;
2126 if (1 || dev->objectBucket[bucket].count > 0) {
2127 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2128 /* If there is already one in the list */
2129 if (i && ylist_entry(i, yaffs_Object,
2130 hashLink)->objectId == n) {
2140 static void yaffs_HashObject(yaffs_Object *in)
2142 int bucket = yaffs_HashFunction(in->objectId);
2143 yaffs_Device *dev = in->myDev;
2145 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2146 dev->objectBucket[bucket].count++;
2149 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2151 int bucket = yaffs_HashFunction(number);
2152 struct ylist_head *i;
2155 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2156 /* Look if it is in the list */
2158 in = ylist_entry(i, yaffs_Object, hashLink);
2159 if (in->objectId == number) {
2161 /* Don't tell the VFS about this one if it is defered free */
2162 if (in->deferedFree)
2174 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2175 yaffs_ObjectType type)
2177 yaffs_Object *theObject;
2178 yaffs_Tnode *tn = NULL;
2181 number = yaffs_CreateNewObjectNumber(dev);
2184 theObject = yaffs_AllocateEmptyObject(dev);
2188 if (type == YAFFS_OBJECT_TYPE_FILE) {
2189 tn = yaffs_GetTnode(dev);
2191 yaffs_FreeObject(theObject);
2197 theObject->fake = 0;
2198 theObject->renameAllowed = 1;
2199 theObject->unlinkAllowed = 1;
2200 theObject->objectId = number;
2201 yaffs_HashObject(theObject);
2202 theObject->variantType = type;
2203 #ifdef CONFIG_YAFFS_WINCE
2204 yfsd_WinFileTimeNow(theObject->win_atime);
2205 theObject->win_ctime[0] = theObject->win_mtime[0] =
2206 theObject->win_atime[0];
2207 theObject->win_ctime[1] = theObject->win_mtime[1] =
2208 theObject->win_atime[1];
2212 theObject->yst_atime = theObject->yst_mtime =
2213 theObject->yst_ctime = Y_CURRENT_TIME;
2216 case YAFFS_OBJECT_TYPE_FILE:
2217 theObject->variant.fileVariant.fileSize = 0;
2218 theObject->variant.fileVariant.scannedFileSize = 0;
2219 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2220 theObject->variant.fileVariant.topLevel = 0;
2221 theObject->variant.fileVariant.top = tn;
2223 case YAFFS_OBJECT_TYPE_DIRECTORY:
2224 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2227 case YAFFS_OBJECT_TYPE_SYMLINK:
2228 case YAFFS_OBJECT_TYPE_HARDLINK:
2229 case YAFFS_OBJECT_TYPE_SPECIAL:
2230 /* No action required */
2232 case YAFFS_OBJECT_TYPE_UNKNOWN:
2233 /* todo this should not happen */
2241 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2243 yaffs_ObjectType type)
2245 yaffs_Object *theObject = NULL;
2248 theObject = yaffs_FindObjectByNumber(dev, number);
2252 theObject = yaffs_CreateNewObject(dev, number, type);
2260 static YCHAR *yaffs_CloneString(const YCHAR *str)
2262 YCHAR *newStr = NULL;
2265 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2267 yaffs_strcpy(newStr, str);
2275 * Mknod (create) a new object.
2276 * equivalentObject only has meaning for a hard link;
2277 * aliasString only has meaning for a sumlink.
2278 * rdev only has meaning for devices (a subset of special objects)
2281 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2282 yaffs_Object *parent,
2287 yaffs_Object *equivalentObject,
2288 const YCHAR *aliasString, __u32 rdev)
2293 yaffs_Device *dev = parent->myDev;
2295 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2296 if (yaffs_FindObjectByName(parent, name)) {
2300 in = yaffs_CreateNewObject(dev, -1, type);
2305 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2306 str = yaffs_CloneString(aliasString);
2308 yaffs_FreeObject(in);
2318 in->variantType = type;
2320 in->yst_mode = mode;
2322 #ifdef CONFIG_YAFFS_WINCE
2323 yfsd_WinFileTimeNow(in->win_atime);
2324 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2325 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2328 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2330 in->yst_rdev = rdev;
2334 in->nDataChunks = 0;
2336 yaffs_SetObjectName(in, name);
2339 yaffs_AddObjectToDirectory(parent, in);
2341 in->myDev = parent->myDev;
2344 case YAFFS_OBJECT_TYPE_SYMLINK:
2345 in->variant.symLinkVariant.alias = str;
2347 case YAFFS_OBJECT_TYPE_HARDLINK:
2348 in->variant.hardLinkVariant.equivalentObject =
2350 in->variant.hardLinkVariant.equivalentObjectId =
2351 equivalentObject->objectId;
2352 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2354 case YAFFS_OBJECT_TYPE_FILE:
2355 case YAFFS_OBJECT_TYPE_DIRECTORY:
2356 case YAFFS_OBJECT_TYPE_SPECIAL:
2357 case YAFFS_OBJECT_TYPE_UNKNOWN:
2362 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2363 /* Could not create the object header, fail the creation */
2364 yaffs_DeleteObject(in);
2373 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2374 __u32 mode, __u32 uid, __u32 gid)
2376 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2377 uid, gid, NULL, NULL, 0);
2380 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2381 __u32 mode, __u32 uid, __u32 gid)
2383 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2384 mode, uid, gid, NULL, NULL, 0);
2387 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2388 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2390 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2391 uid, gid, NULL, NULL, rdev);
2394 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2395 __u32 mode, __u32 uid, __u32 gid,
2398 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2399 uid, gid, NULL, alias, 0);
2402 /* yaffs_Link returns the object id of the equivalent object.*/
2403 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2404 yaffs_Object *equivalentObject)
2406 /* Get the real object in case we were fed a hard link as an equivalent object */
2407 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2409 if (yaffs_MknodObject
2410 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2411 equivalentObject, NULL, 0)) {
2412 return equivalentObject;
2419 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2420 const YCHAR *newName, int force, int shadows)
2425 yaffs_Object *existingTarget;
2427 if (newDir == NULL) {
2428 newDir = obj->parent; /* use the old directory */
2431 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2432 T(YAFFS_TRACE_ALWAYS,
2434 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2439 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2440 if (obj->myDev->isYaffs2) {
2441 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2443 unlinkOp = (newDir == obj->myDev->unlinkedDir
2444 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2447 deleteOp = (newDir == obj->myDev->deletedDir);
2449 existingTarget = yaffs_FindObjectByName(newDir, newName);
2451 /* If the object is a file going into the unlinked directory,
2452 * then it is OK to just stuff it in since duplicate names are allowed.
2453 * else only proceed if the new name does not exist and if we're putting
2454 * it into a directory.
2461 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2462 yaffs_SetObjectName(obj, newName);
2465 yaffs_AddObjectToDirectory(newDir, obj);
2470 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2471 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2478 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2479 yaffs_Object *newDir, const YCHAR *newName)
2481 yaffs_Object *obj = NULL;
2482 yaffs_Object *existingTarget = NULL;
2486 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2488 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2491 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2492 /* Special case for case insemsitive systems (eg. WinCE).
2493 * While look-up is case insensitive, the name isn't.
2494 * Therefore we might want to change x.txt to X.txt
2496 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2501 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2505 obj = yaffs_FindObjectByName(oldDir, oldName);
2507 if (obj && obj->renameAllowed) {
2509 /* Now do the handling for an existing target, if there is one */
2511 existingTarget = yaffs_FindObjectByName(newDir, newName);
2512 if (existingTarget &&
2513 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2514 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2515 /* There is a target that is a non-empty directory, so we fail */
2516 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2517 } else if (existingTarget && existingTarget != obj) {
2518 /* Nuke the target first, using shadowing,
2519 * but only if it isn't the same object
2521 yaffs_ChangeObjectName(obj, newDir, newName, force,
2522 existingTarget->objectId);
2523 yaffs_UnlinkObject(existingTarget);
2526 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2531 /*------------------------- Block Management and Page Allocation ----------------*/
2533 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2535 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2537 dev->blockInfo = NULL;
2538 dev->chunkBits = NULL;
2540 dev->allocationBlock = -1; /* force it to get a new one */
2542 /* If the first allocation strategy fails, thry the alternate one */
2543 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2544 if (!dev->blockInfo) {
2545 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2546 dev->blockInfoAlt = 1;
2548 dev->blockInfoAlt = 0;
2550 if (dev->blockInfo) {
2551 /* Set up dynamic blockinfo stuff. */
2552 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2553 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2554 if (!dev->chunkBits) {
2555 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2556 dev->chunkBitsAlt = 1;
2558 dev->chunkBitsAlt = 0;
2561 if (dev->blockInfo && dev->chunkBits) {
2562 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2563 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2570 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2572 if (dev->blockInfoAlt && dev->blockInfo)
2573 YFREE_ALT(dev->blockInfo);
2574 else if (dev->blockInfo)
2575 YFREE(dev->blockInfo);
2577 dev->blockInfoAlt = 0;
2579 dev->blockInfo = NULL;
2581 if (dev->chunkBitsAlt && dev->chunkBits)
2582 YFREE_ALT(dev->chunkBits);
2583 else if (dev->chunkBits)
2584 YFREE(dev->chunkBits);
2585 dev->chunkBitsAlt = 0;
2586 dev->chunkBits = NULL;
2589 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2590 yaffs_BlockInfo *bi)
2597 return 1; /* disqualification only applies to yaffs2. */
2599 if (!bi->hasShrinkHeader)
2600 return 1; /* can gc */
2602 /* Find the oldest dirty sequence number if we don't know it and save it
2603 * so we don't have to keep recomputing it.
2605 if (!dev->oldestDirtySequence) {
2606 seq = dev->sequenceNumber;
2608 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2610 b = yaffs_GetBlockInfo(dev, i);
2611 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2612 (b->pagesInUse - b->softDeletions) <
2613 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2614 seq = b->sequenceNumber;
2617 dev->oldestDirtySequence = seq;
2620 /* Can't do gc of this block if there are any blocks older than this one that have
2623 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2626 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2627 * for garbage collection.
2630 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2633 int b = dev->currentDirtyChecker;
2639 int prioritised = 0;
2640 yaffs_BlockInfo *bi;
2641 int pendingPrioritisedExist = 0;
2643 /* First let's see if we need to grab a prioritised block */
2644 if (dev->hasPendingPrioritisedGCs) {
2645 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2647 bi = yaffs_GetBlockInfo(dev, i);
2648 /* yaffs_VerifyBlock(dev,bi,i); */
2650 if (bi->gcPrioritise) {
2651 pendingPrioritisedExist = 1;
2652 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2653 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2654 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2657 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2662 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2663 dev->hasPendingPrioritisedGCs = 0;
2666 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2668 * else (we're doing a leasurely gc), then we only bother to do this if the
2669 * block has only a few pages in use.
2672 dev->nonAggressiveSkip--;
2674 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2680 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2684 dev->internalEndBlock - dev->internalStartBlock + 1;
2687 dev->internalEndBlock - dev->internalStartBlock + 1;
2688 iterations = iterations / 16;
2689 if (iterations > 200) {
2694 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2696 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2697 b = dev->internalStartBlock;
2700 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2701 T(YAFFS_TRACE_ERROR,
2702 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2706 bi = yaffs_GetBlockInfo(dev, b);
2709 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2715 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2716 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2717 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2719 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2723 dev->currentDirtyChecker = b;
2727 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2728 dev->nChunksPerBlock - pagesInUse, prioritised));
2731 dev->oldestDirtySequence = 0;
2734 dev->nonAggressiveSkip = 4;
2739 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2741 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2745 /* If the block is still healthy erase it and mark as clean.
2746 * If the block has had a data failure, then retire it.
2749 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2750 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2751 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2753 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2755 if (!bi->needsRetiring) {
2756 yaffs_InvalidateCheckpoint(dev);
2757 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2759 dev->nErasureFailures++;
2760 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2761 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2766 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2768 for (i = 0; i < dev->nChunksPerBlock; i++) {
2769 if (!yaffs_CheckChunkErased
2770 (dev, blockNo * dev->nChunksPerBlock + i)) {
2771 T(YAFFS_TRACE_ERROR,
2773 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2774 TENDSTR), blockNo, i));
2780 /* Clean it up... */
2781 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2782 dev->nErasedBlocks++;
2784 bi->softDeletions = 0;
2785 bi->hasShrinkHeader = 0;
2786 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2787 bi->gcPrioritise = 0;
2788 yaffs_ClearChunkBits(dev, blockNo);
2790 T(YAFFS_TRACE_ERASE,
2791 (TSTR("Erased block %d" TENDSTR), blockNo));
2793 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2795 yaffs_RetireBlock(dev, blockNo);
2796 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2797 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2801 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2805 yaffs_BlockInfo *bi;
2807 if (dev->nErasedBlocks < 1) {
2808 /* Hoosterman we've got a problem.
2809 * Can't get space to gc
2811 T(YAFFS_TRACE_ERROR,
2812 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2817 /* Find an empty block. */
2819 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2820 dev->allocationBlockFinder++;
2821 if (dev->allocationBlockFinder < dev->internalStartBlock
2822 || dev->allocationBlockFinder > dev->internalEndBlock) {
2823 dev->allocationBlockFinder = dev->internalStartBlock;
2826 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2828 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2829 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2830 dev->sequenceNumber++;
2831 bi->sequenceNumber = dev->sequenceNumber;
2832 dev->nErasedBlocks--;
2833 T(YAFFS_TRACE_ALLOCATE,
2834 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2835 dev->allocationBlockFinder, dev->sequenceNumber,
2836 dev->nErasedBlocks));
2837 return dev->allocationBlockFinder;
2841 T(YAFFS_TRACE_ALWAYS,
2843 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2844 TENDSTR), dev->nErasedBlocks));
2851 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2853 if (!dev->nCheckpointBlocksRequired &&
2855 /* Not a valid value so recalculate */
2858 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2861 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2863 if (tnodeSize < sizeof(yaffs_Tnode))
2864 tnodeSize = sizeof(yaffs_Tnode);
2866 nBytes += sizeof(yaffs_CheckpointValidity);
2867 nBytes += sizeof(yaffs_CheckpointDevice);
2868 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2869 nBytes += devBlocks * dev->chunkBitmapStride;
2870 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2871 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2872 nBytes += sizeof(yaffs_CheckpointValidity);
2873 nBytes += sizeof(__u32); /* checksum*/
2875 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2877 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2879 dev->nCheckpointBlocksRequired = nBlocks;
2882 return dev->nCheckpointBlocksRequired;
2886 * Check if there's space to allocate...
2887 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2889 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2892 int reservedBlocks = dev->nReservedBlocks;
2893 int checkpointBlocks;
2895 if (dev->isYaffs2) {
2896 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2897 dev->blocksInCheckpoint;
2898 if (checkpointBlocks < 0)
2899 checkpointBlocks = 0;
2901 checkpointBlocks = 0;
2904 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2906 return (dev->nFreeChunks > reservedChunks);
2909 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2910 yaffs_BlockInfo **blockUsedPtr)
2913 yaffs_BlockInfo *bi;
2915 if (dev->allocationBlock < 0) {
2916 /* Get next block to allocate off */
2917 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2918 dev->allocationPage = 0;
2921 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2922 /* Not enough space to allocate unless we're allowed to use the reserve. */
2926 if (dev->nErasedBlocks < dev->nReservedBlocks
2927 && dev->allocationPage == 0) {
2928 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2931 /* Next page please.... */
2932 if (dev->allocationBlock >= 0) {
2933 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2935 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2936 dev->allocationPage;
2938 yaffs_SetChunkBit(dev, dev->allocationBlock,
2939 dev->allocationPage);
2941 dev->allocationPage++;
2945 /* If the block is full set the state to full */
2946 if (dev->allocationPage >= dev->nChunksPerBlock) {
2947 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2948 dev->allocationBlock = -1;
2957 T(YAFFS_TRACE_ERROR,
2958 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2963 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2967 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2969 if (dev->allocationBlock > 0) {
2970 n += (dev->nChunksPerBlock - dev->allocationPage);
2977 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2983 int retVal = YAFFS_OK;
2986 int isCheckpointBlock;
2990 int chunksBefore = yaffs_GetErasedChunks(dev);
2993 yaffs_ExtendedTags tags;
2995 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2997 yaffs_Object *object;
2999 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3001 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3003 T(YAFFS_TRACE_TRACING,
3004 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3007 bi->hasShrinkHeader,
3010 /*yaffs_VerifyFreeChunks(dev); */
3012 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3014 /* Take off the number of soft deleted entries because
3015 * they're going to get really deleted during GC.
3017 dev->nFreeChunks -= bi->softDeletions;
3021 if (isCheckpointBlock ||
3022 !yaffs_StillSomeChunkBits(dev, block)) {
3023 T(YAFFS_TRACE_TRACING,
3025 ("Collecting block %d that has no chunks in use" TENDSTR),
3027 yaffs_BlockBecameDirty(dev, block);
3030 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3032 yaffs_VerifyBlock(dev, bi, block);
3034 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3035 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3037 for (/* init already done */;
3038 retVal == YAFFS_OK &&
3039 dev->gcChunk < dev->nChunksPerBlock &&
3040 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3042 dev->gcChunk++, oldChunk++) {
3043 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3045 /* This page is in use and might need to be copied off */
3051 yaffs_InitialiseTags(&tags);
3053 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3057 yaffs_FindObjectByNumber(dev,
3060 T(YAFFS_TRACE_GC_DETAIL,
3062 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3063 dev->gcChunk, tags.objectId, tags.chunkId,
3066 if (object && !yaffs_SkipVerification(dev)) {
3067 if (tags.chunkId == 0)
3068 matchingChunk = object->hdrChunk;
3069 else if (object->softDeleted)
3070 matchingChunk = oldChunk; /* Defeat the test */
3072 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3074 if (oldChunk != matchingChunk)
3075 T(YAFFS_TRACE_ERROR,
3076 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3077 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3082 T(YAFFS_TRACE_ERROR,
3084 ("page %d in gc has no object: %d %d %d "
3086 tags.objectId, tags.chunkId, tags.byteCount));
3091 object->softDeleted &&
3092 tags.chunkId != 0) {
3093 /* Data chunk in a soft deleted file, throw it away
3094 * It's a soft deleted data chunk,
3095 * No need to copy this, just forget about it and
3096 * fix up the object.
3099 object->nDataChunks--;
3101 if (object->nDataChunks <= 0) {
3102 /* remeber to clean up the object */
3103 dev->gcCleanupList[cleanups] =
3109 /* Todo object && object->deleted && object->nDataChunks == 0 */
3110 /* Deleted object header with no data chunks.
3111 * Can be discarded and the file deleted.
3113 object->hdrChunk = 0;
3114 yaffs_FreeTnode(object->myDev,
3117 object->variant.fileVariant.top = NULL;
3118 yaffs_DoGenericObjectDeletion(object);
3120 } else if (object) {
3121 /* It's either a data chunk in a live file or
3122 * an ObjectHeader, so we're interested in it.
3123 * NB Need to keep the ObjectHeaders of deleted files
3124 * until the whole file has been deleted off
3126 tags.serialNumber++;
3130 if (tags.chunkId == 0) {
3131 /* It is an object Id,
3132 * We need to nuke the shrinkheader flags first
3133 * We no longer want the shrinkHeader flag since its work is done
3134 * and if it is left in place it will mess up scanning.
3137 yaffs_ObjectHeader *oh;
3138 oh = (yaffs_ObjectHeader *)buffer;
3140 tags.extraIsShrinkHeader = 0;
3142 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3146 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3149 retVal = YAFFS_FAIL;
3152 /* Ok, now fix up the Tnodes etc. */
3154 if (tags.chunkId == 0) {
3156 object->hdrChunk = newChunk;
3157 object->serial = tags.serialNumber;
3159 /* It's a data chunk */
3160 yaffs_PutChunkIntoFile
3168 if (retVal == YAFFS_OK)
3169 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3174 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3177 /* Do any required cleanups */
3178 for (i = 0; i < cleanups; i++) {
3179 /* Time to delete the file too */
3181 yaffs_FindObjectByNumber(dev,
3182 dev->gcCleanupList[i]);
3184 yaffs_FreeTnode(dev,
3185 object->variant.fileVariant.
3187 object->variant.fileVariant.top = NULL;
3190 ("yaffs: About to finally delete object %d"
3191 TENDSTR), object->objectId));
3192 yaffs_DoGenericObjectDeletion(object);
3193 object->myDev->nDeletedFiles--;
3200 yaffs_VerifyCollectedBlock(dev, bi, block);
3202 chunksAfter = yaffs_GetErasedChunks(dev);
3203 if (chunksBefore >= chunksAfter) {
3206 ("gc did not increase free chunks before %d after %d"
3207 TENDSTR), chunksBefore, chunksAfter));
3210 /* If the gc completed then clear the current gcBlock so that we find another. */
3211 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3221 /* New garbage collector
3222 * If we're very low on erased blocks then we do aggressive garbage collection
3223 * otherwise we do "leasurely" garbage collection.
3224 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3225 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3227 * The idea is to help clear out space in a more spread-out manner.
3228 * Dunno if it really does anything useful.
3230 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3234 int gcOk = YAFFS_OK;
3237 int checkpointBlockAdjust;
3239 if (dev->isDoingGC) {
3240 /* Bail out so we don't get recursive gc */
3244 /* This loop should pass the first time.
3245 * We'll only see looping here if the erase of the collected block fails.
3251 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3252 if (checkpointBlockAdjust < 0)
3253 checkpointBlockAdjust = 0;
3255 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3256 /* We need a block soon...*/
3259 /* We're in no hurry */
3263 if (dev->gcBlock <= 0) {
3264 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3268 block = dev->gcBlock;
3271 dev->garbageCollections++;
3273 dev->passiveGarbageCollections++;
3278 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3279 dev->nErasedBlocks, aggressive));
3281 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3284 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3287 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3288 TENDSTR), dev->nErasedBlocks, maxTries, block));
3290 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3294 return aggressive ? gcOk : YAFFS_OK;
3297 /*------------------------- TAGS --------------------------------*/
3299 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3302 return (tags->chunkId == chunkInObject &&
3303 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3308 /*-------------------- Data file manipulation -----------------*/
3310 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3311 yaffs_ExtendedTags *tags)
3313 /*Get the Tnode, then get the level 0 offset chunk offset */
3316 yaffs_ExtendedTags localTags;
3319 yaffs_Device *dev = in->myDev;
3322 /* Passed a NULL, so use our own tags space */
3326 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3329 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3332 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3338 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3339 yaffs_ExtendedTags *tags)
3341 /* Get the Tnode, then get the level 0 offset chunk offset */
3344 yaffs_ExtendedTags localTags;
3346 yaffs_Device *dev = in->myDev;
3350 /* Passed a NULL, so use our own tags space */
3354 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3358 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3361 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3364 /* Delete the entry in the filestructure (if found) */
3366 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, 0);
3369 /*T(("No level 0 found for %d\n", chunkInInode)); */
3373 /* T(("Could not find %d to delete\n",chunkInInode)); */
3378 #ifdef YAFFS_PARANOID
3380 static int yaffs_CheckFileSanity(yaffs_Object *in)
3388 yaffs_Tags localTags;
3389 yaffs_Tags *tags = &localTags;
3393 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3394 /* T(("Object not a file\n")); */
3398 objId = in->objectId;
3399 fSize = in->variant.fileVariant.fileSize;
3401 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3403 for (chunk = 1; chunk <= nChunks; chunk++) {
3404 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3409 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3411 if (yaffs_CheckChunkBits
3412 (dev, theChunk / dev->nChunksPerBlock,
3413 theChunk % dev->nChunksPerBlock)) {
3415 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3419 (tags, in->objectId, chunk, chunkDeleted)) {
3429 /* T(("No level 0 found for %d\n", chunk)); */
3433 return failed ? YAFFS_FAIL : YAFFS_OK;
3438 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3439 int chunkInNAND, int inScan)
3441 /* NB inScan is zero unless scanning.
3442 * For forward scanning, inScan is > 0;
3443 * for backward scanning inScan is < 0
3447 yaffs_Device *dev = in->myDev;
3449 yaffs_ExtendedTags existingTags;
3450 yaffs_ExtendedTags newTags;
3451 unsigned existingSerial, newSerial;
3453 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3454 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3455 * If it is not during Scanning then something went wrong!
3458 T(YAFFS_TRACE_ERROR,
3460 ("yaffs tragedy:attempt to put data chunk into a non-file"
3465 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3469 tn = yaffs_AddOrFindLevel0Tnode(dev,
3470 &in->variant.fileVariant,
3477 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3480 /* If we're scanning then we need to test for duplicates
3481 * NB This does not need to be efficient since it should only ever
3482 * happen when the power fails during a write, then only one
3483 * chunk should ever be affected.
3485 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3486 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3489 if (existingChunk > 0) {
3490 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3491 * thus we have to do a FindChunkInFile to get the real chunk id.
3493 * We have a duplicate now we need to decide which one to use:
3495 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3496 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3497 * YAFFS1: Get both sets of tags and compare serial numbers.
3501 /* Only do this for forward scanning */
3502 yaffs_ReadChunkWithTagsFromNAND(dev,
3506 /* Do a proper find */
3508 yaffs_FindChunkInFile(in, chunkInInode,
3512 if (existingChunk <= 0) {
3513 /*Hoosterman - how did this happen? */
3515 T(YAFFS_TRACE_ERROR,
3517 ("yaffs tragedy: existing chunk < 0 in scan"
3522 /* NB The deleted flags should be false, otherwise the chunks will
3523 * not be loaded during a scan
3527 newSerial = newTags.serialNumber;
3528 existingSerial = existingTags.serialNumber;
3532 (in->myDev->isYaffs2 ||
3533 existingChunk <= 0 ||
3534 ((existingSerial + 1) & 3) == newSerial)) {
3535 /* Forward scanning.
3537 * Delete the old one and drop through to update the tnode
3539 yaffs_DeleteChunk(dev, existingChunk, 1,
3542 /* Backward scanning or we want to use the existing one
3544 * Delete the new one and return early so that the tnode isn't changed
3546 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3554 if (existingChunk == 0) {
3558 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3563 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3566 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3568 if (chunkInNAND >= 0) {
3569 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3572 T(YAFFS_TRACE_NANDACCESS,
3573 (TSTR("Chunk %d not found zero instead" TENDSTR),
3575 /* get sane (zero) data if you read a hole */
3576 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3582 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3586 yaffs_ExtendedTags tags;
3587 yaffs_BlockInfo *bi;
3594 block = chunkId / dev->nChunksPerBlock;
3595 page = chunkId % dev->nChunksPerBlock;
3598 if (!yaffs_CheckChunkBit(dev, block, page))
3599 T(YAFFS_TRACE_VERIFY,
3600 (TSTR("Deleting invalid chunk %d"TENDSTR),
3603 bi = yaffs_GetBlockInfo(dev, block);
3605 T(YAFFS_TRACE_DELETION,
3606 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3609 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3611 yaffs_InitialiseTags(&tags);
3613 tags.chunkDeleted = 1;
3615 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3616 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3618 dev->nUnmarkedDeletions++;
3621 /* Pull out of the management area.
3622 * If the whole block became dirty, this will kick off an erasure.
3624 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3625 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3626 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3627 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3630 yaffs_ClearChunkBit(dev, block, page);
3634 if (bi->pagesInUse == 0 &&
3635 !bi->hasShrinkHeader &&
3636 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3637 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3638 yaffs_BlockBecameDirty(dev, block);
3642 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3647 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3648 const __u8 *buffer, int nBytes,
3651 /* Find old chunk Need to do this to get serial number
3652 * Write new one and patch into tree.
3653 * Invalidate old tags.
3657 yaffs_ExtendedTags prevTags;
3660 yaffs_ExtendedTags newTags;
3662 yaffs_Device *dev = in->myDev;
3664 yaffs_CheckGarbageCollection(dev);
3666 /* Get the previous chunk at this location in the file if it exists */
3667 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3669 /* Set up new tags */
3670 yaffs_InitialiseTags(&newTags);
3672 newTags.chunkId = chunkInInode;
3673 newTags.objectId = in->objectId;
3674 newTags.serialNumber =
3675 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3676 newTags.byteCount = nBytes;
3678 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3679 T(YAFFS_TRACE_ERROR,
3680 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3685 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3688 if (newChunkId >= 0) {
3689 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3691 if (prevChunkId >= 0) {
3692 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3696 yaffs_CheckFileSanity(in);
3702 /* UpdateObjectHeader updates the header on NAND for an object.
3703 * If name is not NULL, then that new name is used.
3705 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3706 int isShrink, int shadows)
3709 yaffs_BlockInfo *bi;
3711 yaffs_Device *dev = in->myDev;
3718 yaffs_ExtendedTags newTags;
3719 yaffs_ExtendedTags oldTags;
3721 __u8 *buffer = NULL;
3722 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3724 yaffs_ObjectHeader *oh = NULL;
3726 yaffs_strcpy(oldName, _Y("silly old name"));
3730 in == dev->rootDir || /* The rootDir should also be saved */
3733 yaffs_CheckGarbageCollection(dev);
3734 yaffs_CheckObjectDetailsLoaded(in);
3736 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3737 oh = (yaffs_ObjectHeader *) buffer;
3739 prevChunkId = in->hdrChunk;
3741 if (prevChunkId > 0) {
3742 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3745 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3747 memcpy(oldName, oh->name, sizeof(oh->name));
3750 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3752 oh->type = in->variantType;
3753 oh->yst_mode = in->yst_mode;
3754 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3756 #ifdef CONFIG_YAFFS_WINCE
3757 oh->win_atime[0] = in->win_atime[0];
3758 oh->win_ctime[0] = in->win_ctime[0];
3759 oh->win_mtime[0] = in->win_mtime[0];
3760 oh->win_atime[1] = in->win_atime[1];
3761 oh->win_ctime[1] = in->win_ctime[1];
3762 oh->win_mtime[1] = in->win_mtime[1];
3764 oh->yst_uid = in->yst_uid;
3765 oh->yst_gid = in->yst_gid;
3766 oh->yst_atime = in->yst_atime;
3767 oh->yst_mtime = in->yst_mtime;
3768 oh->yst_ctime = in->yst_ctime;
3769 oh->yst_rdev = in->yst_rdev;
3772 oh->parentObjectId = in->parent->objectId;
3774 oh->parentObjectId = 0;
3777 if (name && *name) {
3778 memset(oh->name, 0, sizeof(oh->name));
3779 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3780 } else if (prevChunkId >= 0) {
3781 memcpy(oh->name, oldName, sizeof(oh->name));
3783 memset(oh->name, 0, sizeof(oh->name));
3786 oh->isShrink = isShrink;
3788 switch (in->variantType) {
3789 case YAFFS_OBJECT_TYPE_UNKNOWN:
3790 /* Should not happen */
3792 case YAFFS_OBJECT_TYPE_FILE:
3794 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3795 || oh->parentObjectId ==
3796 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3797 fileVariant.fileSize;
3799 case YAFFS_OBJECT_TYPE_HARDLINK:
3800 oh->equivalentObjectId =
3801 in->variant.hardLinkVariant.equivalentObjectId;
3803 case YAFFS_OBJECT_TYPE_SPECIAL:
3806 case YAFFS_OBJECT_TYPE_DIRECTORY:
3809 case YAFFS_OBJECT_TYPE_SYMLINK:
3810 yaffs_strncpy(oh->alias,
3811 in->variant.symLinkVariant.alias,
3812 YAFFS_MAX_ALIAS_LENGTH);
3813 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3818 yaffs_InitialiseTags(&newTags);
3820 newTags.chunkId = 0;
3821 newTags.objectId = in->objectId;
3822 newTags.serialNumber = in->serial;
3824 /* Add extra info for file header */
3826 newTags.extraHeaderInfoAvailable = 1;
3827 newTags.extraParentObjectId = oh->parentObjectId;
3828 newTags.extraFileLength = oh->fileSize;
3829 newTags.extraIsShrinkHeader = oh->isShrink;
3830 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3831 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3832 newTags.extraObjectType = in->variantType;
3834 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3836 /* Create new chunk in NAND */
3838 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3839 (prevChunkId >= 0) ? 1 : 0);
3841 if (newChunkId >= 0) {
3843 in->hdrChunk = newChunkId;
3845 if (prevChunkId >= 0) {
3846 yaffs_DeleteChunk(dev, prevChunkId, 1,
3850 if (!yaffs_ObjectHasCachedWriteData(in))
3853 /* If this was a shrink, then mark the block that the chunk lives on */
3855 bi = yaffs_GetBlockInfo(in->myDev,
3856 newChunkId / in->myDev->nChunksPerBlock);
3857 bi->hasShrinkHeader = 1;
3862 retVal = newChunkId;
3867 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3872 /*------------------------ Short Operations Cache ----------------------------------------
3873 * In many situations where there is no high level buffering (eg WinCE) a lot of
3874 * reads might be short sequential reads, and a lot of writes may be short
3875 * sequential writes. eg. scanning/writing a jpeg file.
3876 * In these cases, a short read/write cache can provide a huge perfomance benefit
3877 * with dumb-as-a-rock code.
3878 * In Linux, the page cache provides read buffering aand the short op cache provides write
3881 * There are a limited number (~10) of cache chunks per device so that we don't
3882 * need a very intelligent search.
3885 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3887 yaffs_Device *dev = obj->myDev;
3889 yaffs_ChunkCache *cache;
3890 int nCaches = obj->myDev->nShortOpCaches;
3892 for (i = 0; i < nCaches; i++) {
3893 cache = &dev->srCache[i];
3894 if (cache->object == obj &&
3903 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3905 yaffs_Device *dev = obj->myDev;
3906 int lowest = -99; /* Stop compiler whining. */
3908 yaffs_ChunkCache *cache;
3909 int chunkWritten = 0;
3910 int nCaches = obj->myDev->nShortOpCaches;
3916 /* Find the dirty cache for this object with the lowest chunk id. */
3917 for (i = 0; i < nCaches; i++) {
3918 if (dev->srCache[i].object == obj &&
3919 dev->srCache[i].dirty) {
3921 || dev->srCache[i].chunkId <
3923 cache = &dev->srCache[i];
3924 lowest = cache->chunkId;
3929 if (cache && !cache->locked) {
3930 /* Write it out and free it up */
3933 yaffs_WriteChunkDataToObject(cache->object,
3939 cache->object = NULL;
3942 } while (cache && chunkWritten > 0);
3945 /* Hoosterman, disk full while writing cache out. */
3946 T(YAFFS_TRACE_ERROR,
3947 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3954 /*yaffs_FlushEntireDeviceCache(dev)
3959 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3962 int nCaches = dev->nShortOpCaches;
3965 /* Find a dirty object in the cache and flush it...
3966 * until there are no further dirty objects.
3970 for (i = 0; i < nCaches && !obj; i++) {
3971 if (dev->srCache[i].object &&
3972 dev->srCache[i].dirty)
3973 obj = dev->srCache[i].object;
3977 yaffs_FlushFilesChunkCache(obj);
3984 /* Grab us a cache chunk for use.
3985 * First look for an empty one.
3986 * Then look for the least recently used non-dirty one.
3987 * Then look for the least recently used dirty one...., flush and look again.
3989 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3993 if (dev->nShortOpCaches > 0) {
3994 for (i = 0; i < dev->nShortOpCaches; i++) {
3995 if (!dev->srCache[i].object)
3996 return &dev->srCache[i];
4003 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4005 yaffs_ChunkCache *cache;
4006 yaffs_Object *theObj;
4011 if (dev->nShortOpCaches > 0) {
4012 /* Try find a non-dirty one... */
4014 cache = yaffs_GrabChunkCacheWorker(dev);
4017 /* They were all dirty, find the last recently used object and flush
4018 * its cache, then find again.
4019 * NB what's here is not very accurate, we actually flush the object
4020 * the last recently used page.
4023 /* With locking we can't assume we can use entry zero */
4030 for (i = 0; i < dev->nShortOpCaches; i++) {
4031 if (dev->srCache[i].object &&
4032 !dev->srCache[i].locked &&
4033 (dev->srCache[i].lastUse < usage || !cache)) {
4034 usage = dev->srCache[i].lastUse;
4035 theObj = dev->srCache[i].object;
4036 cache = &dev->srCache[i];
4041 if (!cache || cache->dirty) {
4042 /* Flush and try again */
4043 yaffs_FlushFilesChunkCache(theObj);
4044 cache = yaffs_GrabChunkCacheWorker(dev);
4054 /* Find a cached chunk */
4055 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4058 yaffs_Device *dev = obj->myDev;
4060 if (dev->nShortOpCaches > 0) {
4061 for (i = 0; i < dev->nShortOpCaches; i++) {
4062 if (dev->srCache[i].object == obj &&
4063 dev->srCache[i].chunkId == chunkId) {
4066 return &dev->srCache[i];
4073 /* Mark the chunk for the least recently used algorithym */
4074 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4078 if (dev->nShortOpCaches > 0) {
4079 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4080 /* Reset the cache usages */
4082 for (i = 1; i < dev->nShortOpCaches; i++) {
4083 dev->srCache[i].lastUse = 0;
4090 cache->lastUse = dev->srLastUse;
4098 /* Invalidate a single cache page.
4099 * Do this when a whole page gets written,
4100 * ie the short cache for this page is no longer valid.
4102 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4104 if (object->myDev->nShortOpCaches > 0) {
4105 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4108 cache->object = NULL;
4113 /* Invalidate all the cache pages associated with this object
4114 * Do this whenever ther file is deleted or resized.
4116 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4119 yaffs_Device *dev = in->myDev;
4121 if (dev->nShortOpCaches > 0) {
4122 /* Invalidate it. */
4123 for (i = 0; i < dev->nShortOpCaches; i++) {
4124 if (dev->srCache[i].object == in) {
4125 dev->srCache[i].object = NULL;
4131 /*--------------------- Checkpointing --------------------*/
4134 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4136 yaffs_CheckpointValidity cp;
4138 memset(&cp, 0, sizeof(cp));
4140 cp.structType = sizeof(cp);
4141 cp.magic = YAFFS_MAGIC;
4142 cp.version = YAFFS_CHECKPOINT_VERSION;
4143 cp.head = (head) ? 1 : 0;
4145 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4149 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4151 yaffs_CheckpointValidity cp;
4154 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4157 ok = (cp.structType == sizeof(cp)) &&
4158 (cp.magic == YAFFS_MAGIC) &&
4159 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4160 (cp.head == ((head) ? 1 : 0));
4164 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4167 cp->nErasedBlocks = dev->nErasedBlocks;
4168 cp->allocationBlock = dev->allocationBlock;
4169 cp->allocationPage = dev->allocationPage;
4170 cp->nFreeChunks = dev->nFreeChunks;
4172 cp->nDeletedFiles = dev->nDeletedFiles;
4173 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4174 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4175 cp->sequenceNumber = dev->sequenceNumber;
4176 cp->oldestDirtySequence = dev->oldestDirtySequence;
4180 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4181 yaffs_CheckpointDevice *cp)
4183 dev->nErasedBlocks = cp->nErasedBlocks;
4184 dev->allocationBlock = cp->allocationBlock;
4185 dev->allocationPage = cp->allocationPage;
4186 dev->nFreeChunks = cp->nFreeChunks;
4188 dev->nDeletedFiles = cp->nDeletedFiles;
4189 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4190 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4191 dev->sequenceNumber = cp->sequenceNumber;
4192 dev->oldestDirtySequence = cp->oldestDirtySequence;
4196 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4198 yaffs_CheckpointDevice cp;
4200 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4204 /* Write device runtime values*/
4205 yaffs_DeviceToCheckpointDevice(&cp, dev);
4206 cp.structType = sizeof(cp);
4208 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4210 /* Write block info */
4212 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4213 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4216 /* Write chunk bits */
4218 nBytes = nBlocks * dev->chunkBitmapStride;
4219 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4225 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4227 yaffs_CheckpointDevice cp;
4229 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4233 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4237 if (cp.structType != sizeof(cp))
4241 yaffs_CheckpointDeviceToDevice(dev, &cp);
4243 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4245 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4249 nBytes = nBlocks * dev->chunkBitmapStride;
4251 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4256 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4260 cp->objectId = obj->objectId;
4261 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4262 cp->hdrChunk = obj->hdrChunk;
4263 cp->variantType = obj->variantType;
4264 cp->deleted = obj->deleted;
4265 cp->softDeleted = obj->softDeleted;
4266 cp->unlinked = obj->unlinked;
4267 cp->fake = obj->fake;
4268 cp->renameAllowed = obj->renameAllowed;
4269 cp->unlinkAllowed = obj->unlinkAllowed;
4270 cp->serial = obj->serial;
4271 cp->nDataChunks = obj->nDataChunks;
4273 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4274 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4275 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4276 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4279 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4282 yaffs_Object *parent;
4284 if (obj->variantType != cp->variantType) {
4285 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4286 TCONT("chunk %d does not match existing object type %d")
4287 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4292 obj->objectId = cp->objectId;
4295 parent = yaffs_FindOrCreateObjectByNumber(
4298 YAFFS_OBJECT_TYPE_DIRECTORY);
4303 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4304 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4305 TCONT(" chunk %d Parent type, %d, not directory")
4307 cp->objectId, cp->parentId, cp->variantType,
4308 cp->hdrChunk, parent->variantType));
4311 yaffs_AddObjectToDirectory(parent, obj);
4314 obj->hdrChunk = cp->hdrChunk;
4315 obj->variantType = cp->variantType;
4316 obj->deleted = cp->deleted;
4317 obj->softDeleted = cp->softDeleted;
4318 obj->unlinked = cp->unlinked;
4319 obj->fake = cp->fake;
4320 obj->renameAllowed = cp->renameAllowed;
4321 obj->unlinkAllowed = cp->unlinkAllowed;
4322 obj->serial = cp->serial;
4323 obj->nDataChunks = cp->nDataChunks;
4325 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4326 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4327 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4328 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4330 if (obj->hdrChunk > 0)
4331 obj->lazyLoaded = 1;
4337 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4338 __u32 level, int chunkOffset)
4341 yaffs_Device *dev = in->myDev;
4343 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4345 if (tnodeSize < sizeof(yaffs_Tnode))
4346 tnodeSize = sizeof(yaffs_Tnode);
4352 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4353 if (tn->internal[i]) {
4354 ok = yaffs_CheckpointTnodeWorker(in,
4357 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4360 } else if (level == 0) {
4361 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4362 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4364 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4372 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4374 __u32 endMarker = ~0;
4377 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4378 ok = yaffs_CheckpointTnodeWorker(obj,
4379 obj->variant.fileVariant.top,
4380 obj->variant.fileVariant.topLevel,
4383 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4390 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4394 yaffs_Device *dev = obj->myDev;
4395 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4398 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4400 if (tnodeSize < sizeof(yaffs_Tnode))
4401 tnodeSize = sizeof(yaffs_Tnode);
4403 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4405 while (ok && (~baseChunk)) {
4407 /* Read level 0 tnode */
4410 tn = yaffs_GetTnodeRaw(dev);
4412 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4417 ok = yaffs_AddOrFindLevel0Tnode(dev,
4423 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4427 T(YAFFS_TRACE_CHECKPOINT, (
4428 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4429 nread, baseChunk, ok));
4435 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4438 yaffs_CheckpointObject cp;
4441 struct ylist_head *lh;
4444 /* Iterate through the objects in each hash entry,
4445 * dumping them to the checkpointing stream.
4448 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4449 ylist_for_each(lh, &dev->objectBucket[i].list) {
4451 obj = ylist_entry(lh, yaffs_Object, hashLink);
4452 if (!obj->deferedFree) {
4453 yaffs_ObjectToCheckpointObject(&cp, obj);
4454 cp.structType = sizeof(cp);
4456 T(YAFFS_TRACE_CHECKPOINT, (
4457 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4458 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, (unsigned) obj));
4460 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4462 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4463 ok = yaffs_WriteCheckpointTnodes(obj);
4470 /* Dump end of list */
4471 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4472 cp.structType = sizeof(cp);
4475 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4480 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4483 yaffs_CheckpointObject cp;
4486 yaffs_Object *hardList = NULL;
4488 while (ok && !done) {
4489 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4490 if (cp.structType != sizeof(cp)) {
4491 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4492 cp.structType, sizeof(cp), ok));
4496 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4497 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4499 if (ok && cp.objectId == ~0)
4502 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4504 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4507 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4508 ok = yaffs_ReadCheckpointTnodes(obj);
4509 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4510 obj->hardLinks.next =
4511 (struct ylist_head *) hardList;
4520 yaffs_HardlinkFixup(dev, hardList);
4525 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4527 __u32 checkpointSum;
4530 yaffs_GetCheckpointSum(dev, &checkpointSum);
4532 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4540 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4542 __u32 checkpointSum0;
4543 __u32 checkpointSum1;
4546 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4548 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4553 if (checkpointSum0 != checkpointSum1)
4560 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4564 if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4565 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4570 ok = yaffs_CheckpointOpen(dev, 1);
4573 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4574 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4577 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4578 ok = yaffs_WriteCheckpointDevice(dev);
4581 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4582 ok = yaffs_WriteCheckpointObjects(dev);
4585 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4586 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4590 ok = yaffs_WriteCheckpointSum(dev);
4594 if (!yaffs_CheckpointClose(dev))
4598 dev->isCheckpointed = 1;
4600 dev->isCheckpointed = 0;
4602 return dev->isCheckpointed;
4605 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4609 if (dev->skipCheckpointRead || !dev->isYaffs2) {
4610 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4615 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4618 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4619 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4622 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4623 ok = yaffs_ReadCheckpointDevice(dev);
4626 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4627 ok = yaffs_ReadCheckpointObjects(dev);
4630 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4631 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4635 ok = yaffs_ReadCheckpointSum(dev);
4636 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4639 if (!yaffs_CheckpointClose(dev))
4643 dev->isCheckpointed = 1;
4645 dev->isCheckpointed = 0;
4651 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4653 if (dev->isCheckpointed ||
4654 dev->blocksInCheckpoint > 0) {
4655 dev->isCheckpointed = 0;
4656 yaffs_CheckpointInvalidateStream(dev);
4657 if (dev->superBlock && dev->markSuperBlockDirty)
4658 dev->markSuperBlockDirty(dev->superBlock);
4663 int yaffs_CheckpointSave(yaffs_Device *dev)
4666 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4668 yaffs_VerifyObjects(dev);
4669 yaffs_VerifyBlocks(dev);
4670 yaffs_VerifyFreeChunks(dev);
4672 if (!dev->isCheckpointed) {
4673 yaffs_InvalidateCheckpoint(dev);
4674 yaffs_WriteCheckpointData(dev);
4677 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4679 return dev->isCheckpointed;
4682 int yaffs_CheckpointRestore(yaffs_Device *dev)
4685 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4687 retval = yaffs_ReadCheckpointData(dev);
4689 if (dev->isCheckpointed) {
4690 yaffs_VerifyObjects(dev);
4691 yaffs_VerifyBlocks(dev);
4692 yaffs_VerifyFreeChunks(dev);
4695 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4700 /*--------------------- File read/write ------------------------
4701 * Read and write have very similar structures.
4702 * In general the read/write has three parts to it
4703 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4704 * Some complete chunks
4705 * An incomplete chunk to end off with
4707 * Curve-balls: the first chunk might also be the last chunk.
4710 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4719 yaffs_ChunkCache *cache;
4726 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4727 /* start = offset % dev->nDataBytesPerChunk; */
4728 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4731 /* OK now check for the curveball where the start and end are in
4734 if ((start + n) < dev->nDataBytesPerChunk) {
4737 nToCopy = dev->nDataBytesPerChunk - start;
4740 cache = yaffs_FindChunkCache(in, chunk);
4742 /* If the chunk is already in the cache or it is less than a whole chunk
4743 * or we're using inband tags then use the cache (if there is caching)
4744 * else bypass the cache.
4746 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4747 if (dev->nShortOpCaches > 0) {
4749 /* If we can't find the data in the cache, then load it up. */
4752 cache = yaffs_GrabChunkCache(in->myDev);
4754 cache->chunkId = chunk;
4757 yaffs_ReadChunkDataFromObject(in, chunk,
4763 yaffs_UseChunkCache(dev, cache, 0);
4768 memcpy(buffer, &cache->data[start], nToCopy);
4772 /* Read into the local buffer then copy..*/
4775 yaffs_GetTempBuffer(dev, __LINE__);
4776 yaffs_ReadChunkDataFromObject(in, chunk,
4779 memcpy(buffer, &localBuffer[start], nToCopy);
4782 yaffs_ReleaseTempBuffer(dev, localBuffer,
4788 /* A full chunk. Read directly into the supplied buffer. */
4789 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4803 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4804 int nBytes, int writeThrough)
4813 int startOfWrite = offset;
4814 int chunkWritten = 0;
4822 while (n > 0 && chunkWritten >= 0) {
4823 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4824 /* start = offset % dev->nDataBytesPerChunk; */
4825 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4827 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4828 start >= dev->nDataBytesPerChunk) {
4829 T(YAFFS_TRACE_ERROR, (
4830 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4832 (int)offset, chunk, start));
4836 /* OK now check for the curveball where the start and end are in
4840 if ((start + n) < dev->nDataBytesPerChunk) {
4843 /* Now folks, to calculate how many bytes to write back....
4844 * If we're overwriting and not writing to then end of file then
4845 * we need to write back as much as was there before.
4848 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4850 if (chunkStart > in->variant.fileVariant.fileSize)
4851 nBytesRead = 0; /* Past end of file */
4853 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4855 if (nBytesRead > dev->nDataBytesPerChunk) {
4856 nBytesRead = dev->nDataBytesPerChunk;
4861 (start + n)) ? nBytesRead : (start + n);
4863 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4867 nToCopy = dev->nDataBytesPerChunk - start;
4868 nToWriteBack = dev->nDataBytesPerChunk;
4871 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4872 /* An incomplete start or end chunk (or maybe both start and end chunk),
4873 * or we're using inband tags, so we want to use the cache buffers.
4875 if (dev->nShortOpCaches > 0) {
4876 yaffs_ChunkCache *cache;
4877 /* If we can't find the data in the cache, then load the cache */
4878 cache = yaffs_FindChunkCache(in, chunk);
4881 && yaffs_CheckSpaceForAllocation(in->
4883 cache = yaffs_GrabChunkCache(in->myDev);
4885 cache->chunkId = chunk;
4888 yaffs_ReadChunkDataFromObject(in, chunk,
4893 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4894 /* Drop the cache if it was a read cache item and
4895 * no space check has been made for it.
4901 yaffs_UseChunkCache(dev, cache, 1);
4905 memcpy(&cache->data[start], buffer,
4910 cache->nBytes = nToWriteBack;
4914 yaffs_WriteChunkDataToObject
4917 cache->data, cache->nBytes,
4923 chunkWritten = -1; /* fail the write */
4926 /* An incomplete start or end chunk (or maybe both start and end chunk)
4927 * Read into the local buffer then copy, then copy over and write back.
4931 yaffs_GetTempBuffer(dev, __LINE__);
4933 yaffs_ReadChunkDataFromObject(in, chunk,
4938 memcpy(&localBuffer[start], buffer, nToCopy);
4941 yaffs_WriteChunkDataToObject(in, chunk,
4946 yaffs_ReleaseTempBuffer(dev, localBuffer,
4952 /* A full chunk. Write directly from the supplied buffer. */
4957 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4958 dev->nDataBytesPerChunk,
4961 /* Since we've overwritten the cached data, we better invalidate it. */
4962 yaffs_InvalidateChunkCache(in, chunk);
4965 if (chunkWritten >= 0) {
4974 /* Update file object */
4976 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4977 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4986 /* ---------------------- File resizing stuff ------------------ */
4988 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4991 yaffs_Device *dev = in->myDev;
4992 int oldFileSize = in->variant.fileVariant.fileSize;
4994 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4996 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4997 dev->nDataBytesPerChunk;
5001 /* Delete backwards so that we don't end up with holes if
5002 * power is lost part-way through the operation.
5004 for (i = lastDel; i >= startDel; i--) {
5005 /* NB this could be optimised somewhat,
5006 * eg. could retrieve the tags and write them without
5007 * using yaffs_DeleteChunk
5010 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5013 (dev->internalStartBlock * dev->nChunksPerBlock)
5015 ((dev->internalEndBlock +
5016 1) * dev->nChunksPerBlock)) {
5017 T(YAFFS_TRACE_ALWAYS,
5018 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5022 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5029 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5032 int oldFileSize = in->variant.fileVariant.fileSize;
5033 __u32 newSizeOfPartialChunk;
5036 yaffs_Device *dev = in->myDev;
5038 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5040 yaffs_FlushFilesChunkCache(in);
5041 yaffs_InvalidateWholeChunkCache(in);
5043 yaffs_CheckGarbageCollection(dev);
5045 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5049 if (newSize == oldFileSize) {
5053 if (newSize < oldFileSize) {
5055 yaffs_PruneResizedChunks(in, newSize);
5057 if (newSizeOfPartialChunk != 0) {
5058 int lastChunk = 1 + newFullChunks;
5060 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5062 /* Got to read and rewrite the last chunk with its new size and zero pad */
5063 yaffs_ReadChunkDataFromObject(in, lastChunk,
5066 memset(localBuffer + newSizeOfPartialChunk, 0,
5067 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5069 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5070 newSizeOfPartialChunk, 1);
5072 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5075 in->variant.fileVariant.fileSize = newSize;
5077 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5079 /* newsSize > oldFileSize */
5080 in->variant.fileVariant.fileSize = newSize;
5084 /* Write a new object header.
5085 * show we've shrunk the file, if need be
5086 * Do this only if the file is not in the deleted directories.
5089 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5090 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5091 yaffs_UpdateObjectHeader(in, NULL, 0,
5092 (newSize < oldFileSize) ? 1 : 0, 0);
5098 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5100 obj = yaffs_GetEquivalentObject(obj);
5102 switch (obj->variantType) {
5103 case YAFFS_OBJECT_TYPE_FILE:
5104 return obj->variant.fileVariant.fileSize;
5105 case YAFFS_OBJECT_TYPE_SYMLINK:
5106 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5114 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
5118 yaffs_FlushFilesChunkCache(in);
5120 #ifdef CONFIG_YAFFS_WINCE
5121 yfsd_WinFileTimeNow(in->win_mtime);
5124 in->yst_mtime = Y_CURRENT_TIME;
5129 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5130 0) ? YAFFS_OK : YAFFS_FAIL;
5139 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5142 /* First off, invalidate the file's data in the cache, without flushing. */
5143 yaffs_InvalidateWholeChunkCache(in);
5145 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5146 /* Move to the unlinked directory so we have a record that it was deleted. */
5147 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5151 yaffs_RemoveObjectFromDirectory(in);
5152 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5155 yaffs_FreeObject(in);
5160 /* yaffs_DeleteFile deletes the whole file data
5161 * and the inode associated with the file.
5162 * It does not delete the links associated with the file.
5164 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5168 int immediateDeletion = 0;
5172 immediateDeletion = 1;
5175 if (in->inUse <= 0) {
5176 immediateDeletion = 1;
5180 if (immediateDeletion) {
5182 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5183 _Y("deleted"), 0, 0);
5184 T(YAFFS_TRACE_TRACING,
5185 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5188 in->myDev->nDeletedFiles++;
5189 if (1 || in->myDev->isYaffs2) {
5190 yaffs_ResizeFile(in, 0);
5192 yaffs_SoftDeleteFile(in);
5195 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5196 _Y("unlinked"), 0, 0);
5203 int yaffs_DeleteFile(yaffs_Object *in)
5205 int retVal = YAFFS_OK;
5206 int deleted = in->deleted;
5208 yaffs_ResizeFile(in, 0);
5210 if (in->nDataChunks > 0) {
5211 /* Use soft deletion if there is data in the file.
5212 * That won't be the case if it has been resized to zero.
5214 if (!in->unlinked) {
5215 retVal = yaffs_UnlinkFileIfNeeded(in);
5217 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5218 in->deleted = deleted = 1;
5219 in->myDev->nDeletedFiles++;
5220 yaffs_SoftDeleteFile(in);
5222 return deleted ? YAFFS_OK : YAFFS_FAIL;
5224 /* The file has no data chunks so we toss it immediately */
5225 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5226 in->variant.fileVariant.top = NULL;
5227 yaffs_DoGenericObjectDeletion(in);
5233 static int yaffs_DeleteDirectory(yaffs_Object *in)
5235 /* First check that the directory is empty. */
5236 if (ylist_empty(&in->variant.directoryVariant.children)) {
5237 return yaffs_DoGenericObjectDeletion(in);
5244 static int yaffs_DeleteSymLink(yaffs_Object *in)
5246 YFREE(in->variant.symLinkVariant.alias);
5248 return yaffs_DoGenericObjectDeletion(in);
5251 static int yaffs_DeleteHardLink(yaffs_Object *in)
5253 /* remove this hardlink from the list assocaited with the equivalent
5256 ylist_del_init(&in->hardLinks);
5257 return yaffs_DoGenericObjectDeletion(in);
5260 int yaffs_DeleteObject(yaffs_Object *obj)
5263 switch (obj->variantType) {
5264 case YAFFS_OBJECT_TYPE_FILE:
5265 retVal = yaffs_DeleteFile(obj);
5267 case YAFFS_OBJECT_TYPE_DIRECTORY:
5268 return yaffs_DeleteDirectory(obj);
5270 case YAFFS_OBJECT_TYPE_SYMLINK:
5271 retVal = yaffs_DeleteSymLink(obj);
5273 case YAFFS_OBJECT_TYPE_HARDLINK:
5274 retVal = yaffs_DeleteHardLink(obj);
5276 case YAFFS_OBJECT_TYPE_SPECIAL:
5277 retVal = yaffs_DoGenericObjectDeletion(obj);
5279 case YAFFS_OBJECT_TYPE_UNKNOWN:
5281 break; /* should not happen. */
5287 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5290 int immediateDeletion = 0;
5293 if (!obj->myInode) {
5294 immediateDeletion = 1;
5297 if (obj->inUse <= 0) {
5298 immediateDeletion = 1;
5302 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5303 return yaffs_DeleteHardLink(obj);
5304 } else if (!ylist_empty(&obj->hardLinks)) {
5305 /* Curve ball: We're unlinking an object that has a hardlink.
5307 * This problem arises because we are not strictly following
5308 * The Linux link/inode model.
5310 * We can't really delete the object.
5311 * Instead, we do the following:
5312 * - Select a hardlink.
5313 * - Unhook it from the hard links
5314 * - Unhook it from its parent directory (so that the rename can work)
5315 * - Rename the object to the hardlink's name.
5316 * - Delete the hardlink
5321 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5323 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5325 ylist_del_init(&hl->hardLinks);
5326 ylist_del_init(&hl->siblings);
5328 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5330 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5332 if (retVal == YAFFS_OK) {
5333 retVal = yaffs_DoGenericObjectDeletion(hl);
5337 } else if(immediateDeletion){
5338 switch (obj->variantType) {
5339 case YAFFS_OBJECT_TYPE_FILE:
5340 return yaffs_DeleteFile(obj);
5342 case YAFFS_OBJECT_TYPE_DIRECTORY:
5343 return yaffs_DeleteDirectory(obj);
5345 case YAFFS_OBJECT_TYPE_SYMLINK:
5346 return yaffs_DeleteSymLink(obj);
5348 case YAFFS_OBJECT_TYPE_SPECIAL:
5349 return yaffs_DoGenericObjectDeletion(obj);
5351 case YAFFS_OBJECT_TYPE_HARDLINK:
5352 case YAFFS_OBJECT_TYPE_UNKNOWN:
5357 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5358 _Y("unlinked"), 0, 0);
5363 static int yaffs_UnlinkObject(yaffs_Object *obj)
5366 if (obj && obj->unlinkAllowed) {
5367 return yaffs_UnlinkWorker(obj);
5373 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5377 obj = yaffs_FindObjectByName(dir, name);
5378 return yaffs_UnlinkObject(obj);
5381 /*----------------------- Initialisation Scanning ---------------------- */
5383 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5384 int backwardScanning)
5388 if (!backwardScanning) {
5389 /* Handle YAFFS1 forward scanning case
5390 * For YAFFS1 we always do the deletion
5394 /* Handle YAFFS2 case (backward scanning)
5395 * If the shadowed object exists then ignore.
5397 if (yaffs_FindObjectByNumber(dev, objId)) {
5402 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5403 * We put it in unlinked dir to be cleaned up after the scanning
5406 yaffs_FindOrCreateObjectByNumber(dev, objId,
5407 YAFFS_OBJECT_TYPE_FILE);
5410 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5411 obj->variant.fileVariant.shrinkSize = 0;
5412 obj->valid = 1; /* So that we don't read any other info for this file */
5422 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5429 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5431 in = yaffs_FindObjectByNumber(dev,
5432 hl->variant.hardLinkVariant.
5433 equivalentObjectId);
5436 /* Add the hardlink pointers */
5437 hl->variant.hardLinkVariant.equivalentObject = in;
5438 ylist_add(&hl->hardLinks, &in->hardLinks);
5440 /* Todo Need to report/handle this better.
5441 * Got a problem... hardlink to a non-existant object
5443 hl->variant.hardLinkVariant.equivalentObject = NULL;
5444 YINIT_LIST_HEAD(&hl->hardLinks);
5454 static int ybicmp(const void *a, const void *b)
5456 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5457 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5458 register int ablock = ((yaffs_BlockIndex *)a)->block;
5459 register int bblock = ((yaffs_BlockIndex *)b)->block;
5461 return ablock - bblock;
5467 struct yaffs_ShadowFixerStruct {
5470 struct yaffs_ShadowFixerStruct *next;
5474 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5477 * Sort out state of unlinked and deleted objects after scanning.
5479 struct ylist_head *i;
5480 struct ylist_head *n;
5483 /* Soft delete all the unlinked files */
5484 ylist_for_each_safe(i, n,
5485 &dev->unlinkedDir->variant.directoryVariant.children) {
5487 l = ylist_entry(i, yaffs_Object, siblings);
5488 yaffs_DeleteObject(l);
5492 ylist_for_each_safe(i, n,
5493 &dev->deletedDir->variant.directoryVariant.children) {
5495 l = ylist_entry(i, yaffs_Object, siblings);
5496 yaffs_DeleteObject(l);
5502 static int yaffs_Scan(yaffs_Device *dev)
5504 yaffs_ExtendedTags tags;
5514 yaffs_BlockState state;
5515 yaffs_Object *hardList = NULL;
5516 yaffs_BlockInfo *bi;
5517 __u32 sequenceNumber;
5518 yaffs_ObjectHeader *oh;
5520 yaffs_Object *parent;
5522 int alloc_failed = 0;
5524 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5532 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5533 dev->internalStartBlock, dev->internalEndBlock));
5535 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5537 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5539 /* Scan all the blocks to determine their state */
5540 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5541 bi = yaffs_GetBlockInfo(dev, blk);
5542 yaffs_ClearChunkBits(dev, blk);
5544 bi->softDeletions = 0;
5546 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5548 bi->blockState = state;
5549 bi->sequenceNumber = sequenceNumber;
5551 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5552 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5554 T(YAFFS_TRACE_SCAN_DEBUG,
5555 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5556 state, sequenceNumber));
5558 if (state == YAFFS_BLOCK_STATE_DEAD) {
5559 T(YAFFS_TRACE_BAD_BLOCKS,
5560 (TSTR("block %d is bad" TENDSTR), blk));
5561 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5562 T(YAFFS_TRACE_SCAN_DEBUG,
5563 (TSTR("Block empty " TENDSTR)));
5564 dev->nErasedBlocks++;
5565 dev->nFreeChunks += dev->nChunksPerBlock;
5569 startIterator = dev->internalStartBlock;
5570 endIterator = dev->internalEndBlock;
5572 /* For each block.... */
5573 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5580 blk = blockIterator;
5582 bi = yaffs_GetBlockInfo(dev, blk);
5583 state = bi->blockState;
5587 /* For each chunk in each block that needs scanning....*/
5588 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5589 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5590 /* Read the tags and decide what to do */
5591 chunk = blk * dev->nChunksPerBlock + c;
5593 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5596 /* Let's have a good look at this chunk... */
5598 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5604 /*T((" %d %d deleted\n",blk,c)); */
5605 } else if (!tags.chunkUsed) {
5606 /* An unassigned chunk in the block
5607 * This means that either the block is empty or
5608 * this is the one being allocated from
5612 /* We're looking at the first chunk in the block so the block is unused */
5613 state = YAFFS_BLOCK_STATE_EMPTY;
5614 dev->nErasedBlocks++;
5616 /* this is the block being allocated from */
5619 (" Allocating from %d %d" TENDSTR),
5621 state = YAFFS_BLOCK_STATE_ALLOCATING;
5622 dev->allocationBlock = blk;
5623 dev->allocationPage = c;
5624 dev->allocationBlockFinder = blk;
5625 /* Set it to here to encourage the allocator to go forth from here. */
5629 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5630 } else if (tags.chunkId > 0) {
5631 /* chunkId > 0 so it is a data chunk... */
5632 unsigned int endpos;
5634 yaffs_SetChunkBit(dev, blk, c);
5637 in = yaffs_FindOrCreateObjectByNumber(dev,
5640 YAFFS_OBJECT_TYPE_FILE);
5641 /* PutChunkIntoFile checks for a clash (two data chunks with
5642 * the same chunkId).
5649 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5654 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5657 in->variantType == YAFFS_OBJECT_TYPE_FILE
5658 && in->variant.fileVariant.scannedFileSize <
5660 in->variant.fileVariant.
5661 scannedFileSize = endpos;
5662 if (!dev->useHeaderFileSize) {
5663 in->variant.fileVariant.
5665 in->variant.fileVariant.
5670 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5672 /* chunkId == 0, so it is an ObjectHeader.
5673 * Thus, we read in the object header and make the object
5675 yaffs_SetChunkBit(dev, blk, c);
5678 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5682 oh = (yaffs_ObjectHeader *) chunkData;
5684 in = yaffs_FindObjectByNumber(dev,
5686 if (in && in->variantType != oh->type) {
5687 /* This should not happen, but somehow
5688 * Wev'e ended up with an objectId that has been reused but not yet
5689 * deleted, and worse still it has changed type. Delete the old object.
5692 yaffs_DeleteObject(in);
5697 in = yaffs_FindOrCreateObjectByNumber(dev,
5705 if (in && oh->shadowsObject > 0) {
5707 struct yaffs_ShadowFixerStruct *fixer;
5708 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5710 fixer->next = shadowFixerList;
5711 shadowFixerList = fixer;
5712 fixer->objectId = tags.objectId;
5713 fixer->shadowedId = oh->shadowsObject;
5718 if (in && in->valid) {
5719 /* We have already filled this one. We have a duplicate and need to resolve it. */
5721 unsigned existingSerial = in->serial;
5722 unsigned newSerial = tags.serialNumber;
5724 if (((existingSerial + 1) & 3) == newSerial) {
5725 /* Use new one - destroy the exisiting one */
5726 yaffs_DeleteChunk(dev,
5731 /* Use existing - destroy this one. */
5732 yaffs_DeleteChunk(dev, chunk, 1,
5737 if (in && !in->valid &&
5738 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5739 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5740 /* We only load some info, don't fiddle with directory structure */
5742 in->variantType = oh->type;
5744 in->yst_mode = oh->yst_mode;
5745 #ifdef CONFIG_YAFFS_WINCE
5746 in->win_atime[0] = oh->win_atime[0];
5747 in->win_ctime[0] = oh->win_ctime[0];
5748 in->win_mtime[0] = oh->win_mtime[0];
5749 in->win_atime[1] = oh->win_atime[1];
5750 in->win_ctime[1] = oh->win_ctime[1];
5751 in->win_mtime[1] = oh->win_mtime[1];
5753 in->yst_uid = oh->yst_uid;
5754 in->yst_gid = oh->yst_gid;
5755 in->yst_atime = oh->yst_atime;
5756 in->yst_mtime = oh->yst_mtime;
5757 in->yst_ctime = oh->yst_ctime;
5758 in->yst_rdev = oh->yst_rdev;
5760 in->hdrChunk = chunk;
5761 in->serial = tags.serialNumber;
5763 } else if (in && !in->valid) {
5764 /* we need to load this info */
5767 in->variantType = oh->type;
5769 in->yst_mode = oh->yst_mode;
5770 #ifdef CONFIG_YAFFS_WINCE
5771 in->win_atime[0] = oh->win_atime[0];
5772 in->win_ctime[0] = oh->win_ctime[0];
5773 in->win_mtime[0] = oh->win_mtime[0];
5774 in->win_atime[1] = oh->win_atime[1];
5775 in->win_ctime[1] = oh->win_ctime[1];
5776 in->win_mtime[1] = oh->win_mtime[1];
5778 in->yst_uid = oh->yst_uid;
5779 in->yst_gid = oh->yst_gid;
5780 in->yst_atime = oh->yst_atime;
5781 in->yst_mtime = oh->yst_mtime;
5782 in->yst_ctime = oh->yst_ctime;
5783 in->yst_rdev = oh->yst_rdev;
5785 in->hdrChunk = chunk;
5786 in->serial = tags.serialNumber;
5788 yaffs_SetObjectName(in, oh->name);
5791 /* directory stuff...
5796 yaffs_FindOrCreateObjectByNumber
5797 (dev, oh->parentObjectId,
5798 YAFFS_OBJECT_TYPE_DIRECTORY);
5801 if (parent && parent->variantType ==
5802 YAFFS_OBJECT_TYPE_UNKNOWN) {
5803 /* Set up as a directory */
5804 parent->variantType =
5805 YAFFS_OBJECT_TYPE_DIRECTORY;
5806 YINIT_LIST_HEAD(&parent->variant.
5809 } else if (!parent || parent->variantType !=
5810 YAFFS_OBJECT_TYPE_DIRECTORY) {
5811 /* Hoosterman, another problem....
5812 * We're trying to use a non-directory as a directory
5815 T(YAFFS_TRACE_ERROR,
5817 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5819 parent = dev->lostNFoundDir;
5822 yaffs_AddObjectToDirectory(parent, in);
5824 if (0 && (parent == dev->deletedDir ||
5825 parent == dev->unlinkedDir)) {
5826 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5827 dev->nDeletedFiles++;
5829 /* Note re hardlinks.
5830 * Since we might scan a hardlink before its equivalent object is scanned
5831 * we put them all in a list.
5832 * After scanning is complete, we should have all the objects, so we run through this
5833 * list and fix up all the chains.
5836 switch (in->variantType) {
5837 case YAFFS_OBJECT_TYPE_UNKNOWN:
5838 /* Todo got a problem */
5840 case YAFFS_OBJECT_TYPE_FILE:
5841 if (dev->useHeaderFileSize)
5843 in->variant.fileVariant.
5848 case YAFFS_OBJECT_TYPE_HARDLINK:
5849 in->variant.hardLinkVariant.
5850 equivalentObjectId =
5851 oh->equivalentObjectId;
5852 in->hardLinks.next =
5853 (struct ylist_head *)
5857 case YAFFS_OBJECT_TYPE_DIRECTORY:
5860 case YAFFS_OBJECT_TYPE_SPECIAL:
5863 case YAFFS_OBJECT_TYPE_SYMLINK:
5864 in->variant.symLinkVariant.alias =
5865 yaffs_CloneString(oh->alias);
5866 if (!in->variant.symLinkVariant.alias)
5872 if (parent == dev->deletedDir) {
5873 yaffs_DestroyObject(in);
5874 bi->hasShrinkHeader = 1;
5881 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5882 /* If we got this far while scanning, then the block is fully allocated.*/
5883 state = YAFFS_BLOCK_STATE_FULL;
5886 bi->blockState = state;
5888 /* Now let's see if it was dirty */
5889 if (bi->pagesInUse == 0 &&
5890 !bi->hasShrinkHeader &&
5891 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5892 yaffs_BlockBecameDirty(dev, blk);
5898 /* Ok, we've done all the scanning.
5899 * Fix up the hard link chains.
5900 * We should now have scanned all the objects, now it's time to add these
5904 yaffs_HardlinkFixup(dev, hardList);
5906 /* Fix up any shadowed objects */
5908 struct yaffs_ShadowFixerStruct *fixer;
5911 while (shadowFixerList) {
5912 fixer = shadowFixerList;
5913 shadowFixerList = fixer->next;
5914 /* Complete the rename transaction by deleting the shadowed object
5915 * then setting the object header to unshadowed.
5917 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
5919 yaffs_DeleteObject(obj);
5921 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
5923 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5930 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5936 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5942 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5945 yaffs_ObjectHeader *oh;
5947 yaffs_ExtendedTags tags;
5949 int alloc_failed = 0;
5957 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
5959 in->lazyLoaded ? "not yet" : "already"));
5962 if (in->lazyLoaded && in->hdrChunk > 0) {
5964 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5966 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
5967 oh = (yaffs_ObjectHeader *) chunkData;
5969 in->yst_mode = oh->yst_mode;
5970 #ifdef CONFIG_YAFFS_WINCE
5971 in->win_atime[0] = oh->win_atime[0];
5972 in->win_ctime[0] = oh->win_ctime[0];
5973 in->win_mtime[0] = oh->win_mtime[0];
5974 in->win_atime[1] = oh->win_atime[1];
5975 in->win_ctime[1] = oh->win_ctime[1];
5976 in->win_mtime[1] = oh->win_mtime[1];
5978 in->yst_uid = oh->yst_uid;
5979 in->yst_gid = oh->yst_gid;
5980 in->yst_atime = oh->yst_atime;
5981 in->yst_mtime = oh->yst_mtime;
5982 in->yst_ctime = oh->yst_ctime;
5983 in->yst_rdev = oh->yst_rdev;
5986 yaffs_SetObjectName(in, oh->name);
5988 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5989 in->variant.symLinkVariant.alias =
5990 yaffs_CloneString(oh->alias);
5991 if (!in->variant.symLinkVariant.alias)
5992 alloc_failed = 1; /* Not returned to caller */
5995 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5999 static int yaffs_ScanBackwards(yaffs_Device *dev)
6001 yaffs_ExtendedTags tags;
6006 int nBlocksToScan = 0;
6012 yaffs_BlockState state;
6013 yaffs_Object *hardList = NULL;
6014 yaffs_BlockInfo *bi;
6015 __u32 sequenceNumber;
6016 yaffs_ObjectHeader *oh;
6018 yaffs_Object *parent;
6019 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6025 int foundChunksInBlock;
6026 int equivalentObjectId;
6027 int alloc_failed = 0;
6030 yaffs_BlockIndex *blockIndex = NULL;
6031 int altBlockIndex = 0;
6033 if (!dev->isYaffs2) {
6035 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6041 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6042 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6045 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6047 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6050 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6056 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6060 dev->blocksInCheckpoint = 0;
6062 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6064 /* Scan all the blocks to determine their state */
6065 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6066 bi = yaffs_GetBlockInfo(dev, blk);
6067 yaffs_ClearChunkBits(dev, blk);
6069 bi->softDeletions = 0;
6071 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6073 bi->blockState = state;
6074 bi->sequenceNumber = sequenceNumber;
6076 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6077 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6078 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6079 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6081 T(YAFFS_TRACE_SCAN_DEBUG,
6082 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6083 state, sequenceNumber));
6086 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6087 dev->blocksInCheckpoint++;
6089 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6090 T(YAFFS_TRACE_BAD_BLOCKS,
6091 (TSTR("block %d is bad" TENDSTR), blk));
6092 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6093 T(YAFFS_TRACE_SCAN_DEBUG,
6094 (TSTR("Block empty " TENDSTR)));
6095 dev->nErasedBlocks++;
6096 dev->nFreeChunks += dev->nChunksPerBlock;
6097 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6099 /* Determine the highest sequence number */
6100 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6101 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6103 blockIndex[nBlocksToScan].seq = sequenceNumber;
6104 blockIndex[nBlocksToScan].block = blk;
6108 if (sequenceNumber >= dev->sequenceNumber) {
6109 dev->sequenceNumber = sequenceNumber;
6112 /* TODO: Nasty sequence number! */
6115 ("Block scanning block %d has bad sequence number %d"
6116 TENDSTR), blk, sequenceNumber));
6123 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6129 /* Sort the blocks */
6130 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6132 /* Use qsort now. */
6133 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6137 /* Dungy old bubble sort... */
6139 yaffs_BlockIndex temp;
6143 for (i = 0; i < nBlocksToScan; i++)
6144 for (j = i + 1; j < nBlocksToScan; j++)
6145 if (blockIndex[i].seq > blockIndex[j].seq) {
6146 temp = blockIndex[j];
6147 blockIndex[j] = blockIndex[i];
6148 blockIndex[i] = temp;
6155 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6157 /* Now scan the blocks looking at the data. */
6159 endIterator = nBlocksToScan - 1;
6160 T(YAFFS_TRACE_SCAN_DEBUG,
6161 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6163 /* For each block.... backwards */
6164 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6166 /* Cooperative multitasking! This loop can run for so
6167 long that watchdog timers expire. */
6170 /* get the block to scan in the correct order */
6171 blk = blockIndex[blockIterator].block;
6173 bi = yaffs_GetBlockInfo(dev, blk);
6176 state = bi->blockState;
6180 /* For each chunk in each block that needs scanning.... */
6181 foundChunksInBlock = 0;
6182 for (c = dev->nChunksPerBlock - 1;
6183 !alloc_failed && c >= 0 &&
6184 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6185 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6186 /* Scan backwards...
6187 * Read the tags and decide what to do
6190 chunk = blk * dev->nChunksPerBlock + c;
6192 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6195 /* Let's have a good look at this chunk... */
6197 if (!tags.chunkUsed) {
6198 /* An unassigned chunk in the block.
6199 * If there are used chunks after this one, then
6200 * it is a chunk that was skipped due to failing the erased
6201 * check. Just skip it so that it can be deleted.
6202 * But, more typically, We get here when this is an unallocated
6203 * chunk and his means that either the block is empty or
6204 * this is the one being allocated from
6207 if (foundChunksInBlock) {
6208 /* This is a chunk that was skipped due to failing the erased check */
6209 } else if (c == 0) {
6210 /* We're looking at the first chunk in the block so the block is unused */
6211 state = YAFFS_BLOCK_STATE_EMPTY;
6212 dev->nErasedBlocks++;
6214 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6215 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6216 if (dev->sequenceNumber == bi->sequenceNumber) {
6217 /* this is the block being allocated from */
6221 (" Allocating from %d %d"
6224 state = YAFFS_BLOCK_STATE_ALLOCATING;
6225 dev->allocationBlock = blk;
6226 dev->allocationPage = c;
6227 dev->allocationBlockFinder = blk;
6229 /* This is a partially written block that is not
6230 * the current allocation block. This block must have
6231 * had a write failure, so set up for retirement.
6234 /* bi->needsRetiring = 1; ??? TODO */
6235 bi->gcPrioritise = 1;
6237 T(YAFFS_TRACE_ALWAYS,
6238 (TSTR("Partially written block %d detected" TENDSTR),
6246 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6248 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6253 } else if (tags.chunkId > 0) {
6254 /* chunkId > 0 so it is a data chunk... */
6255 unsigned int endpos;
6257 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6259 foundChunksInBlock = 1;
6262 yaffs_SetChunkBit(dev, blk, c);
6265 in = yaffs_FindOrCreateObjectByNumber(dev,
6268 YAFFS_OBJECT_TYPE_FILE);
6275 in->variantType == YAFFS_OBJECT_TYPE_FILE
6277 in->variant.fileVariant.shrinkSize) {
6278 /* This has not been invalidated by a resize */
6279 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6284 /* File size is calculated by looking at the data chunks if we have not
6285 * seen an object header yet. Stop this practice once we find an object header.
6289 1) * dev->nDataBytesPerChunk +
6292 if (!in->valid && /* have not got an object header yet */
6293 in->variant.fileVariant.
6294 scannedFileSize < endpos) {
6295 in->variant.fileVariant.
6296 scannedFileSize = endpos;
6297 in->variant.fileVariant.
6299 in->variant.fileVariant.
6304 /* This chunk has been invalidated by a resize, so delete */
6305 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6309 /* chunkId == 0, so it is an ObjectHeader.
6310 * Thus, we read in the object header and make the object
6312 foundChunksInBlock = 1;
6314 yaffs_SetChunkBit(dev, blk, c);
6320 if (tags.extraHeaderInfoAvailable) {
6321 in = yaffs_FindOrCreateObjectByNumber
6322 (dev, tags.objectId,
6323 tags.extraObjectType);
6329 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6332 tags.extraShadows ||
6334 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6335 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6337 /* If we don't have valid info then we need to read the chunk
6338 * TODO In future we can probably defer reading the chunk and
6339 * living with invalid data until needed.
6342 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6347 oh = (yaffs_ObjectHeader *) chunkData;
6349 if (dev->inbandTags) {
6350 /* Fix up the header if they got corrupted by inband tags */
6351 oh->shadowsObject = oh->inbandShadowsObject;
6352 oh->isShrink = oh->inbandIsShrink;
6356 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6364 /* TODO Hoosterman we have a problem! */
6365 T(YAFFS_TRACE_ERROR,
6367 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6368 TENDSTR), tags.objectId, chunk));
6373 /* We have already filled this one.
6374 * We have a duplicate that will be discarded, but
6375 * we first have to suck out resize info if it is a file.
6378 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6380 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6381 (tags.extraHeaderInfoAvailable &&
6382 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6384 (oh) ? oh->fileSize : tags.
6386 __u32 parentObjectId =
6388 parentObjectId : tags.
6389 extraParentObjectId;
6393 (oh) ? oh->isShrink : tags.
6394 extraIsShrinkHeader;
6396 /* If it is deleted (unlinked at start also means deleted)
6397 * we treat the file size as being zeroed at this point.
6399 if (parentObjectId ==
6400 YAFFS_OBJECTID_DELETED
6401 || parentObjectId ==
6402 YAFFS_OBJECTID_UNLINKED) {
6408 in->variant.fileVariant.
6409 shrinkSize > thisSize) {
6410 in->variant.fileVariant.
6416 bi->hasShrinkHeader = 1;
6420 /* Use existing - destroy this one. */
6421 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6425 if (!in->valid && in->variantType !=
6426 (oh ? oh->type : tags.extraObjectType))
6427 T(YAFFS_TRACE_ERROR, (
6428 TSTR("yaffs tragedy: Bad object type, "
6429 TCONT("%d != %d, for object %d at chunk ")
6430 TCONT("%d during scan")
6432 oh->type : tags.extraObjectType,
6433 in->variantType, tags.objectId,
6437 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6439 YAFFS_OBJECTID_LOSTNFOUND)) {
6440 /* We only load some info, don't fiddle with directory structure */
6444 in->variantType = oh->type;
6446 in->yst_mode = oh->yst_mode;
6447 #ifdef CONFIG_YAFFS_WINCE
6448 in->win_atime[0] = oh->win_atime[0];
6449 in->win_ctime[0] = oh->win_ctime[0];
6450 in->win_mtime[0] = oh->win_mtime[0];
6451 in->win_atime[1] = oh->win_atime[1];
6452 in->win_ctime[1] = oh->win_ctime[1];
6453 in->win_mtime[1] = oh->win_mtime[1];
6455 in->yst_uid = oh->yst_uid;
6456 in->yst_gid = oh->yst_gid;
6457 in->yst_atime = oh->yst_atime;
6458 in->yst_mtime = oh->yst_mtime;
6459 in->yst_ctime = oh->yst_ctime;
6460 in->yst_rdev = oh->yst_rdev;
6464 in->variantType = tags.extraObjectType;
6468 in->hdrChunk = chunk;
6470 } else if (!in->valid) {
6471 /* we need to load this info */
6474 in->hdrChunk = chunk;
6477 in->variantType = oh->type;
6479 in->yst_mode = oh->yst_mode;
6480 #ifdef CONFIG_YAFFS_WINCE
6481 in->win_atime[0] = oh->win_atime[0];
6482 in->win_ctime[0] = oh->win_ctime[0];
6483 in->win_mtime[0] = oh->win_mtime[0];
6484 in->win_atime[1] = oh->win_atime[1];
6485 in->win_ctime[1] = oh->win_ctime[1];
6486 in->win_mtime[1] = oh->win_mtime[1];
6488 in->yst_uid = oh->yst_uid;
6489 in->yst_gid = oh->yst_gid;
6490 in->yst_atime = oh->yst_atime;
6491 in->yst_mtime = oh->yst_mtime;
6492 in->yst_ctime = oh->yst_ctime;
6493 in->yst_rdev = oh->yst_rdev;
6496 if (oh->shadowsObject > 0)
6497 yaffs_HandleShadowedObject(dev,
6503 yaffs_SetObjectName(in, oh->name);
6505 yaffs_FindOrCreateObjectByNumber
6506 (dev, oh->parentObjectId,
6507 YAFFS_OBJECT_TYPE_DIRECTORY);
6509 fileSize = oh->fileSize;
6510 isShrink = oh->isShrink;
6511 equivalentObjectId = oh->equivalentObjectId;
6514 in->variantType = tags.extraObjectType;
6516 yaffs_FindOrCreateObjectByNumber
6517 (dev, tags.extraParentObjectId,
6518 YAFFS_OBJECT_TYPE_DIRECTORY);
6519 fileSize = tags.extraFileLength;
6520 isShrink = tags.extraIsShrinkHeader;
6521 equivalentObjectId = tags.extraEquivalentObjectId;
6530 /* directory stuff...
6534 if (parent && parent->variantType ==
6535 YAFFS_OBJECT_TYPE_UNKNOWN) {
6536 /* Set up as a directory */
6537 parent->variantType =
6538 YAFFS_OBJECT_TYPE_DIRECTORY;
6539 YINIT_LIST_HEAD(&parent->variant.
6542 } else if (!parent || parent->variantType !=
6543 YAFFS_OBJECT_TYPE_DIRECTORY) {
6544 /* Hoosterman, another problem....
6545 * We're trying to use a non-directory as a directory
6548 T(YAFFS_TRACE_ERROR,
6550 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6552 parent = dev->lostNFoundDir;
6555 yaffs_AddObjectToDirectory(parent, in);
6557 itsUnlinked = (parent == dev->deletedDir) ||
6558 (parent == dev->unlinkedDir);
6561 /* Mark the block as having a shrinkHeader */
6562 bi->hasShrinkHeader = 1;
6565 /* Note re hardlinks.
6566 * Since we might scan a hardlink before its equivalent object is scanned
6567 * we put them all in a list.
6568 * After scanning is complete, we should have all the objects, so we run
6569 * through this list and fix up all the chains.
6572 switch (in->variantType) {
6573 case YAFFS_OBJECT_TYPE_UNKNOWN:
6574 /* Todo got a problem */
6576 case YAFFS_OBJECT_TYPE_FILE:
6578 if (in->variant.fileVariant.
6579 scannedFileSize < fileSize) {
6580 /* This covers the case where the file size is greater
6581 * than where the data is
6582 * This will happen if the file is resized to be larger
6583 * than its current data extents.
6585 in->variant.fileVariant.fileSize = fileSize;
6586 in->variant.fileVariant.scannedFileSize =
6587 in->variant.fileVariant.fileSize;
6591 in->variant.fileVariant.shrinkSize > fileSize) {
6592 in->variant.fileVariant.shrinkSize = fileSize;
6596 case YAFFS_OBJECT_TYPE_HARDLINK:
6598 in->variant.hardLinkVariant.equivalentObjectId =
6600 in->hardLinks.next =
6601 (struct ylist_head *) hardList;
6605 case YAFFS_OBJECT_TYPE_DIRECTORY:
6608 case YAFFS_OBJECT_TYPE_SPECIAL:
6611 case YAFFS_OBJECT_TYPE_SYMLINK:
6613 in->variant.symLinkVariant.alias =
6614 yaffs_CloneString(oh->alias);
6615 if (!in->variant.symLinkVariant.alias)
6625 } /* End of scanning for each chunk */
6627 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6628 /* If we got this far while scanning, then the block is fully allocated. */
6629 state = YAFFS_BLOCK_STATE_FULL;
6632 bi->blockState = state;
6634 /* Now let's see if it was dirty */
6635 if (bi->pagesInUse == 0 &&
6636 !bi->hasShrinkHeader &&
6637 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6638 yaffs_BlockBecameDirty(dev, blk);
6644 YFREE_ALT(blockIndex);
6648 /* Ok, we've done all the scanning.
6649 * Fix up the hard link chains.
6650 * We should now have scanned all the objects, now it's time to add these
6653 yaffs_HardlinkFixup(dev, hardList);
6656 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6662 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6667 /*------------------------------ Directory Functions ----------------------------- */
6669 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6671 struct ylist_head *lh;
6672 yaffs_Object *listObj;
6677 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6682 if (yaffs_SkipVerification(obj->myDev))
6686 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6691 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6692 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6696 /* Iterate through the objects in each hash entry */
6698 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6700 listObj = ylist_entry(lh, yaffs_Object, siblings);
6701 yaffs_VerifyObject(listObj);
6708 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6713 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6715 struct ylist_head *lh;
6716 yaffs_Object *listObj;
6723 if (yaffs_SkipFullVerification(directory->myDev))
6726 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6727 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6731 /* Iterate through the objects in each hash entry */
6733 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6735 listObj = ylist_entry(lh, yaffs_Object, siblings);
6736 if (listObj->parent != directory) {
6737 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6740 yaffs_VerifyObjectInDirectory(listObj);
6746 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6748 yaffs_Device *dev = obj->myDev;
6749 yaffs_Object *parent;
6751 yaffs_VerifyObjectInDirectory(obj);
6752 parent = obj->parent;
6754 yaffs_VerifyDirectory(parent);
6756 if (dev && dev->removeObjectCallback)
6757 dev->removeObjectCallback(obj);
6760 ylist_del_init(&obj->siblings);
6763 yaffs_VerifyDirectory(parent);
6767 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6771 T(YAFFS_TRACE_ALWAYS,
6773 ("tragedy: Trying to add an object to a null pointer directory"
6778 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6779 T(YAFFS_TRACE_ALWAYS,
6781 ("tragedy: Trying to add an object to a non-directory"
6786 if (obj->siblings.prev == NULL) {
6787 /* Not initialised */
6792 yaffs_VerifyDirectory(directory);
6794 yaffs_RemoveObjectFromDirectory(obj);
6798 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6799 obj->parent = directory;
6801 if (directory == obj->myDev->unlinkedDir
6802 || directory == obj->myDev->deletedDir) {
6804 obj->myDev->nUnlinkedFiles++;
6805 obj->renameAllowed = 0;
6808 yaffs_VerifyDirectory(directory);
6809 yaffs_VerifyObjectInDirectory(obj);
6812 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
6817 struct ylist_head *i;
6818 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6827 T(YAFFS_TRACE_ALWAYS,
6829 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6834 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6835 T(YAFFS_TRACE_ALWAYS,
6837 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6841 sum = yaffs_CalcNameSum(name);
6843 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6845 l = ylist_entry(i, yaffs_Object, siblings);
6847 if (l->parent != directory)
6850 yaffs_CheckObjectDetailsLoaded(l);
6852 /* Special case for lost-n-found */
6853 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6854 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6857 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
6858 /* LostnFound chunk called Objxxx
6861 yaffs_GetObjectName(l, buffer,
6862 YAFFS_MAX_NAME_LENGTH);
6863 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0) {
6875 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
6876 int (*fn) (yaffs_Object *))
6878 struct ylist_head *i;
6882 T(YAFFS_TRACE_ALWAYS,
6884 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6889 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6890 T(YAFFS_TRACE_ALWAYS,
6892 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6897 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6899 l = ylist_entry(i, yaffs_Object, siblings);
6911 /* GetEquivalentObject dereferences any hard links to get to the
6915 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
6917 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6918 /* We want the object id of the equivalent object, not this one */
6919 obj = obj->variant.hardLinkVariant.equivalentObject;
6920 yaffs_CheckObjectDetailsLoaded(obj);
6925 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
6927 memset(name, 0, buffSize * sizeof(YCHAR));
6929 yaffs_CheckObjectDetailsLoaded(obj);
6931 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6932 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6933 } else if (obj->hdrChunk <= 0) {
6935 YCHAR numString[20];
6936 YCHAR *x = &numString[19];
6937 unsigned v = obj->objectId;
6941 *x = '0' + (v % 10);
6944 /* make up a name */
6945 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6946 yaffs_strcat(locName, x);
6947 yaffs_strncpy(name, locName, buffSize - 1);
6950 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6951 else if (obj->shortName[0]) {
6952 yaffs_strcpy(name, obj->shortName);
6957 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6959 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6961 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6963 if (obj->hdrChunk > 0) {
6964 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6965 obj->hdrChunk, buffer,
6968 yaffs_strncpy(name, oh->name, buffSize - 1);
6970 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6973 return yaffs_strlen(name);
6976 int yaffs_GetObjectFileLength(yaffs_Object *obj)
6978 /* Dereference any hard linking */
6979 obj = yaffs_GetEquivalentObject(obj);
6981 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6982 return obj->variant.fileVariant.fileSize;
6984 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6985 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6987 /* Only a directory should drop through to here */
6988 return obj->myDev->nDataBytesPerChunk;
6992 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
6995 struct ylist_head *i;
6997 if (!obj->unlinked) {
6998 count++; /* the object itself */
7000 ylist_for_each(i, &obj->hardLinks) {
7001 count++; /* add the hard links; */
7006 int yaffs_GetObjectInode(yaffs_Object *obj)
7008 obj = yaffs_GetEquivalentObject(obj);
7010 return obj->objectId;
7013 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7015 obj = yaffs_GetEquivalentObject(obj);
7017 switch (obj->variantType) {
7018 case YAFFS_OBJECT_TYPE_FILE:
7021 case YAFFS_OBJECT_TYPE_DIRECTORY:
7024 case YAFFS_OBJECT_TYPE_SYMLINK:
7027 case YAFFS_OBJECT_TYPE_HARDLINK:
7030 case YAFFS_OBJECT_TYPE_SPECIAL:
7031 if (S_ISFIFO(obj->yst_mode))
7033 if (S_ISCHR(obj->yst_mode))
7035 if (S_ISBLK(obj->yst_mode))
7037 if (S_ISSOCK(obj->yst_mode))
7045 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7047 obj = yaffs_GetEquivalentObject(obj);
7048 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7049 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7051 return yaffs_CloneString(_Y(""));
7055 #ifndef CONFIG_YAFFS_WINCE
7057 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7059 unsigned int valid = attr->ia_valid;
7061 if (valid & ATTR_MODE)
7062 obj->yst_mode = attr->ia_mode;
7063 if (valid & ATTR_UID)
7064 obj->yst_uid = attr->ia_uid;
7065 if (valid & ATTR_GID)
7066 obj->yst_gid = attr->ia_gid;
7068 if (valid & ATTR_ATIME)
7069 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7070 if (valid & ATTR_CTIME)
7071 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7072 if (valid & ATTR_MTIME)
7073 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7075 if (valid & ATTR_SIZE)
7076 yaffs_ResizeFile(obj, attr->ia_size);
7078 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7083 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7085 unsigned int valid = 0;
7087 attr->ia_mode = obj->yst_mode;
7089 attr->ia_uid = obj->yst_uid;
7091 attr->ia_gid = obj->yst_gid;
7094 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7095 valid |= ATTR_ATIME;
7096 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7097 valid |= ATTR_CTIME;
7098 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7099 valid |= ATTR_MTIME;
7101 attr->ia_size = yaffs_GetFileSize(obj);
7104 attr->ia_valid = valid;
7112 int yaffs_DumpObject(yaffs_Object *obj)
7116 yaffs_GetObjectName(obj, name, 256);
7118 T(YAFFS_TRACE_ALWAYS,
7120 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7121 " chunk %d type %d size %d\n"
7122 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7123 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7124 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7130 /*---------------------------- Initialisation code -------------------------------------- */
7132 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7135 /* Common functions, gotta have */
7136 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7139 #ifdef CONFIG_YAFFS_YAFFS2
7141 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7142 if (dev->writeChunkWithTagsToNAND &&
7143 dev->readChunkWithTagsFromNAND &&
7144 !dev->writeChunkToNAND &&
7145 !dev->readChunkFromNAND &&
7146 dev->markNANDBlockBad && dev->queryNANDBlock)
7150 /* Can use the "spare" style interface for yaffs1 */
7151 if (!dev->isYaffs2 &&
7152 !dev->writeChunkWithTagsToNAND &&
7153 !dev->readChunkWithTagsFromNAND &&
7154 dev->writeChunkToNAND &&
7155 dev->readChunkFromNAND &&
7156 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7163 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7165 /* Initialise the unlinked, deleted, root and lost and found directories */
7167 dev->lostNFoundDir = dev->rootDir = NULL;
7168 dev->unlinkedDir = dev->deletedDir = NULL;
7171 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7174 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7177 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7178 YAFFS_ROOT_MODE | S_IFDIR);
7179 dev->lostNFoundDir =
7180 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7181 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7183 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7184 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7191 int yaffs_GutsInitialise(yaffs_Device *dev)
7193 int init_failed = 0;
7197 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7199 /* Check stuff that must be set */
7202 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7206 dev->internalStartBlock = dev->startBlock;
7207 dev->internalEndBlock = dev->endBlock;
7208 dev->blockOffset = 0;
7209 dev->chunkOffset = 0;
7210 dev->nFreeChunks = 0;
7214 if (dev->startBlock == 0) {
7215 dev->internalStartBlock = dev->startBlock + 1;
7216 dev->internalEndBlock = dev->endBlock + 1;
7217 dev->blockOffset = 1;
7218 dev->chunkOffset = dev->nChunksPerBlock;
7221 /* Check geometry parameters. */
7223 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7224 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7225 (dev->inbandTags && !dev->isYaffs2) ||
7226 dev->nChunksPerBlock < 2 ||
7227 dev->nReservedBlocks < 2 ||
7228 dev->internalStartBlock <= 0 ||
7229 dev->internalEndBlock <= 0 ||
7230 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) { /* otherwise it is too small */
7231 T(YAFFS_TRACE_ALWAYS,
7233 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7234 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7238 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7239 T(YAFFS_TRACE_ALWAYS,
7240 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7244 /* Sort out space for inband tags, if required */
7245 if (dev->inbandTags)
7246 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7248 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7250 /* Got the right mix of functions? */
7251 if (!yaffs_CheckDevFunctions(dev)) {
7252 /* Function missing */
7253 T(YAFFS_TRACE_ALWAYS,
7255 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7260 /* This is really a compilation check. */
7261 if (!yaffs_CheckStructures()) {
7262 T(YAFFS_TRACE_ALWAYS,
7263 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7267 if (dev->isMounted) {
7268 T(YAFFS_TRACE_ALWAYS,
7269 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7273 /* Finished with most checks. One or two more checks happen later on too. */
7277 /* OK now calculate a few things for the device */
7280 * Calculate all the chunk size manipulation numbers:
7282 x = dev->nDataBytesPerChunk;
7283 /* We always use dev->chunkShift and dev->chunkDiv */
7284 dev->chunkShift = Shifts(x);
7285 x >>= dev->chunkShift;
7287 /* We only use chunk mask if chunkDiv is 1 */
7288 dev->chunkMask = (1<<dev->chunkShift) - 1;
7291 * Calculate chunkGroupBits.
7292 * We need to find the next power of 2 > than internalEndBlock
7295 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7299 /* Set up tnode width if wide tnodes are enabled. */
7300 if (!dev->wideTnodesDisabled) {
7301 /* bits must be even so that we end up with 32-bit words */
7305 dev->tnodeWidth = 16;
7307 dev->tnodeWidth = bits;
7309 dev->tnodeWidth = 16;
7311 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7313 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7314 * so if the bitwidth of the
7315 * chunk range we're using is greater than 16 we need
7316 * to figure out chunk shift and chunkGroupSize
7319 if (bits <= dev->tnodeWidth)
7320 dev->chunkGroupBits = 0;
7322 dev->chunkGroupBits = bits - dev->tnodeWidth;
7325 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7327 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7328 /* We have a problem because the soft delete won't work if
7329 * the chunk group size > chunks per block.
7330 * This can be remedied by using larger "virtual blocks".
7332 T(YAFFS_TRACE_ALWAYS,
7333 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7338 /* OK, we've finished verifying the device, lets continue with initialisation */
7340 /* More device initialisation */
7341 dev->garbageCollections = 0;
7342 dev->passiveGarbageCollections = 0;
7343 dev->currentDirtyChecker = 0;
7344 dev->bufferedBlock = -1;
7345 dev->doingBufferedBlockRewrite = 0;
7346 dev->nDeletedFiles = 0;
7347 dev->nBackgroundDeletions = 0;
7348 dev->nUnlinkedFiles = 0;
7350 dev->eccUnfixed = 0;
7351 dev->tagsEccFixed = 0;
7352 dev->tagsEccUnfixed = 0;
7353 dev->nErasureFailures = 0;
7354 dev->nErasedBlocks = 0;
7356 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7358 /* Initialise temporary buffers and caches. */
7359 if (!yaffs_InitialiseTempBuffers(dev))
7362 dev->srCache = NULL;
7363 dev->gcCleanupList = NULL;
7367 dev->nShortOpCaches > 0) {
7370 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7372 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7373 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7376 dev->srCache = YMALLOC(srCacheBytes);
7378 buf = (__u8 *) dev->srCache;
7381 memset(dev->srCache, 0, srCacheBytes);
7383 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7384 dev->srCache[i].object = NULL;
7385 dev->srCache[i].lastUse = 0;
7386 dev->srCache[i].dirty = 0;
7387 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7398 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7399 if (!dev->gcCleanupList)
7403 if (dev->isYaffs2) {
7404 dev->useHeaderFileSize = 1;
7406 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7409 yaffs_InitialiseTnodes(dev);
7410 yaffs_InitialiseObjects(dev);
7412 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7417 /* Now scan the flash. */
7418 if (dev->isYaffs2) {
7419 if (yaffs_CheckpointRestore(dev)) {
7420 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7421 T(YAFFS_TRACE_ALWAYS,
7422 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7425 /* Clean up the mess caused by an aborted checkpoint load
7426 * and scan backwards.
7428 yaffs_DeinitialiseBlocks(dev);
7429 yaffs_DeinitialiseTnodes(dev);
7430 yaffs_DeinitialiseObjects(dev);
7433 dev->nErasedBlocks = 0;
7434 dev->nFreeChunks = 0;
7435 dev->allocationBlock = -1;
7436 dev->allocationPage = -1;
7437 dev->nDeletedFiles = 0;
7438 dev->nUnlinkedFiles = 0;
7439 dev->nBackgroundDeletions = 0;
7440 dev->oldestDirtySequence = 0;
7442 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7445 yaffs_InitialiseTnodes(dev);
7446 yaffs_InitialiseObjects(dev);
7448 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7451 if (!init_failed && !yaffs_ScanBackwards(dev))
7454 } else if (!yaffs_Scan(dev))
7457 yaffs_StripDeletedObjects(dev);
7461 /* Clean up the mess */
7462 T(YAFFS_TRACE_TRACING,
7463 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7465 yaffs_Deinitialise(dev);
7469 /* Zero out stats */
7470 dev->nPageReads = 0;
7471 dev->nPageWrites = 0;
7472 dev->nBlockErasures = 0;
7474 dev->nRetriedWrites = 0;
7476 dev->nRetiredBlocks = 0;
7478 yaffs_VerifyFreeChunks(dev);
7479 yaffs_VerifyBlocks(dev);
7482 T(YAFFS_TRACE_TRACING,
7483 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7488 void yaffs_Deinitialise(yaffs_Device *dev)
7490 if (dev->isMounted) {
7493 yaffs_DeinitialiseBlocks(dev);
7494 yaffs_DeinitialiseTnodes(dev);
7495 yaffs_DeinitialiseObjects(dev);
7496 if (dev->nShortOpCaches > 0 &&
7499 for (i = 0; i < dev->nShortOpCaches; i++) {
7500 if (dev->srCache[i].data)
7501 YFREE(dev->srCache[i].data);
7502 dev->srCache[i].data = NULL;
7505 YFREE(dev->srCache);
7506 dev->srCache = NULL;
7509 YFREE(dev->gcCleanupList);
7511 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7512 YFREE(dev->tempBuffer[i].buffer);
7518 if (dev->deinitialiseNAND)
7519 dev->deinitialiseNAND(dev);
7523 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7528 yaffs_BlockInfo *blk;
7530 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7532 blk = yaffs_GetBlockInfo(dev, b);
7534 switch (blk->blockState) {
7535 case YAFFS_BLOCK_STATE_EMPTY:
7536 case YAFFS_BLOCK_STATE_ALLOCATING:
7537 case YAFFS_BLOCK_STATE_COLLECTING:
7538 case YAFFS_BLOCK_STATE_FULL:
7540 (dev->nChunksPerBlock - blk->pagesInUse +
7541 blk->softDeletions);
7551 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7553 /* This is what we report to the outside world */
7556 int nDirtyCacheChunks;
7557 int blocksForCheckpoint;
7560 nFree = dev->nFreeChunks;
7562 nFree = yaffs_CountFreeChunks(dev);
7565 nFree += dev->nDeletedFiles;
7567 /* Now count the number of dirty chunks in the cache and subtract those */
7571 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7572 if (dev->srCache[i].dirty)
7573 nDirtyCacheChunks++;
7577 nFree -= nDirtyCacheChunks;
7579 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7581 /* Now we figure out how much to reserve for the checkpoint and report that... */
7582 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7583 if (blocksForCheckpoint < 0)
7584 blocksForCheckpoint = 0;
7586 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7595 static int yaffs_freeVerificationFailures;
7597 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7602 if (yaffs_SkipVerification(dev))
7605 counted = yaffs_CountFreeChunks(dev);
7607 difference = dev->nFreeChunks - counted;
7610 T(YAFFS_TRACE_ALWAYS,
7611 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7612 dev->nFreeChunks, counted, difference));
7613 yaffs_freeVerificationFailures++;
7617 /*---------------------------------------- YAFFS test code ----------------------*/
7619 #define yaffs_CheckStruct(structure, syze, name) \
7621 if (sizeof(structure) != syze) { \
7622 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7623 name, syze, sizeof(structure))); \
7624 return YAFFS_FAIL; \
7628 static int yaffs_CheckStructures(void)
7630 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7631 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7632 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7633 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7634 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7636 #ifndef CONFIG_YAFFS_WINCE
7637 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");